]> git.sommitrealweird.co.uk Git - eoc.git/blob - eoc.py
Report problems sending mail. Thanks to Antti-Juhani Kaijanaho
[eoc.git] / eoc.py
1 """Mailing list manager.
2
3 This is a simple mailing list manager that mimicks the ezmlm-idx mail
4 address commands. See manual page for more information.
5 """
6
7 VERSION = "1.2.1"
8 PLUGIN_INTERFACE_VERSION = "1"
9
10 import getopt
11 import md5
12 import os
13 import shutil
14 import smtplib
15 import string
16 import sys
17 import time
18 import ConfigParser
19 try:
20     import email.Header
21     have_email_module = 1
22 except ImportError:
23     have_email_module = 0
24 import imp
25
26 import qmqp
27
28
29 # The following values will be overriden by "make install".
30 TEMPLATE_DIRS = ["./templates"]
31 DOTDIR = "dot-eoc"
32
33
34 class EocException(Exception):
35
36     def __init__(self, arg=None):
37         self.msg = repr(arg)
38
39     def __str__(self):
40         return self.msg
41
42 class UnknownList(EocException):
43     def __init__(self, list_name):
44         self.msg = "%s is not a known mailing list" % list_name
45
46 class BadCommandAddress(EocException):
47     def __init__(self, address):
48         self.msg = "%s is not a valid command address" % address
49
50 class BadSignature(EocException):
51     def __init__(self, address):
52         self.msg = "address %s has an invalid digital signature" % address
53
54 class ListExists(EocException):
55     def __init__(self, list_name):
56         self.msg = "Mailing list %s alreadys exists" % list_name
57
58 class ListDoesNotExist(EocException):
59     def __init__(self, list_name):
60         self.msg = "Mailing list %s does not exist" % list_name
61
62 class MissingEnvironmentVariable(EocException):
63     def __init__(self, name):
64         self.msg = "Environment variable %s does not exist" % name
65
66 class MissingTemplate(EocException):
67     def __init__(self, template):
68         self.msg = "Template %s does not exit" % template
69
70
71 # Names of commands EoC recognizes in e-mail addresses.
72 SIMPLE_COMMANDS = ["help", "list", "owner", "setlist", "setlistsilently", "ignore"]
73 SUB_COMMANDS = ["subscribe", "unsubscribe"]
74 HASH_COMMANDS = ["subyes", "subapprove", "subreject", "unsubyes",
75                  "bounce", "probe", "approve", "reject", "setlistyes",
76                  "setlistsilentyes"]
77 COMMANDS = SIMPLE_COMMANDS + SUB_COMMANDS + HASH_COMMANDS
78
79
80 def md5sum_as_hex(s):
81     return md5.new(s).hexdigest()
82
83 environ = None
84
85 def set_environ(new_environ):
86     global environ
87     environ = new_environ
88
89 def get_from_environ(key):
90     global environ
91     if environ:
92         env = environ
93     else:
94         env = os.environ
95     if env.has_key(key):
96         return env[key].lower()
97     raise MissingEnvironmentVariable(key)
98
99 class AddressParser:
100
101     """A parser for incoming e-mail addresses."""
102
103     def __init__(self, lists):
104         self.set_lists(lists)
105         self.set_skip_prefix(None)
106         self.set_forced_domain(None)
107
108     def set_lists(self, lists):
109         """Set the list of canonical list names we should know about."""
110         self.lists = lists
111
112     def set_skip_prefix(self, skip_prefix):
113         """Set the prefix to be removed from an address."""
114         self.skip_prefix = skip_prefix
115         
116     def set_forced_domain(self, forced_domain):
117         """Set the domain part we should force the address to have."""
118         self.forced_domain = forced_domain
119
120     def clean(self, address):
121         """Remove cruft from the address and convert the rest to lower case."""
122         if self.skip_prefix:
123             n = self.skip_prefix and len(self.skip_prefix)
124             if address[:n] == self.skip_prefix:
125                 address = address[n:]
126         if self.forced_domain:
127             parts = address.split("@", 1)
128             address = "%s@%s" % (parts[0], self.forced_domain)
129         return address.lower()
130
131     def split_address(self, address):
132         """Split an address to a local part and a domain."""
133         parts = address.lower().split("@", 1)
134         if len(parts) != 2:
135             return (address, "")
136         else:
137             return parts
138
139     # Does an address refer to a list? If not, return None, else return a list
140     # of additional parts (separated by hyphens) in the address. Note that []
141     # is not the same as None.
142     
143     def additional_address_parts(self, address, listname):
144         addr_local, addr_domain = self.split_address(address)
145         list_local, list_domain = self.split_address(listname)
146         
147         if addr_domain != list_domain:
148             return None
149         
150         if addr_local.lower() == list_local.lower():
151             return []
152         
153         n = len(list_local)
154         if addr_local[:n] != list_local or addr_local[n] != "-":
155             return None
156             
157         return addr_local[n+1:].split("-")
158         
159
160     # Parse an address we have received that identifies a list we manage.
161     # The address may contain command and signature parts. Return the name
162     # of the list, and a sequence of the additional parts (split at hyphens).
163     # Raise exceptions for errors. Note that the command will be valid, but
164     # cryptographic signatures in the address is not checked.
165     
166     def parse(self, address):
167         address = self.clean(address)
168         for listname in self.lists:
169             parts = self.additional_address_parts(address, listname)
170             if parts == None:
171                 pass
172             elif parts == []:
173                 return listname, parts
174             elif parts[0] in HASH_COMMANDS:
175                 if len(parts) != 3:
176                     raise BadCommandAddress(address)
177                 return listname, parts
178             elif parts[0] in COMMANDS:
179                 return listname, parts
180
181         raise UnknownList(address)
182
183
184 class MailingListManager:
185
186     def __init__(self, dotdir, sendmail="/usr/sbin/sendmail", lists=[],
187                  smtp_server=None, qmqp_server=None):
188         self.dotdir = dotdir
189         self.sendmail = sendmail
190         self.smtp_server = smtp_server
191         self.qmqp_server = qmqp_server
192
193         self.make_dotdir()
194         self.secret = self.make_and_read_secret()
195
196         if not lists:
197             lists = filter(lambda s: "@" in s, os.listdir(dotdir))
198         self.set_lists(lists)
199
200         self.simple_commands = ["help", "list", "owner", "setlist",
201                                 "setlistsilently", "ignore"]
202         self.sub_commands = ["subscribe", "unsubscribe"]
203         self.hash_commands = ["subyes", "subapprove", "subreject", "unsubyes",
204                               "bounce", "probe", "approve", "reject",
205                               "setlistyes", "setlistsilentyes"]
206         self.commands = self.simple_commands + self.sub_commands + \
207                         self.hash_commands
208
209         self.environ = None
210
211         self.load_plugins()
212         
213     # Create the dot directory for us, if it doesn't exist already.
214     def make_dotdir(self):
215         if not os.path.isdir(self.dotdir):
216             os.makedirs(self.dotdir, 0700)
217
218     # Create the "secret" file, with a random value used as cookie for
219     # verification addresses.
220     def make_and_read_secret(self):
221         secret_name = os.path.join(self.dotdir, "secret")
222         if not os.path.isfile(secret_name):
223             f = open("/dev/urandom", "r")
224             secret = f.read(32)
225             f.close()
226             f = open(secret_name, "w")
227             f.write(secret)
228             f.close()
229         else:
230             f = open(secret_name, "r")
231             secret = f.read()
232             f.close()
233         return secret
234
235     # Load the plugins from DOTDIR/plugins/*.py.
236     def load_plugins(self):
237         self.plugins = []
238
239         dirname = os.path.join(DOTDIR, "plugins")
240         try:
241             plugins = os.listdir(dirname)
242         except OSError:
243             return
244             
245         plugins.sort()
246         plugins = map(os.path.splitext, plugins)
247         plugins = filter(lambda p: p[1] == ".py", plugins)
248         plugins = map(lambda p: p[0], plugins)
249         for name in plugins:
250             pathname = os.path.join(dirname, name + ".py")
251             f = open(pathname, "r")
252             module = imp.load_module(name, f, pathname, 
253                                      (".py", "r", imp.PY_SOURCE))
254             f.close()
255             if module.PLUGIN_INTERFACE_VERSION == PLUGIN_INTERFACE_VERSION:
256                 self.plugins.append(module)
257
258     # Call function named funcname (a string) in all plugins, giving as
259     # arguments all the remaining arguments preceded by ml. Return value
260     # of each function is the new list of arguments to the next function.
261     # Return value of this function is the return value of the last function.
262     def call_plugins(self, funcname, list, *args):
263         for plugin in self.plugins:
264             if plugin.__dict__.has_key(funcname):
265                 args = apply(plugin.__dict__[funcname], (list,) + args)
266                 if type(args) != type((0,)):
267                     args = (args,)
268         return args
269
270     # Set the list of listnames. The list of lists needs to be sorted in
271     # length order so that test@example.com is matched before
272     # test-list@example.com
273     def set_lists(self, lists):
274         temp = map(lambda s: (len(s), s), lists)
275         temp.sort()
276         self.lists = map(lambda t: t[1], temp)
277
278     # Return the list of listnames.
279     def get_lists(self):
280         return self.lists
281
282     # Decode an address that has been encoded to be part of a local part.
283     def decode_address(self, parts):
284         return string.join(string.join(parts, "-").split("="), "@")
285
286     # Is local_part@domain an existing list?
287     def is_list_name(self, local_part, domain):
288         return ("%s@%s" % (local_part, domain)) in self.lists
289
290     # Compute the verification checksum for an address.
291     def compute_hash(self, address):
292         return md5sum_as_hex(address + self.secret)
293
294     # Is the verification signature in a parsed address bad? If so, return true,
295     # otherwise return false.
296     def signature_is_bad(self, dict, hash):
297         local_part, domain = dict["name"].split("@")
298         address = "%s-%s-%s@%s" % (local_part, dict["command"], dict["id"], 
299                                    domain)
300         correct = self.compute_hash(address)
301         return correct != hash
302
303     # Parse a command address we have received and check its validity
304     # (including signature, if any). Return a dictionary with keys
305     # "command", "sender" (address that was encoded into address, if
306     # any), "id" (group ID).
307
308     def parse_recipient_address(self, address, skip_prefix, forced_domain):
309         ap = AddressParser(self.get_lists())
310         ap.set_lists(self.get_lists())
311         ap.set_skip_prefix(skip_prefix)
312         ap.set_forced_domain(forced_domain)
313         listname, parts = ap.parse(address)
314
315         dict = { "name": listname }
316
317         if parts == []:
318             dict["command"] = "post"
319         else:
320             command, args = parts[0], parts[1:]
321             dict["command"] = command
322             if command in SUB_COMMANDS:
323                 dict["sender"] = self.decode_address(args)
324             elif command in HASH_COMMANDS:
325                 dict["id"] = args[0]
326                 hash = args[1]
327                 if self.signature_is_bad(dict, hash):
328                     raise BadSignature(address)
329
330         return dict
331
332     # Does an address refer to a mailing list?
333     def is_list(self, name, skip_prefix=None, domain=None):
334         try:
335             self.parse_recipient_address(name, skip_prefix, domain)
336         except BadCommandAddress:
337             return 0
338         except BadSignature:
339             return 0
340         except UnknownList:
341             return 0
342         return 1
343
344     # Create a new list and return it.
345     def create_list(self, name):
346         if self.is_list(name):
347             raise ListExists(name)
348         self.set_lists(self.lists + [name])
349         return MailingList(self, name)
350
351     # Open an existing list.
352     def open_list(self, name):
353         if self.is_list(name):
354             return self.open_list_exact(name)
355         else:
356             x = name + "@"
357             for list in self.lists:
358                 if list[:len(x)] == x:
359                     return self.open_list_exact(list)
360             raise ListDoesNotExist(name)
361
362     def open_list_exact(self, name):
363         for list in self.get_lists():
364             if list.lower() == name.lower():
365                 return MailingList(self, list)
366         raise ListDoesNotExist(name)
367
368     # Process an incoming message.
369     def incoming_message(self, skip_prefix, domain, moderate, post):
370         debug("Processing incoming message.")
371         debug("$SENDER = <%s>" % get_from_environ("SENDER"))
372         debug("$RECIPIENT = <%s>" % get_from_environ("RECIPIENT"))
373         dict = self.parse_recipient_address(get_from_environ("RECIPIENT"),
374                                                              skip_prefix, 
375                                                              domain)
376         dict["force-moderation"] = moderate
377         dict["force-posting"] = post
378         debug("List is <%(name)s>, command is <%(command)s>." % dict)
379         list = self.open_list_exact(dict["name"])
380         list.obey(dict)
381
382     # Clean up bouncing address and do other janitorial work for all lists.
383     def cleaning_woman(self, send_mail=None):
384         now = time.time()
385         for listname in self.lists:
386             list = self.open_list_exact(listname)
387             if send_mail:
388                 list.send_mail = send_mail
389             list.cleaning_woman(now)
390
391     # Send a mail to the desired recipients.
392     def send_mail(self, envelope_sender, recipients, text):
393         debug("send_mail:\n  sender=%s\n  recipients=%s\n  text=\n    %s" % 
394               (envelope_sender, str(recipients), 
395                "\n    ".join(text[:text.find("\n\n")].split("\n"))))
396         if recipients:
397             if self.smtp_server:
398                 try:
399                     smtp = smtplib.SMTP(self.smtp_server)
400                     smtp.sendmail(envelope_sender, recipients, text)
401                     smtp.quit()
402                 except:
403                     error("Error sending SMTP mail, mail probably not sent")
404                     sys.exit(1)
405             elif self.qmqp_server:
406                 try:
407                     q = qmqp.QMQP(self.qmqp_server)
408                     q.sendmail(envelope_sender, recipients, text)
409                     q.quit()
410                 except:
411                     error("Error sending QMQP mail, mail probably not sent")
412                     sys.exit(1)
413             else:
414                 recipients = string.join(recipients, " ")
415                 f = os.popen("%s -oi -f '%s' %s" % 
416                                  (self.sendmail, 
417                                   envelope_sender, 
418                                   recipients),
419                              "w")
420                 f.write(text)
421                 status = f.close()
422                 if status != 0:
423                     error("%s returned %d, mail sending probably failed" %
424                            (self.sendmail, status))
425                     sys.exit((status >> 8) & 0xff)
426         else:
427             debug("send_mail: no recipients, not sending")
428
429
430
431 class MailingList:
432
433     posting_opts = ["auto", "free", "moderated"]
434
435     def __init__(self, mlm, name):
436         self.mlm = mlm
437         self.name = name
438
439         self.cp = ConfigParser.ConfigParser()
440         self.cp.add_section("list")
441         self.cp.set("list", "owners", "")
442         self.cp.set("list", "moderators", "")
443         self.cp.set("list", "subscription", "free")
444         self.cp.set("list", "posting", "free")
445         self.cp.set("list", "archived", "no")
446         self.cp.set("list", "mail-on-subscription-changes", "no")
447         self.cp.set("list", "mail-on-forced-unsubscribe", "no")
448         self.cp.set("list", "ignore-bounce", "no")
449         self.cp.set("list", "language", "")
450         self.cp.set("list", "pristine-headers", "")
451
452         self.dirname = os.path.join(self.mlm.dotdir, name)
453         self.make_listdir()
454         self.cp.read(self.mkname("config"))
455
456         self.subscribers = SubscriberDatabase(self.dirname, "subscribers")
457         self.moderation_box = MessageBox(self.dirname, "moderation-box")
458         self.subscription_box = MessageBox(self.dirname, "subscription-box")
459         self.bounce_box = MessageBox(self.dirname, "bounce-box")
460
461     def make_listdir(self):
462         if not os.path.isdir(self.dirname):
463             os.mkdir(self.dirname, 0700)
464             self.save_config()
465             f = open(self.mkname("subscribers"), "w")
466             f.close()
467
468     def mkname(self, relative):
469         return os.path.join(self.dirname, relative)
470
471     def save_config(self):
472         f = open(self.mkname("config"), "w")
473         self.cp.write(f)
474         f.close()
475
476     def read_stdin(self):
477         data = sys.stdin.read()
478         # Skip Unix mbox "From " mail start indicator
479         if data[:5] == "From ":
480             data = string.split(data, "\n", 1)[1]
481         return data
482
483     def invent_boundary(self):
484         return "%s/%s" % (md5sum_as_hex(str(time.time())),
485                           md5sum_as_hex(self.name))
486
487     def command_address(self, command):
488         local_part, domain = self.name.split("@")
489         return "%s-%s@%s" % (local_part, command, domain)
490
491     def signed_address(self, command, id):
492         unsigned = self.command_address("%s-%s" % (command, id))
493         hash = self.mlm.compute_hash(unsigned)
494         return self.command_address("%s-%s-%s" % (command, id, hash))
495
496     def ignore(self):
497         return self.command_address("ignore")
498
499     def nice_7bit(self, str):
500         for c in str:
501             if (ord(c) < 32 and not c.isspace()) or ord(c) >= 127:
502                 return False
503         return True
504     
505     def mime_encode_headers(self, text):
506         try:
507             headers, body = text.split("\n\n", 1)
508         
509             list = []
510             for line in headers.split("\n"):
511                 if line[0].isspace():
512                     list[-1] += line
513                 else:
514                     list.append(line)
515         
516             headers = []
517             for header in list:
518                 if self.nice_7bit(header):
519                     headers.append(header)
520                 else:
521                     if ": " in header:
522                         name, content = header.split(": ", 1)
523                     else:
524                         name, content = header.split(":", 1)
525                     hdr = email.Header.Header(content, "utf-8")
526                     headers.append(name + ": " + hdr.encode())
527         
528             return "\n".join(headers) + "\n\n" + body
529         except:
530             error("Cannot MIME encode header, using original ones, sorry")
531             return text
532
533     def template(self, template_name, dict):
534         lang = self.cp.get("list", "language")
535         if lang:
536             template_name_lang = template_name + "." + lang
537         else:
538             template_name_lang = template_name
539
540         if not dict.has_key("list"):
541             dict["list"] = self.name
542             dict["local"], dict["domain"] = self.name.split("@")
543         if not dict.has_key("list"):
544             dict["list"] = self.name
545
546         for dir in [os.path.join(self.dirname, "templates")] + TEMPLATE_DIRS:
547             pathname = os.path.join(dir, template_name_lang)
548             if not os.path.exists(pathname):
549                 pathname = os.path.join(dir, template_name)
550             if os.path.exists(pathname):
551                 f = open(pathname, "r")
552                 data = f.read()
553                 f.close()
554                 return data % dict
555
556         raise MissingTemplate(template_name)
557
558     def send_template(self, envelope_sender, sender, recipients,
559                       template_name, dict):
560         dict["From"] = "EoC <%s>" % sender
561         dict["To"] = string.join(recipients, ", ")
562         text = self.template(template_name, dict)
563         if not text:
564             return
565         if self.cp.get("list", "pristine-headers") != "yes":
566             text = self.mime_encode_headers(text)
567         self.mlm.send_mail(envelope_sender, recipients, text)
568
569     def send_info_message(self, recipients, template_name, dict):
570         self.send_template(self.command_address("ignore"),
571                            self.command_address("help"),
572                            recipients,
573                            template_name,
574                            dict)
575
576     def owners(self):
577         return self.cp.get("list", "owners").split()
578
579     def moderators(self):
580         return self.cp.get("list", "moderators").split()
581
582     def is_list_owner(self, address):
583         return address in self.owners()
584
585     def obey_help(self):
586         self.send_info_message([get_from_environ("SENDER")], "help", {})
587
588     def obey_list(self):
589         recipient = get_from_environ("SENDER")
590         if self.is_list_owner(recipient):
591             addr_list = self.subscribers.get_all()
592             addr_text = string.join(addr_list, "\n")
593             self.send_info_message([recipient], "list",
594                                    {
595                                      "addresses": addr_text,
596                                      "count": len(addr_list),
597                                    })
598         else:
599             self.send_info_message([recipient], "list-sorry", {})
600
601     def obey_setlist(self, origmail):
602         recipient = get_from_environ("SENDER")
603         if self.is_list_owner(recipient):
604             id = self.moderation_box.add(recipient, origmail)
605             if self.parse_setlist_addresses(origmail) == None:
606                 self.send_bad_addresses_in_setlist(id)
607                 self.moderation_box.remove(id)
608             else:
609                 confirm = self.signed_address("setlistyes", id)
610                 self.send_info_message(self.owners(), "setlist-confirm",
611                                        {
612                                           "confirm": confirm,
613                                           "origmail": origmail,
614                                           "boundary": self.invent_boundary(),
615                                        })
616                 
617         else:
618             self.send_info_message([recipient], "setlist-sorry", {})
619
620     def obey_setlistsilently(self, origmail):
621         recipient = get_from_environ("SENDER")
622         if self.is_list_owner(recipient):
623             id = self.moderation_box.add(recipient, origmail)
624             if self.parse_setlist_addresses(origmail) == None:
625                 self.send_bad_addresses_in_setlist(id)
626                 self.moderation_box.remove(id)
627             else:
628                 confirm = self.signed_address("setlistsilentyes", id)
629                 self.send_info_message(self.owners(), "setlist-confirm",
630                                        {
631                                           "confirm": confirm,
632                                           "origmail": origmail,
633                                           "boundary": self.invent_boundary(),
634                                        })
635         else:
636             self.info_message([recipient], "setlist-sorry", {})
637
638     def parse_setlist_addresses(self, text):
639         body = text.split("\n\n", 1)[1]
640         lines = body.split("\n")
641         lines = filter(lambda line: line != "", lines)
642         badlines = filter(lambda line: "@" not in line, lines)
643         if badlines:
644             return None
645         else:
646             return lines
647
648     def send_bad_addresses_in_setlist(self, id):
649         addr = self.moderation_box.get_address(id)
650         origmail = self.moderation_box.get(id)
651         self.send_info_message([addr], "setlist-badlist",
652                                {
653                                 "origmail": origmail,
654                                 "boundary": self.invent_boundary(),
655                                })
656
657
658     def obey_setlistyes(self, dict):
659         if self.moderation_box.has(dict["id"]):
660             text = self.moderation_box.get(dict["id"])
661             addresses = self.parse_setlist_addresses(text)
662             if addresses == None:
663                 self.send_bad_addresses_in_setlist(id)
664             else:
665                 removed_subscribers = []
666                 self.subscribers.lock()
667                 old = self.subscribers.get_all()
668                 for address in old:
669                     if address.lower() not in map(string.lower, addresses):
670                         self.subscribers.remove(address)
671                         removed_subscribers.append(address)
672                     else:
673                         for x in addresses:
674                             if x.lower() == address.lower():
675                                 addresses.remove(x)
676                 self.subscribers.add_many(addresses)
677                 self.subscribers.save()
678                 
679                 for recipient in addresses:
680                     self.send_info_message([recipient], "sub-welcome", {})
681                 for recipient in removed_subscribers:
682                     self.send_info_message([recipient], "unsub-goodbye", {})
683                 self.send_info_message(self.owners(), "setlist-done", {})
684
685             self.moderation_box.remove(dict["id"])
686
687     def obey_setlistsilentyes(self, dict):
688         if self.moderation_box.has(dict["id"]):
689             text = self.moderation_box.get(dict["id"])
690             addresses = self.parse_setlist_addresses(text)
691             if addresses == None:
692                 self.send_bad_addresses_in_setlist(id)
693             else:
694                 self.subscribers.lock()
695                 old = self.subscribers.get_all()
696                 for address in old:
697                     if address not in addresses:
698                         self.subscribers.remove(address)
699                     else:
700                         addresses.remove(address)
701                 self.subscribers.add_many(addresses)
702                 self.subscribers.save()
703                 self.send_info_message(self.owners(), "setlist-done", {})
704
705             self.moderation_box.remove(dict["id"])
706
707     def obey_owner(self, text):
708         sender = get_from_environ("SENDER")
709         recipients = self.cp.get("list", "owners").split()
710         self.mlm.send_mail(sender, recipients, text)
711
712     def obey_subscribe_or_unsubscribe(self, dict, template_name, command, 
713                                       origmail):
714
715         requester  = get_from_environ("SENDER")
716         subscriber = dict["sender"]
717         if not subscriber:
718             subscriber = requester
719         if subscriber.find("@") == -1:
720             info("Trying to (un)subscribe address without @: %s" % subscriber)
721             return
722         if self.cp.get("list", "ignore-bounce") == "yes":
723             info("Will not (un)subscribe address: %s from static list" %subscriber)
724             return
725         if requester in self.owners():
726             confirmers = self.owners()
727         else:
728             confirmers = [subscriber]
729
730         id = self.subscription_box.add(subscriber, origmail)
731         confirm = self.signed_address(command, id)
732         self.send_info_message(confirmers, template_name,
733                                {
734                                     "confirm": confirm,
735                                     "origmail": origmail,
736                                     "boundary": self.invent_boundary(),
737                                })
738
739     def obey_subscribe(self, dict, origmail):
740         self.obey_subscribe_or_unsubscribe(dict, "sub-confirm", "subyes", 
741                                            origmail)
742
743     def obey_unsubscribe(self, dict, origmail):
744         self.obey_subscribe_or_unsubscribe(dict, "unsub-confirm", "unsubyes",
745                                            origmail)
746
747     def obey_subyes(self, dict):
748         if self.subscription_box.has(dict["id"]):
749             if self.cp.get("list", "subscription") == "free":
750                 recipient = self.subscription_box.get_address(dict["id"])
751                 self.subscribers.lock()
752                 self.subscribers.add(recipient)
753                 self.subscribers.save()
754                 sender = self.command_address("help")
755                 self.send_template(self.ignore(), sender, [recipient], 
756                                    "sub-welcome", {})
757                 self.subscription_box.remove(dict["id"])
758                 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
759                     self.send_info_message(self.owners(), 
760                                            "sub-owner-notification",
761                                            {
762                                             "address": recipient,
763                                            })
764             else:
765                 recipients = self.cp.get("list", "owners").split()
766                 confirm = self.signed_address("subapprove", dict["id"])
767                 deny = self.signed_address("subreject", dict["id"])
768                 subscriber = self.subscription_box.get_address(dict["id"])
769                 origmail = self.subscription_box.get(dict["id"])
770                 self.send_template(self.ignore(), deny, recipients, 
771                                    "sub-moderate", 
772                                    {
773                                        "confirm": confirm,
774                                        "deny": deny,
775                                        "subscriber": subscriber,
776                                        "origmail": origmail,
777                                        "boundary": self.invent_boundary(),
778                                    })
779                 recipient = self.subscription_box.get_address(dict["id"])
780                 self.send_info_message([recipient], "sub-wait", {})
781
782     def obey_subapprove(self, dict):
783         if self.subscription_box.has(dict["id"]):
784             recipient = self.subscription_box.get_address(dict["id"])
785             self.subscribers.lock()
786             self.subscribers.add(recipient)
787             self.subscribers.save()
788             self.send_info_message([recipient], "sub-welcome", {})
789             self.subscription_box.remove(dict["id"])
790             if self.cp.get("list", "mail-on-subscription-changes")=="yes":
791                 self.send_info_message(self.owners(), "sub-owner-notification",
792                                        {
793                                         "address": recipient,
794                                        })
795
796     def obey_subreject(self, dict):
797         if self.subscription_box.has(dict["id"]):
798             recipient = self.subscription_box.get_address(dict["id"])
799             self.send_info_message([recipient], "sub-reject", {})
800             self.subscription_box.remove(dict["id"])
801
802     def obey_unsubyes(self, dict):
803         if self.subscription_box.has(dict["id"]):
804             recipient = self.subscription_box.get_address(dict["id"])
805             self.subscribers.lock()
806             self.subscribers.remove(recipient)
807             self.subscribers.save()
808             self.send_info_message([recipient], "unsub-goodbye", {})
809             self.subscription_box.remove(dict["id"])
810             if self.cp.get("list", "mail-on-subscription-changes")=="yes":
811                 self.send_info_message(self.owners(),
812                                        "unsub-owner-notification",
813                                        {
814                                         "address": recipient,
815                                        })
816
817     def store_into_archive(self, text):
818         if self.cp.get("list", "archived") == "yes":
819             archdir = os.path.join(self.dirname, "archive")
820             if not os.path.exists(archdir):
821                 os.mkdir(archdir, 0700)
822             id = md5sum_as_hex(text)
823             f = open(os.path.join(archdir, id), "w")
824             f.write(text)
825             f.close()
826
827     def list_headers(self):
828         local, domain = self.name.split("@")
829         list = []
830         list.append("List-Id: <%s.%s>" % (local, domain))
831         list.append("List-Help: <mailto:%s-help@%s>" % (local, domain))
832         list.append("List-Unsubscribe: <mailto:%s-unsubscribe@%s>" % 
833                     (local, domain))
834         list.append("List-Subscribe: <mailto:%s-subscribe@%s>" % 
835                     (local, domain))
836         list.append("List-Post: <mailto:%s@%s>" % (local, domain))
837         list.append("List-Owner: <mailto:%s-owner@%s>" % (local, domain))
838         list.append("Precedence: bulk");
839         return string.join(list, "\n") + "\n"
840
841     def read_file(self, basename):
842         try:
843             f = open(os.path.join(self.dirname, basename), "r")
844             data = f.read()
845             f.close()
846             return data
847         except IOError:
848             return ""
849
850     def headers_to_add(self):
851         headers_to_add = self.read_file("headers-to-add").rstrip()
852         if headers_to_add:
853             return headers_to_add + "\n"
854         else:
855             return ""
856
857     def remove_some_headers(self, mail, headers_to_remove):
858         endpos = mail.find("\n\n")
859         if endpos == -1:
860             endpos = mail.find("\n\r\n")
861             if endpos == -1:
862                 return mail
863         headers = mail[:endpos].split("\n")
864         body = mail[endpos:]
865         
866         headers_to_remove = [x.lower() for x in headers_to_remove]
867     
868         remaining = []
869         add_continuation_lines = 0
870
871         for header in headers:
872             if header[0] in [' ','\t']:
873                 # this is a continuation line
874                 if add_continuation_lines:
875                     remaining.append(header)
876             else:
877                 pos = header.find(":")
878                 if pos == -1:
879                     # malformed message, try to remove the junk
880                     add_continuation_lines = 0
881                     continue
882                 name = header[:pos].lower()
883                 if name in headers_to_remove:
884                     add_continuation_lines = 0
885                 else:
886                     add_continuation_lines = 1
887                     remaining.append(header)
888         
889         return "\n".join(remaining) + body
890
891     def headers_to_remove(self, text):
892         headers_to_remove = self.read_file("headers-to-remove").split("\n")
893         headers_to_remove = map(lambda s: s.strip().lower(), 
894                                 headers_to_remove)
895         return self.remove_some_headers(text, headers_to_remove)
896
897     def append_footer(self, text):
898         if "base64" in text or "BASE64" in text:
899             import StringIO
900             for line in StringIO.StringIO(text):
901                 if line.lower().startswith("content-transfer-encoding:") and \
902                    "base64" in line.lower():
903                     return text
904         return text + self.template("footer", {})
905
906     def send_mail_to_subscribers(self, text):
907         text = self.headers_to_add() + self.list_headers() + \
908                self.headers_to_remove(text)
909         text = self.append_footer(text)
910         text, = self.mlm.call_plugins("send_mail_to_subscribers_hook",
911                                      self, text)
912         if have_email_module and \
913            self.cp.get("list", "pristine-headers") != "yes":
914             text = self.mime_encode_headers(text)
915         self.store_into_archive(text)
916         for group in self.subscribers.groups():
917             bounce = self.signed_address("bounce", group)
918             addresses = self.subscribers.in_group(group)
919             self.mlm.send_mail(bounce, addresses, text)
920
921     def post_into_moderate(self, poster, dict, text):
922         id = self.moderation_box.add(poster, text)
923         recipients = self.moderators()
924         if recipients == []:
925             recipients = self.owners()
926
927         confirm = self.signed_address("approve", id)
928         deny = self.signed_address("reject", id)
929         self.send_template(self.ignore(), deny, recipients, "msg-moderate",
930                            {
931                             "confirm": confirm,
932                             "deny": deny,
933                             "origmail": text,
934                             "boundary": self.invent_boundary(),
935                            })
936         self.send_info_message([poster], "msg-wait", {})
937     
938     def should_be_moderated(self, posting, poster):
939         if posting == "moderated":
940             return 1
941         if posting == "auto":
942             if poster.lower() not in \
943                 map(string.lower, self.subscribers.get_all()):
944                 return 1
945         return 0
946
947     def obey_post(self, dict, text):
948         if dict.has_key("force-moderation") and dict["force-moderation"]:
949             force_moderation = 1
950         else:
951             force_moderation = 0
952         if dict.has_key("force-posting") and dict["force-posting"]:
953             force_posting = 1
954         else:
955             force_posting = 0
956         posting = self.cp.get("list", "posting")
957         if posting not in self.posting_opts:
958             error("You have a weird 'posting' config. Please, review it")
959         poster = get_from_environ("SENDER")
960         if force_moderation:
961             self.post_into_moderate(poster, dict, text)
962         elif force_posting:
963             self.send_mail_to_subscribers(text)
964         elif self.should_be_moderated(posting, poster):
965             self.post_into_moderate(poster, dict, text)
966         else:
967             self.send_mail_to_subscribers(text)
968  
969     def obey_approve(self, dict):
970         if self.moderation_box.lock(dict["id"]):
971             if self.moderation_box.has(dict["id"]):
972                 text = self.moderation_box.get(dict["id"])
973                 self.send_mail_to_subscribers(text)
974                 self.moderation_box.remove(dict["id"])
975             self.moderation_box.unlock(dict["id"])
976
977     def obey_reject(self, dict):
978         if self.moderation_box.lock(dict["id"]):
979             if self.moderation_box.has(dict["id"]):
980                 self.moderation_box.remove(dict["id"])
981             self.moderation_box.unlock(dict["id"])
982
983     def split_address_list(self, addrs):
984         domains = {}
985         for addr in addrs:
986             userpart, domain = addr.split("@")
987             if domains.has_key(domain):
988                 domains[domain].append(addr)
989             else:
990                 domains[domain] = [addr]
991         result = []
992         if len(domains.keys()) == 1:
993             for addr in addrs:
994                 result.append([addr])
995         else:
996             result = domains.values()
997         return result
998
999     def obey_bounce(self, dict, text):
1000         if self.subscribers.has_group(dict["id"]):
1001             self.subscribers.lock()
1002             addrs = self.subscribers.in_group(dict["id"])
1003             if len(addrs) == 1:
1004                 if self.cp.get("list", "ignore-bounce") == "yes":
1005                     info("Address <%s> bounced, ignoring bounce as configured." %
1006                          addrs[0])
1007                     self.subscribers.unlock()
1008                     return
1009                 debug("Address <%s> bounced, setting state to bounce." %
1010                       addrs[0])
1011                 bounce_id = self.bounce_box.add(addrs[0], text[:4096])
1012                 self.subscribers.set(dict["id"], "status", "bounced")
1013                 self.subscribers.set(dict["id"], "timestamp-bounced", 
1014                                      "%f" % time.time())
1015                 self.subscribers.set(dict["id"], "bounce-id",
1016                                      bounce_id)
1017             else:
1018                 debug("Group %s bounced, splitting." % dict["id"])
1019                 for new_addrs in self.split_address_list(addrs):
1020                     self.subscribers.add_many(new_addrs)
1021                 self.subscribers.remove_group(dict["id"])
1022             self.subscribers.save()
1023         else:
1024             debug("Ignoring bounce, group %s doesn't exist (anymore?)." %
1025                   dict["id"])
1026
1027     def obey_probe(self, dict, text):
1028         id = dict["id"]
1029         if self.subscribers.has_group(id):
1030             self.subscribers.lock()
1031             if self.subscribers.get(id, "status") == "probed":
1032                 self.subscribers.set(id, "status", "probebounced")
1033             self.subscribers.save()
1034
1035     def obey(self, dict):
1036         text = self.read_stdin()
1037
1038         if dict["command"] in ["help", "list", "subscribe", "unsubscribe",
1039                                "subyes", "subapprove", "subreject",
1040                                "unsubyes", "post", "approve"]:
1041             sender = get_from_environ("SENDER")
1042             if not sender:
1043                 debug("Ignoring bounce message for %s command." % 
1044                         dict["command"])
1045                 return
1046
1047         if dict["command"] == "help":
1048             self.obey_help()
1049         elif dict["command"] == "list":
1050             self.obey_list()
1051         elif dict["command"] == "owner":
1052             self.obey_owner(text)
1053         elif dict["command"] == "subscribe":
1054             self.obey_subscribe(dict, text)
1055         elif dict["command"] == "unsubscribe":
1056             self.obey_unsubscribe(dict, text)
1057         elif dict["command"] == "subyes":
1058             self.obey_subyes(dict)
1059         elif dict["command"] == "subapprove":
1060             self.obey_subapprove(dict)
1061         elif dict["command"] == "subreject":
1062             self.obey_subreject(dict)
1063         elif dict["command"] == "unsubyes":
1064             self.obey_unsubyes(dict)
1065         elif dict["command"] == "post":
1066             self.obey_post(dict, text)
1067         elif dict["command"] == "approve":
1068             self.obey_approve(dict)
1069         elif dict["command"] == "reject":
1070             self.obey_reject(dict)
1071         elif dict["command"] == "bounce":
1072             self.obey_bounce(dict, text)
1073         elif dict["command"] == "probe":
1074             self.obey_probe(dict, text)
1075         elif dict["command"] == "setlist":
1076             self.obey_setlist(text)
1077         elif dict["command"] == "setlistsilently":
1078             self.obey_setlistsilently(text)
1079         elif dict["command"] == "setlistyes":
1080             self.obey_setlistyes(dict)
1081         elif dict["command"] == "setlistsilentyes":
1082             self.obey_setlistsilentyes(dict)
1083         elif dict["command"] == "ignore":
1084             pass
1085
1086     def get_bounce_text(self, id):
1087         bounce_id = self.subscribers.get(id, "bounce-id")
1088         if self.bounce_box.has(bounce_id):
1089             bounce_text = self.bounce_box.get(bounce_id)
1090             bounce_text = string.join(map(lambda s: "> " + s + "\n",
1091                                           bounce_text.split("\n")), "")
1092         else:
1093             bounce_text = "Bounce message not available."
1094         return bounce_text
1095
1096     one_week = 7.0 * 24.0 * 60.0 * 60.0
1097
1098     def handle_bounced_groups(self, now):
1099         for id in self.subscribers.groups():
1100             status = self.subscribers.get(id, "status") 
1101             t = float(self.subscribers.get(id, "timestamp-bounced")) 
1102             if status == "bounced":
1103                 if now - t > self.one_week:
1104                     sender = self.signed_address("probe", id) 
1105                     recipients = self.subscribers.in_group(id) 
1106                     self.send_template(sender, sender, recipients,
1107                                        "bounce-warning", {
1108                                         "bounce": self.get_bounce_text(id),
1109                                         "boundary": self.invent_boundary(),
1110                                        })
1111                     self.subscribers.set(id, "status", "probed")
1112             elif status == "probed":
1113                 if now - t > 2 * self.one_week:
1114                     debug(("Cleaning woman: probe didn't bounce " + 
1115                           "for group <%s>, setting status to ok.") % id)
1116                     self.subscribers.set(id, "status", "ok")
1117                     self.bounce_box.remove(
1118                             self.subscribers.get(id, "bounce-id"))
1119             elif status == "probebounced":
1120                 sender = self.command_address("help") 
1121                 for address in self.subscribers.in_group(id):
1122                     if self.cp.get("list", "mail-on-forced-unsubscribe") \
1123                         == "yes":
1124                         self.send_template(sender, sender,
1125                                        self.owners(),
1126                                        "bounce-owner-notification",
1127                                        {
1128                                         "address": address,
1129                                         "bounce": self.get_bounce_text(id),
1130                                         "boundary": self.invent_boundary(),
1131                                        })
1132
1133                     self.bounce_box.remove(
1134                             self.subscribers.get(id, "bounce-id"))
1135                     self.subscribers.remove(address) 
1136                     debug("Cleaning woman: removing <%s>." % address)
1137                     self.send_template(sender, sender, [address],
1138                                        "bounce-goodbye", {})
1139
1140     def join_nonbouncing_groups(self, now):
1141         to_be_joined = []
1142         for id in self.subscribers.groups():
1143             status = self.subscribers.get(id, "status")
1144             age1 = now - float(self.subscribers.get(id, "timestamp-bounced"))
1145             age2 = now - float(self.subscribers.get(id, "timestamp-created"))
1146             if status == "ok":
1147                 if age1 > self.one_week and age2 > self.one_week:
1148                     to_be_joined.append(id)
1149         if to_be_joined:
1150             addrs = []
1151             for id in to_be_joined:
1152                 addrs = addrs + self.subscribers.in_group(id)
1153             self.subscribers.add_many(addrs)
1154             for id in to_be_joined:
1155                 self.bounce_box.remove(self.subscribers.get(id, "bounce-id"))
1156                 self.subscribers.remove_group(id)
1157
1158     def remove_empty_groups(self):
1159         for id in self.subscribers.groups()[:]:
1160             if len(self.subscribers.in_group(id)) == 0:
1161                 self.subscribers.remove_group(id)
1162
1163     def cleaning_woman(self, now):
1164         if self.subscribers.lock():
1165             self.handle_bounced_groups(now)
1166             self.join_nonbouncing_groups(now)
1167             self.subscribers.save()
1168
1169 class SubscriberDatabase:
1170
1171     def __init__(self, dirname, name):
1172         self.dict = {}
1173         self.filename = os.path.join(dirname, name)
1174         self.lockname = os.path.join(dirname, "lock")
1175         self.loaded = 0
1176         self.locked = 0
1177
1178     def lock(self):
1179         if os.system("lockfile -l 60 %s" % self.lockname) == 0:
1180             self.locked = 1
1181             self.load()
1182         return self.locked
1183     
1184     def unlock(self):
1185         os.remove(self.lockname)
1186         self.locked = 0
1187     
1188     def load(self):
1189         if not self.loaded and not self.dict:
1190             f = open(self.filename, "r")
1191             for line in f.xreadlines():
1192                 parts = line.split()
1193                 self.dict[parts[0]] = {
1194                     "status": parts[1],
1195                     "timestamp-created": parts[2],
1196                     "timestamp-bounced": parts[3],
1197                     "bounce-id": parts[4],
1198                     "addresses": parts[5:],
1199                 }
1200             f.close()
1201             self.loaded = 1
1202
1203     def save(self):
1204         assert self.locked
1205         assert self.loaded
1206         f = open(self.filename + ".new", "w")
1207         for id in self.dict.keys():
1208             f.write("%s " % id)
1209             f.write("%s " % self.dict[id]["status"])
1210             f.write("%s " % self.dict[id]["timestamp-created"])
1211             f.write("%s " % self.dict[id]["timestamp-bounced"])
1212             f.write("%s " % self.dict[id]["bounce-id"])
1213             f.write("%s\n" % string.join(self.dict[id]["addresses"], " "))
1214         f.close()
1215         os.remove(self.filename)
1216         os.rename(self.filename + ".new", self.filename)
1217         self.unlock()
1218
1219     def get(self, id, attribute):
1220         self.load()
1221         if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1222             return self.dict[id][attribute]
1223         return None
1224
1225     def set(self, id, attribute, value):
1226         assert self.locked
1227         self.load()
1228         if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1229             self.dict[id][attribute] = value
1230
1231     def add(self, address):
1232         return self.add_many([address])
1233
1234     def add_many(self, addresses):
1235         assert self.locked
1236         assert self.loaded
1237         for addr in addresses[:]:
1238             if addr.find("@") == -1:
1239                 info("Address '%s' does not contain an @, ignoring it." % addr)
1240                 addresses.remove(addr)
1241         for id in self.dict.keys():
1242             old_ones = self.dict[id]["addresses"]
1243             for addr in addresses:
1244                 for x in old_ones:
1245                     if x.lower() == addr.lower():
1246                         old_ones.remove(x)
1247             self.dict[id]["addresses"] = old_ones
1248         id = self.new_group()
1249         self.dict[id] = {
1250             "status": "ok",
1251             "timestamp-created": self.timestamp(),
1252             "timestamp-bounced": "0",
1253             "bounce-id": "..notexist..",
1254             "addresses": addresses,
1255         }
1256         return id
1257
1258     def new_group(self):
1259         keys = self.dict.keys()
1260         if keys:
1261             keys = map(lambda x: int(x), keys)
1262             keys.sort()
1263             return "%d" % (keys[-1] + 1)
1264         else:
1265             return "0"
1266
1267     def timestamp(self):
1268         return "%.0f" % time.time()
1269
1270     def get_all(self):
1271         self.load()
1272         list = []
1273         for values in self.dict.values():
1274             list = list + values["addresses"]
1275         return list
1276
1277     def groups(self):
1278         self.load()
1279         return self.dict.keys()
1280
1281     def has_group(self, id):
1282         self.load()
1283         return self.dict.has_key(id)
1284
1285     def in_group(self, id):
1286         self.load()
1287         return self.dict[id]["addresses"]
1288
1289     def remove(self, address):
1290         assert self.locked
1291         self.load()
1292         for id in self.dict.keys():
1293             group = self.dict[id]
1294             for x in group["addresses"][:]:
1295                 if x.lower() == address.lower():
1296                     group["addresses"].remove(x)
1297                     if len(group["addresses"]) == 0:
1298                         del self.dict[id]
1299
1300     def remove_group(self, id):
1301         assert self.locked
1302         self.load()
1303         del self.dict[id]
1304
1305
1306 class MessageBox:
1307
1308     def __init__(self, dirname, boxname):
1309         self.boxdir = os.path.join(dirname, boxname)
1310         if not os.path.isdir(self.boxdir):
1311             os.mkdir(self.boxdir, 0700)
1312
1313     def filename(self, id):
1314         return os.path.join(self.boxdir, id)
1315
1316     def add(self, address, message_text):
1317         id = self.make_id(message_text)
1318         filename = self.filename(id)
1319         f = open(filename + ".address", "w")
1320         f.write(address)
1321         f.close()
1322         f = open(filename + ".new", "w")
1323         f.write(message_text)
1324         f.close()
1325         os.rename(filename + ".new", filename)
1326         return id
1327
1328     def make_id(self, message_text):
1329         return md5sum_as_hex(message_text)
1330         # XXX this might be unnecessarily long
1331
1332     def remove(self, id):
1333         filename = self.filename(id)
1334         if os.path.isfile(filename):
1335             os.remove(filename)
1336             os.remove(filename + ".address")
1337
1338     def has(self, id):
1339         return os.path.isfile(self.filename(id))
1340
1341     def get_address(self, id):
1342         f = open(self.filename(id) + ".address", "r")
1343         data = f.read()
1344         f.close()
1345         return data.strip()
1346
1347     def get(self, id):
1348         f = open(self.filename(id), "r")
1349         data = f.read()
1350         f.close()
1351         return data
1352
1353     def lockname(self, id):
1354         return self.filename(id) + ".lock"
1355
1356     def lock(self, id):
1357         if os.system("lockfile -l 600 %s" % self.lockname(id)) == 0:
1358             return 1
1359         else:
1360             return 0
1361     
1362     def unlock(self, id):
1363         try:
1364             os.remove(self.lockname(id))
1365         except os.error:
1366             pass
1367     
1368
1369
1370 class DevNull:
1371
1372     def write(self, str):
1373         pass
1374
1375
1376 log_file_handle = None
1377 def log_file():
1378     global log_file_handle
1379     if log_file_handle is None:
1380         try:
1381             log_file_handle = open(os.path.join(DOTDIR, "logfile.txt"), "a")
1382         except:
1383             log_file_handle = DevNull()
1384     return log_file_handle
1385
1386 def timestamp():
1387     tuple = time.localtime(time.time())
1388     return time.strftime("%Y-%m-%d %H:%M:%S", tuple) + " [%d]" % os.getpid()
1389
1390
1391 quiet = 0
1392
1393
1394 # No logging to stderr of debug messages. Some MTAs have a limit on how
1395 # much data they accept via stderr and debug logs will fill that quickly.
1396 def debug(msg):
1397     log_file().write(timestamp() + " " + msg + "\n")
1398
1399
1400 # Log to log file first, in case MTA's stderr buffer fills up and we lose
1401 # logs.
1402 def info(msg):
1403     log_file().write(timestamp() + " " + msg + "\n")
1404     sys.stderr.write(msg + "\n")
1405
1406
1407 def error(msg):
1408     info(msg)
1409     sys.exit(1)
1410
1411
1412 def usage():
1413     sys.stdout.write("""\
1414 Usage: enemies-of-carlotta [options] command
1415 Mailing list manager.
1416
1417 Options:
1418   --name=listname@domain
1419   --owner=address@domain
1420   --moderator=address@domain
1421   --subscription=free/moderated
1422   --posting=free/moderated/auto
1423   --archived=yes/no
1424   --ignore-bounce=yes/no
1425   --language=language code or empty
1426   --mail-on-forced-unsubscribe=yes/no
1427   --mail-on-subscription-changes=yes/no
1428   --skip-prefix=string
1429   --domain=domain.name
1430   --smtp-server=domain.name
1431   --quiet
1432   --moderate
1433
1434 Commands:
1435   --help
1436   --create
1437   --subscribe
1438   --unsubscribe
1439   --list
1440   --is-list
1441   --edit
1442   --incoming
1443   --cleaning-woman
1444   --show-lists
1445
1446 For more detailed information, please read the enemies-of-carlotta(1)
1447 manual page.
1448 """)
1449     sys.exit(0)
1450
1451
1452 def no_act_send_mail(sender, recipients, text):
1453     print "NOT SENDING MAIL FOR REAL!"
1454     print "Sender:", sender
1455     print "Recipients:", recipients
1456     print "Mail:"
1457     print "\n".join(map(lambda s: "   " + s, text.split("\n")))
1458
1459
1460 def set_list_options(list, owners, moderators, subscription, posting, 
1461                      archived, language, ignore_bounce,
1462                      mail_on_sub_changes, mail_on_forced_unsub):
1463     if owners:
1464         list.cp.set("list", "owners", string.join(owners, " "))
1465     if moderators:
1466         list.cp.set("list", "moderators", string.join(moderators, " "))
1467     if subscription != None:
1468         list.cp.set("list", "subscription", subscription)
1469     if posting != None:
1470         list.cp.set("list", "posting", posting)
1471     if archived != None:
1472         list.cp.set("list", "archived", archived)
1473     if language != None:
1474         list.cp.set("list", "language", language)
1475     if ignore_bounce != None:
1476         list.cp.set("list", "ignore-bounce", ignore_bounce)
1477     if mail_on_sub_changes != None:
1478         list.cp.set("list", "mail-on-subscription-changes", 
1479                             mail_on_sub_changes)
1480     if mail_on_forced_unsub != None:
1481         list.cp.set("list", "mail-on-forced-unsubscribe",
1482                             mail_on_forced_unsub)
1483
1484
1485 def main(args):
1486     try:
1487         opts, args = getopt.getopt(args, "h",
1488                                    ["name=",
1489                                     "owner=",
1490                                     "moderator=",
1491                                     "subscription=",
1492                                     "posting=",
1493                                     "archived=",
1494                                     "language=",
1495                                     "ignore-bounce=",
1496                                     "mail-on-forced-unsubscribe=",
1497                                     "mail-on-subscription-changes=",
1498                                     "skip-prefix=",
1499                                     "domain=",
1500                                     "sendmail=",
1501                                     "smtp-server=",
1502                                     "qmqp-server=",
1503                                     "quiet",
1504                                     "moderate",
1505                                     "post",
1506                                     "sender=",
1507                                     "recipient=",
1508                                     "no-act",
1509                                     
1510                                     "set",
1511                                     "get",
1512                                     "help",
1513                                     "create",
1514                                     "destroy",
1515                                     "subscribe",
1516                                     "unsubscribe",
1517                                     "list",
1518                                     "is-list",
1519                                     "edit",
1520                                     "incoming",
1521                                     "cleaning-woman",
1522                                     "show-lists",
1523                                     "version",
1524                                    ])
1525     except getopt.GetoptError, detail:
1526         error("Error parsing command line options (see --help):\n%s" % 
1527               detail)
1528
1529     operation = None
1530     list_name = None
1531     owners = []
1532     moderators = []
1533     subscription = None
1534     posting = None
1535     archived = None
1536     ignore_bounce = None
1537     skip_prefix = None
1538     domain = None
1539     sendmail = "/usr/sbin/sendmail"
1540     smtp_server = None
1541     qmqp_server = None
1542     moderate = 0
1543     post = 0
1544     sender = None
1545     recipient = None
1546     language = None
1547     mail_on_forced_unsub = None
1548     mail_on_sub_changes = None
1549     no_act = 0
1550     global quiet
1551
1552     for opt, arg in opts:
1553         if opt == "--name":
1554             list_name = arg
1555         elif opt == "--owner":
1556             owners.append(arg)
1557         elif opt == "--moderator":
1558             moderators.append(arg)
1559         elif opt == "--subscription":
1560             subscription = arg
1561         elif opt == "--posting":
1562             posting = arg
1563         elif opt == "--archived":
1564             archived = arg
1565         elif opt == "--ignore-bounce":
1566             ignore_bounce = arg
1567         elif opt == "--skip-prefix":
1568             skip_prefix = arg
1569         elif opt == "--domain":
1570             domain = arg
1571         elif opt == "--sendmail":
1572             sendmail = arg
1573         elif opt == "--smtp-server":
1574             smtp_server = arg
1575         elif opt == "--qmqp-server":
1576             qmqp_server = arg
1577         elif opt == "--sender":
1578             sender = arg
1579         elif opt == "--recipient":
1580             recipient = arg
1581         elif opt == "--language":
1582             language = arg
1583         elif opt == "--mail-on-forced-unsubscribe":
1584             mail_on_forced_unsub = arg
1585         elif opt == "--mail-on-subscription-changes":
1586             mail_on_sub_changes = arg
1587         elif opt == "--moderate":
1588             moderate = 1
1589         elif opt == "--post":
1590             post = 1
1591         elif opt == "--quiet":
1592             quiet = 1
1593         elif opt == "--no-act":
1594             no_act = 1
1595         else:
1596             operation = opt
1597
1598     if operation is None:
1599         error("No operation specified, see --help.")
1600
1601     if list_name is None and operation not in ["--incoming", "--help", "-h",
1602                                                "--cleaning-woman",
1603                                                "--show-lists",
1604                                                "--version"]:
1605         error("%s requires a list name specified with --name" % operation)
1606
1607     if operation in ["--help", "-h"]:
1608         usage()
1609
1610     if sender or recipient:
1611         environ = os.environ.copy()
1612         if sender:
1613             environ["SENDER"] = sender
1614         if recipient:
1615             environ["RECIPIENT"] = recipient
1616         set_environ(environ)
1617
1618     mlm = MailingListManager(DOTDIR, sendmail=sendmail, 
1619                              smtp_server=smtp_server,
1620                              qmqp_server=qmqp_server)
1621     if no_act:
1622         mlm.send_mail = no_act_send_mail
1623
1624     if operation == "--create":
1625         if not owners:
1626             error("You must give at least one list owner with --owner.")
1627         list = mlm.create_list(list_name)
1628         set_list_options(list, owners, moderators, subscription, posting, 
1629                          archived, language, ignore_bounce,
1630                          mail_on_sub_changes, mail_on_forced_unsub)
1631         list.save_config()
1632         debug("Created list %s." % list_name)
1633     elif operation == "--destroy":
1634         shutil.rmtree(os.path.join(DOTDIR, list_name))
1635         debug("Removed list %s." % list_name)
1636     elif operation == "--edit":
1637         list = mlm.open_list(list_name)
1638         set_list_options(list, owners, moderators, subscription, posting, 
1639                          archived, language, ignore_bounce,
1640                          mail_on_sub_changes, mail_on_forced_unsub)
1641         list.save_config()
1642     elif operation == "--subscribe":
1643         list = mlm.open_list(list_name)
1644         list.subscribers.lock()
1645         for address in args:
1646             if address.find("@") == -1:
1647                 error("Address '%s' does not contain an @." % address)
1648             list.subscribers.add(address)
1649             debug("Added subscriber <%s>." % address)
1650         list.subscribers.save()
1651     elif operation == "--unsubscribe":
1652         list = mlm.open_list(list_name)
1653         list.subscribers.lock()
1654         for address in args:
1655             list.subscribers.remove(address)
1656             debug("Removed subscriber <%s>." % address)
1657         list.subscribers.save()
1658     elif operation == "--list":
1659         list = mlm.open_list(list_name)
1660         for address in list.subscribers.get_all():
1661             print address
1662     elif operation == "--is-list":
1663         if mlm.is_list(list_name, skip_prefix, domain):
1664             debug("Indeed a mailing list: <%s>" % list_name)
1665         else:
1666             debug("Not a mailing list: <%s>" % list_name)
1667             sys.exit(1)
1668     elif operation == "--incoming":
1669         mlm.incoming_message(skip_prefix, domain, moderate, post)
1670     elif operation == "--cleaning-woman":
1671         mlm.cleaning_woman()
1672     elif operation == "--show-lists":
1673         listnames = mlm.get_lists()
1674         listnames.sort()
1675         for listname in listnames:
1676             print listname
1677     elif operation == "--get":
1678         list = mlm.open_list(list_name)
1679         for name in args:
1680             print list.cp.get("list", name)
1681     elif operation == "--set":
1682         list = mlm.open_list(list_name)
1683         for arg in args:
1684             if "=" not in arg:
1685                 error("Error: --set arguments must be of form name=value")
1686             name, value = arg.split("=", 1)
1687             list.cp.set("list", name, value)
1688         list.save_config()
1689     elif operation == "--version":
1690         print "EoC, version %s" % VERSION
1691         print "Home page: http://liw.iki.fi/liw/eoc/"
1692     else:
1693         error("Internal error: unimplemented option <%s>." % operation)
1694
1695 if __name__ == "__main__":
1696     try:
1697         main(sys.argv[1:])
1698     except EocException, detail:
1699         error("Error: %s" % detail)