-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheoc.py
1727 lines (1499 loc) · 61.8 KB
/
eoc.py
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Mailing list manager.
This is a simple mailing list manager that mimicks the ezmlm-idx mail
address commands. See manual page for more information.
"""
VERSION = "1.2.6"
PLUGIN_INTERFACE_VERSION = "1"
import getopt
import md5
import os
import shutil
import smtplib
import string
import sys
import time
import ConfigParser
try:
import email.Header
have_email_module = 1
except ImportError:
have_email_module = 0
import imp
import qmqp
# The following values will be overriden by "make install".
TEMPLATE_DIRS = ["./templates"]
DOTDIR = "dot-eoc"
class EocException(Exception):
def __init__(self, arg=None):
self.msg = repr(arg)
def __str__(self):
return self.msg
class UnknownList(EocException):
def __init__(self, list_name):
self.msg = "%s is not a known mailing list" % list_name
class BadCommandAddress(EocException):
def __init__(self, address):
self.msg = "%s is not a valid command address" % address
class BadSignature(EocException):
def __init__(self, address):
self.msg = "address %s has an invalid digital signature" % address
class ListExists(EocException):
def __init__(self, list_name):
self.msg = "Mailing list %s alreadys exists" % list_name
class ListDoesNotExist(EocException):
def __init__(self, list_name):
self.msg = "Mailing list %s does not exist" % list_name
class MissingEnvironmentVariable(EocException):
def __init__(self, name):
self.msg = "Environment variable %s does not exist" % name
class MissingTemplate(EocException):
def __init__(self, template):
self.msg = "Template %s does not exit" % template
# Names of commands EoC recognizes in e-mail addresses.
SIMPLE_COMMANDS = ["help", "list", "owner", "setlist", "setlistsilently", "ignore"]
SUB_COMMANDS = ["subscribe", "unsubscribe"]
HASH_COMMANDS = ["subyes", "subapprove", "subreject", "unsubyes",
"bounce", "probe", "approve", "reject", "setlistyes",
"setlistsilentyes"]
COMMANDS = SIMPLE_COMMANDS + SUB_COMMANDS + HASH_COMMANDS
def md5sum_as_hex(s):
return md5.new(s).hexdigest()
def forkexec(argv, text):
"""Run a command (given as argv array) and write text to its stdin"""
(r, w) = os.pipe()
pid = os.fork()
if pid == -1:
raise Exception("fork failed")
elif pid == 0:
os.dup2(r, 0)
os.close(r)
os.close(w)
fd = os.open("/dev/null", os.O_RDWR)
os.dup2(fd, 1)
os.dup2(fd, 2)
os.execvp(argv[0], argv)
sys.exit(1)
else:
os.close(r)
os.write(w, text)
os.close(w)
(pid2, exit) = os.waitpid(pid, 0)
if pid != pid2:
raise Exception("os.waitpid for %d returned for %d" % (pid, pid2))
if exit != 0:
raise Exception("subprocess failed, exit=0x%x" % exit)
return exit
environ = None
def set_environ(new_environ):
global environ
environ = new_environ
def get_from_environ(key):
global environ
if environ:
env = environ
else:
env = os.environ
if env.has_key(key):
return env[key].lower()
raise MissingEnvironmentVariable(key)
class AddressParser:
"""A parser for incoming e-mail addresses."""
def __init__(self, lists):
self.set_lists(lists)
self.set_skip_prefix(None)
self.set_forced_domain(None)
def set_lists(self, lists):
"""Set the list of canonical list names we should know about."""
self.lists = lists
def set_skip_prefix(self, skip_prefix):
"""Set the prefix to be removed from an address."""
self.skip_prefix = skip_prefix
def set_forced_domain(self, forced_domain):
"""Set the domain part we should force the address to have."""
self.forced_domain = forced_domain
def clean(self, address):
"""Remove cruft from the address and convert the rest to lower case."""
if self.skip_prefix:
n = self.skip_prefix and len(self.skip_prefix)
if address[:n] == self.skip_prefix:
address = address[n:]
if self.forced_domain:
parts = address.split("@", 1)
address = "%s@%s" % (parts[0], self.forced_domain)
return address.lower()
def split_address(self, address):
"""Split an address to a local part and a domain."""
parts = address.lower().split("@", 1)
if len(parts) != 2:
return (address, "")
else:
return parts
# Does an address refer to a list? If not, return None, else return a list
# of additional parts (separated by hyphens) in the address. Note that []
# is not the same as None.
def additional_address_parts(self, address, listname):
addr_local, addr_domain = self.split_address(address)
list_local, list_domain = self.split_address(listname)
if addr_domain != list_domain:
return None
if addr_local.lower() == list_local.lower():
return []
n = len(list_local)
if addr_local[:n] != list_local or addr_local[n] != "-":
return None
return addr_local[n+1:].split("-")
# Parse an address we have received that identifies a list we manage.
# The address may contain command and signature parts. Return the name
# of the list, and a sequence of the additional parts (split at hyphens).
# Raise exceptions for errors. Note that the command will be valid, but
# cryptographic signatures in the address is not checked.
def parse(self, address):
address = self.clean(address)
for listname in self.lists:
parts = self.additional_address_parts(address, listname)
if parts == None:
pass
elif parts == []:
return listname, parts
elif parts[0] in HASH_COMMANDS:
if len(parts) != 3:
raise BadCommandAddress(address)
return listname, parts
elif parts[0] in COMMANDS:
return listname, parts
raise UnknownList(address)
class MailingListManager:
def __init__(self, dotdir, sendmail="/usr/sbin/sendmail", lists=[],
smtp_server=None, qmqp_server=None):
self.dotdir = dotdir
self.sendmail = sendmail
self.smtp_server = smtp_server
self.qmqp_server = qmqp_server
self.make_dotdir()
self.secret = self.make_and_read_secret()
if not lists:
lists = filter(lambda s: "@" in s, os.listdir(dotdir))
self.set_lists(lists)
self.simple_commands = ["help", "list", "owner", "setlist",
"setlistsilently", "ignore"]
self.sub_commands = ["subscribe", "unsubscribe"]
self.hash_commands = ["subyes", "subapprove", "subreject", "unsubyes",
"bounce", "probe", "approve", "reject",
"setlistyes", "setlistsilentyes"]
self.commands = self.simple_commands + self.sub_commands + \
self.hash_commands
self.environ = None
self.load_plugins()
# Create the dot directory for us, if it doesn't exist already.
def make_dotdir(self):
if not os.path.isdir(self.dotdir):
os.makedirs(self.dotdir, 0700)
# Create the "secret" file, with a random value used as cookie for
# verification addresses.
def make_and_read_secret(self):
secret_name = os.path.join(self.dotdir, "secret")
if not os.path.isfile(secret_name):
f = open("/dev/urandom", "r")
secret = f.read(32)
f.close()
f = open(secret_name, "w")
f.write(secret)
f.close()
else:
f = open(secret_name, "r")
secret = f.read()
f.close()
return secret
# Load the plugins from DOTDIR/plugins/*.py.
def load_plugins(self):
self.plugins = []
dirname = os.path.join(DOTDIR, "plugins")
try:
plugins = os.listdir(dirname)
except OSError:
return
plugins.sort()
plugins = map(os.path.splitext, plugins)
plugins = filter(lambda p: p[1] == ".py", plugins)
plugins = map(lambda p: p[0], plugins)
for name in plugins:
pathname = os.path.join(dirname, name + ".py")
f = open(pathname, "r")
module = imp.load_module(name, f, pathname,
(".py", "r", imp.PY_SOURCE))
f.close()
if module.PLUGIN_INTERFACE_VERSION == PLUGIN_INTERFACE_VERSION:
self.plugins.append(module)
# Call function named funcname (a string) in all plugins, giving as
# arguments all the remaining arguments preceded by ml. Return value
# of each function is the new list of arguments to the next function.
# Return value of this function is the return value of the last function.
def call_plugins(self, funcname, list, *args):
for plugin in self.plugins:
if plugin.__dict__.has_key(funcname):
args = apply(plugin.__dict__[funcname], (list,) + args)
if type(args) != type((0,)):
args = (args,)
return args
# Set the list of listnames. The list of lists needs to be sorted in
# length order so that test@example.com is matched before
# test-list@example.com
def set_lists(self, lists):
temp = map(lambda s: (len(s), s), lists)
temp.sort()
self.lists = map(lambda t: t[1], temp)
# Return the list of listnames.
def get_lists(self):
return self.lists
# Decode an address that has been encoded to be part of a local part.
def decode_address(self, parts):
return string.join(string.join(parts, "-").split("="), "@")
# Is local_part@domain an existing list?
def is_list_name(self, local_part, domain):
return ("%s@%s" % (local_part, domain)) in self.lists
# Compute the verification checksum for an address.
def compute_hash(self, address):
return md5sum_as_hex(address + self.secret)
# Is the verification signature in a parsed address bad? If so, return true,
# otherwise return false.
def signature_is_bad(self, dict, hash):
local_part, domain = dict["name"].split("@")
address = "%s-%s-%s@%s" % (local_part, dict["command"], dict["id"],
domain)
correct = self.compute_hash(address)
return correct != hash
# Parse a command address we have received and check its validity
# (including signature, if any). Return a dictionary with keys
# "command", "sender" (address that was encoded into address, if
# any), "id" (group ID).
def parse_recipient_address(self, address, skip_prefix, forced_domain):
ap = AddressParser(self.get_lists())
ap.set_lists(self.get_lists())
ap.set_skip_prefix(skip_prefix)
ap.set_forced_domain(forced_domain)
listname, parts = ap.parse(address)
dict = { "name": listname }
if parts == []:
dict["command"] = "post"
else:
command, args = parts[0], parts[1:]
dict["command"] = command
if command in SUB_COMMANDS:
dict["sender"] = self.decode_address(args)
elif command in HASH_COMMANDS:
dict["id"] = args[0]
hash = args[1]
if self.signature_is_bad(dict, hash):
raise BadSignature(address)
return dict
# Does an address refer to a mailing list?
def is_list(self, name, skip_prefix=None, domain=None):
try:
self.parse_recipient_address(name, skip_prefix, domain)
except BadCommandAddress:
return 0
except BadSignature:
return 0
except UnknownList:
return 0
return 1
# Create a new list and return it.
def create_list(self, name):
if self.is_list(name):
raise ListExists(name)
self.set_lists(self.lists + [name])
return MailingList(self, name)
# Open an existing list.
def open_list(self, name):
if self.is_list(name):
return self.open_list_exact(name)
else:
x = name + "@"
for list in self.lists:
if list[:len(x)] == x:
return self.open_list_exact(list)
raise ListDoesNotExist(name)
def open_list_exact(self, name):
for list in self.get_lists():
if list.lower() == name.lower():
return MailingList(self, list)
raise ListDoesNotExist(name)
# Process an incoming message.
def incoming_message(self, skip_prefix, domain, moderate, post):
debug("Processing incoming message.")
debug("$SENDER = <%s>" % get_from_environ("SENDER"))
debug("$RECIPIENT = <%s>" % get_from_environ("RECIPIENT"))
dict = self.parse_recipient_address(get_from_environ("RECIPIENT"),
skip_prefix,
domain)
dict["force-moderation"] = moderate
dict["force-posting"] = post
debug("List is <%(name)s>, command is <%(command)s>." % dict)
list = self.open_list_exact(dict["name"])
list.obey(dict)
# Clean up bouncing address and do other janitorial work for all lists.
def cleaning_woman(self, send_mail=None):
now = time.time()
for listname in self.lists:
list = self.open_list_exact(listname)
if send_mail:
list.send_mail = send_mail
list.cleaning_woman(now)
# Send a mail to the desired recipients.
def send_mail(self, envelope_sender, recipients, text):
debug("send_mail:\n sender=%s\n recipients=%s\n text=\n %s" %
(envelope_sender, str(recipients),
"\n ".join(text[:text.find("\n\n")].split("\n"))))
if recipients:
if self.smtp_server:
try:
smtp = smtplib.SMTP(self.smtp_server)
smtp.sendmail(envelope_sender, recipients, text)
smtp.quit()
except:
error("Error sending SMTP mail, mail probably not sent")
sys.exit(1)
elif self.qmqp_server:
try:
q = qmqp.QMQP(self.qmqp_server)
q.sendmail(envelope_sender, recipients, text)
q.quit()
except:
error("Error sending QMQP mail, mail probably not sent")
sys.exit(1)
else:
status = forkexec([self.sendmail, "-oi", "-f",
envelope_sender] + recipients, text)
if status:
error("%s returned %s, mail sending probably failed" %
(self.sendmail, status))
sys.exit((status >> 8) & 0xff)
else:
debug("send_mail: no recipients, not sending")
class MailingList:
posting_opts = ["auto", "free", "moderated"]
def __init__(self, mlm, name):
self.mlm = mlm
self.name = name
self.cp = ConfigParser.ConfigParser()
self.cp.add_section("list")
self.cp.set("list", "owners", "")
self.cp.set("list", "moderators", "")
self.cp.set("list", "subscription", "free")
self.cp.set("list", "posting", "free")
self.cp.set("list", "archived", "no")
self.cp.set("list", "mail-on-subscription-changes", "no")
self.cp.set("list", "mail-on-forced-unsubscribe", "no")
self.cp.set("list", "ignore-bounce", "no")
self.cp.set("list", "language", "")
self.cp.set("list", "pristine-headers", "")
self.dirname = os.path.join(self.mlm.dotdir, name)
self.make_listdir()
self.cp.read(self.mkname("config"))
self.subscribers = SubscriberDatabase(self.dirname, "subscribers")
self.moderation_box = MessageBox(self.dirname, "moderation-box")
self.subscription_box = MessageBox(self.dirname, "subscription-box")
self.bounce_box = MessageBox(self.dirname, "bounce-box")
def make_listdir(self):
if not os.path.isdir(self.dirname):
os.mkdir(self.dirname, 0700)
self.save_config()
f = open(self.mkname("subscribers"), "w")
f.close()
def mkname(self, relative):
return os.path.join(self.dirname, relative)
def save_config(self):
f = open(self.mkname("config"), "w")
self.cp.write(f)
f.close()
def read_stdin(self):
data = sys.stdin.read()
# Convert CRLF to plain LF
data = "\n".join(data.split("\r\n"))
# Skip Unix mbox "From " mail start indicator
if data[:5] == "From ":
data = string.split(data, "\n", 1)[1]
return data
def invent_boundary(self):
return "%s/%s" % (md5sum_as_hex(str(time.time())),
md5sum_as_hex(self.name))
def command_address(self, command):
local_part, domain = self.name.split("@")
return "%s-%s@%s" % (local_part, command, domain)
def signed_address(self, command, id):
unsigned = self.command_address("%s-%s" % (command, id))
hash = self.mlm.compute_hash(unsigned)
return self.command_address("%s-%s-%s" % (command, id, hash))
def ignore(self):
return self.command_address("ignore")
def nice_7bit(self, str):
for c in str:
if (ord(c) < 32 and not c.isspace()) or ord(c) >= 127:
return False
return True
def mime_encode_headers(self, text):
try:
headers, body = text.split("\n\n", 1)
list = []
for line in headers.split("\n"):
if line[0].isspace():
list[-1] += line
else:
list.append(line)
headers = []
for header in list:
if self.nice_7bit(header):
headers.append(header)
else:
if ": " in header:
name, content = header.split(": ", 1)
else:
name, content = header.split(":", 1)
hdr = email.Header.Header(content, "utf-8")
headers.append(name + ": " + hdr.encode())
return "\n".join(headers) + "\n\n" + body
except:
info("Cannot MIME encode header, using original ones, sorry")
return text
def template(self, template_name, dict):
lang = self.cp.get("list", "language")
if lang:
template_name_lang = template_name + "." + lang
else:
template_name_lang = template_name
if not dict.has_key("list"):
dict["list"] = self.name
dict["local"], dict["domain"] = self.name.split("@")
if not dict.has_key("list"):
dict["list"] = self.name
for dir in [os.path.join(self.dirname, "templates")] + TEMPLATE_DIRS:
pathname = os.path.join(dir, template_name_lang)
if not os.path.exists(pathname):
pathname = os.path.join(dir, template_name)
if os.path.exists(pathname):
f = open(pathname, "r")
data = f.read()
f.close()
return data % dict
raise MissingTemplate(template_name)
def send_template(self, envelope_sender, sender, recipients,
template_name, dict):
dict["From"] = "EoC <%s>" % sender
dict["To"] = string.join(recipients, ", ")
text = self.template(template_name, dict)
if not text:
return
if self.cp.get("list", "pristine-headers") != "yes":
text = self.mime_encode_headers(text)
self.mlm.send_mail(envelope_sender, recipients, text)
def send_info_message(self, recipients, template_name, dict):
self.send_template(self.command_address("ignore"),
self.command_address("help"),
recipients,
template_name,
dict)
def owners(self):
return self.cp.get("list", "owners").split()
def moderators(self):
return self.cp.get("list", "moderators").split()
def is_list_owner(self, address):
return address in self.owners()
def obey_help(self):
self.send_info_message([get_from_environ("SENDER")], "help", {})
def obey_list(self):
recipient = get_from_environ("SENDER")
if self.is_list_owner(recipient):
addr_list = self.subscribers.get_all()
addr_text = string.join(addr_list, "\n")
self.send_info_message([recipient], "list",
{
"addresses": addr_text,
"count": len(addr_list),
})
else:
self.send_info_message([recipient], "list-sorry", {})
def obey_setlist(self, origmail):
recipient = get_from_environ("SENDER")
if self.is_list_owner(recipient):
id = self.moderation_box.add(recipient, origmail)
if self.parse_setlist_addresses(origmail) == None:
self.send_bad_addresses_in_setlist(id)
self.moderation_box.remove(id)
else:
confirm = self.signed_address("setlistyes", id)
self.send_info_message(self.owners(), "setlist-confirm",
{
"confirm": confirm,
"origmail": origmail,
"boundary": self.invent_boundary(),
})
else:
self.send_info_message([recipient], "setlist-sorry", {})
def obey_setlistsilently(self, origmail):
recipient = get_from_environ("SENDER")
if self.is_list_owner(recipient):
id = self.moderation_box.add(recipient, origmail)
if self.parse_setlist_addresses(origmail) == None:
self.send_bad_addresses_in_setlist(id)
self.moderation_box.remove(id)
else:
confirm = self.signed_address("setlistsilentyes", id)
self.send_info_message(self.owners(), "setlist-confirm",
{
"confirm": confirm,
"origmail": origmail,
"boundary": self.invent_boundary(),
})
else:
self.send_info_message([recipient], "setlist-sorry", {})
def parse_setlist_addresses(self, text):
body = text.split("\n\n", 1)[1]
lines = body.split("\n")
lines = filter(lambda line: line != "", lines)
badlines = filter(lambda line: "@" not in line, lines)
if badlines:
return None
else:
return lines
def send_bad_addresses_in_setlist(self, id):
addr = self.moderation_box.get_address(id)
origmail = self.moderation_box.get(id)
self.send_info_message([addr], "setlist-badlist",
{
"origmail": origmail,
"boundary": self.invent_boundary(),
})
def obey_setlistyes(self, dict):
if self.moderation_box.has(dict["id"]):
text = self.moderation_box.get(dict["id"])
addresses = self.parse_setlist_addresses(text)
if addresses == None:
self.send_bad_addresses_in_setlist(id)
else:
removed_subscribers = []
self.subscribers.lock()
old = self.subscribers.get_all()
for address in old:
if address.lower() not in map(string.lower, addresses):
self.subscribers.remove(address)
removed_subscribers.append(address)
else:
for x in addresses:
if x.lower() == address.lower():
addresses.remove(x)
self.subscribers.add_many(addresses)
self.subscribers.save()
for recipient in addresses:
self.send_info_message([recipient], "sub-welcome", {})
for recipient in removed_subscribers:
self.send_info_message([recipient], "unsub-goodbye", {})
self.send_info_message(self.owners(), "setlist-done", {})
self.moderation_box.remove(dict["id"])
def obey_setlistsilentyes(self, dict):
if self.moderation_box.has(dict["id"]):
text = self.moderation_box.get(dict["id"])
addresses = self.parse_setlist_addresses(text)
if addresses == None:
self.send_bad_addresses_in_setlist(id)
else:
self.subscribers.lock()
old = self.subscribers.get_all()
for address in old:
if address not in addresses:
self.subscribers.remove(address)
else:
addresses.remove(address)
self.subscribers.add_many(addresses)
self.subscribers.save()
self.send_info_message(self.owners(), "setlist-done", {})
self.moderation_box.remove(dict["id"])
def obey_owner(self, text):
sender = get_from_environ("SENDER")
recipients = self.cp.get("list", "owners").split()
self.mlm.send_mail(sender, recipients, text)
def obey_subscribe_or_unsubscribe(self, dict, template_name, command,
origmail):
requester = get_from_environ("SENDER")
subscriber = dict["sender"]
if not subscriber:
subscriber = requester
if subscriber.find("@") == -1:
info("Trying to (un)subscribe address without @: %s" % subscriber)
return
if self.cp.get("list", "ignore-bounce") == "yes":
info("Will not (un)subscribe address: %s from static list" %subscriber)
return
if requester in self.owners():
confirmers = self.owners()
else:
confirmers = [subscriber]
id = self.subscription_box.add(subscriber, origmail)
confirm = self.signed_address(command, id)
self.send_info_message(confirmers, template_name,
{
"confirm": confirm,
"origmail": origmail,
"boundary": self.invent_boundary(),
})
def obey_subscribe(self, dict, origmail):
self.obey_subscribe_or_unsubscribe(dict, "sub-confirm", "subyes",
origmail)
def obey_unsubscribe(self, dict, origmail):
self.obey_subscribe_or_unsubscribe(dict, "unsub-confirm", "unsubyes",
origmail)
def obey_subyes(self, dict):
if self.subscription_box.has(dict["id"]):
if self.cp.get("list", "subscription") == "free":
recipient = self.subscription_box.get_address(dict["id"])
self.subscribers.lock()
self.subscribers.add(recipient)
self.subscribers.save()
sender = self.command_address("help")
self.send_template(self.ignore(), sender, [recipient],
"sub-welcome", {})
self.subscription_box.remove(dict["id"])
if self.cp.get("list", "mail-on-subscription-changes")=="yes":
self.send_info_message(self.owners(),
"sub-owner-notification",
{
"address": recipient,
})
else:
recipients = self.cp.get("list", "owners").split()
confirm = self.signed_address("subapprove", dict["id"])
deny = self.signed_address("subreject", dict["id"])
subscriber = self.subscription_box.get_address(dict["id"])
origmail = self.subscription_box.get(dict["id"])
self.send_template(self.ignore(), deny, recipients,
"sub-moderate",
{
"confirm": confirm,
"deny": deny,
"subscriber": subscriber,
"origmail": origmail,
"boundary": self.invent_boundary(),
})
recipient = self.subscription_box.get_address(dict["id"])
self.send_info_message([recipient], "sub-wait", {})
def obey_subapprove(self, dict):
if self.subscription_box.has(dict["id"]):
recipient = self.subscription_box.get_address(dict["id"])
self.subscribers.lock()
self.subscribers.add(recipient)
self.subscribers.save()
self.send_info_message([recipient], "sub-welcome", {})
self.subscription_box.remove(dict["id"])
if self.cp.get("list", "mail-on-subscription-changes")=="yes":
self.send_info_message(self.owners(), "sub-owner-notification",
{
"address": recipient,
})
def obey_subreject(self, dict):
if self.subscription_box.has(dict["id"]):
recipient = self.subscription_box.get_address(dict["id"])
self.send_info_message([recipient], "sub-reject", {})
self.subscription_box.remove(dict["id"])
def obey_unsubyes(self, dict):
if self.subscription_box.has(dict["id"]):
recipient = self.subscription_box.get_address(dict["id"])
self.subscribers.lock()
self.subscribers.remove(recipient)
self.subscribers.save()
self.send_info_message([recipient], "unsub-goodbye", {})
self.subscription_box.remove(dict["id"])
if self.cp.get("list", "mail-on-subscription-changes")=="yes":
self.send_info_message(self.owners(),
"unsub-owner-notification",
{
"address": recipient,
})
def store_into_archive(self, text):
if self.cp.get("list", "archived") == "yes":
archdir = os.path.join(self.dirname, "archive")
if not os.path.exists(archdir):
os.mkdir(archdir, 0700)
id = md5sum_as_hex(text)
f = open(os.path.join(archdir, id), "w")
f.write(text)
f.close()
def list_headers(self):
local, domain = self.name.split("@")
list = []
list.append("List-Id: <%s.%s>" % (local, domain))
list.append("List-Help: <mailto:%s-help@%s>" % (local, domain))
list.append("List-Unsubscribe: <mailto:%s-unsubscribe@%s>" %
(local, domain))
list.append("List-Subscribe: <mailto:%s-subscribe@%s>" %
(local, domain))
list.append("List-Post: <mailto:%s@%s>" % (local, domain))
list.append("List-Owner: <mailto:%s-owner@%s>" % (local, domain))
list.append("Precedence: bulk");
return string.join(list, "\n") + "\n"
def read_file(self, basename):
try:
f = open(os.path.join(self.dirname, basename), "r")
data = f.read()
f.close()
return data
except IOError:
return ""
def headers_to_add(self):
headers_to_add = self.read_file("headers-to-add").rstrip()
if headers_to_add:
return headers_to_add + "\n"
else:
return ""
def remove_some_headers(self, mail, headers_to_remove):
endpos = mail.find("\n\n")
if endpos == -1:
endpos = mail.find("\n\r\n")
if endpos == -1:
return mail
headers = mail[:endpos].split("\n")
body = mail[endpos:]
headers_to_remove = [x.lower() for x in headers_to_remove]
remaining = []
add_continuation_lines = 0
for header in headers:
if header[0] in [' ','\t']:
# this is a continuation line
if add_continuation_lines:
remaining.append(header)
else:
pos = header.find(":")
if pos == -1:
# malformed message, try to remove the junk
add_continuation_lines = 0
continue
name = header[:pos].lower()
if name in headers_to_remove:
add_continuation_lines = 0
else:
add_continuation_lines = 1
remaining.append(header)
return "\n".join(remaining) + body
def headers_to_remove(self, text):
headers_to_remove = self.read_file("headers-to-remove").split("\n")
headers_to_remove = map(lambda s: s.strip().lower(),
headers_to_remove)
return self.remove_some_headers(text, headers_to_remove)
def append_footer(self, text):
if "base64" in text or "BASE64" in text:
import StringIO
for line in StringIO.StringIO(text):
if line.lower().startswith("content-transfer-encoding:") and \
"base64" in line.lower():
return text
return text + self.template("footer", {})
def send_mail_to_subscribers(self, text):
text = self.remove_some_headers(text, ["list-id", "list-help",
"list-unsubscribe",
"list-subscribe", "list-post",
"list-owner", "precedence"])
text = self.headers_to_add() + self.list_headers() + \
self.headers_to_remove(text)
text = self.append_footer(text)
text, = self.mlm.call_plugins("send_mail_to_subscribers_hook",
self, text)
if have_email_module and \
self.cp.get("list", "pristine-headers") != "yes":
text = self.mime_encode_headers(text)
self.store_into_archive(text)
for group in self.subscribers.groups():
bounce = self.signed_address("bounce", group)
addresses = self.subscribers.in_group(group)
self.mlm.send_mail(bounce, addresses, text)
def post_into_moderate(self, poster, dict, text):
id = self.moderation_box.add(poster, text)
recipients = self.moderators()
if recipients == []:
recipients = self.owners()
confirm = self.signed_address("approve", id)
deny = self.signed_address("reject", id)
self.send_template(self.ignore(), deny, recipients, "msg-moderate",
{
"confirm": confirm,
"deny": deny,
"origmail": text,
"boundary": self.invent_boundary(),
})
self.send_info_message([poster], "msg-wait", {})
def should_be_moderated(self, posting, poster):
if posting == "moderated":
return 1
if posting == "auto":
if poster.lower() not in \
map(string.lower, self.subscribers.get_all()):
return 1
return 0
def obey_post(self, dict, text):
if dict.has_key("force-moderation") and dict["force-moderation"]:
force_moderation = 1
else:
force_moderation = 0
if dict.has_key("force-posting") and dict["force-posting"]:
force_posting = 1
else:
force_posting = 0
posting = self.cp.get("list", "posting")
if posting not in self.posting_opts:
error("You have a weird 'posting' config. Please, review it")
poster = get_from_environ("SENDER")
if force_moderation:
self.post_into_moderate(poster, dict, text)
elif force_posting:
self.send_mail_to_subscribers(text)
elif self.should_be_moderated(posting, poster):
self.post_into_moderate(poster, dict, text)
else:
self.send_mail_to_subscribers(text)
def obey_approve(self, dict):
if self.moderation_box.lock(dict["id"]):
if self.moderation_box.has(dict["id"]):
text = self.moderation_box.get(dict["id"])