1 """Mailing list manager.
3 This is a simple mailing list manager that mimicks the ezmlm-idx mail
4 address commands. See manual page for more information.
8 PLUGIN_INTERFACE_VERSION = "1"
29 # The following values will be overriden by "make install".
30 TEMPLATE_DIRS = ["./templates"]
34 class EocException(Exception):
36 def __init__(self, arg=None):
42 class UnknownList(EocException):
43 def __init__(self, list_name):
44 self.msg = "%s is not a known mailing list" % list_name
46 class BadCommandAddress(EocException):
47 def __init__(self, address):
48 self.msg = "%s is not a valid command address" % address
50 class BadSignature(EocException):
51 def __init__(self, address):
52 self.msg = "address %s has an invalid digital signature" % address
54 class ListExists(EocException):
55 def __init__(self, list_name):
56 self.msg = "Mailing list %s alreadys exists" % list_name
58 class ListDoesNotExist(EocException):
59 def __init__(self, list_name):
60 self.msg = "Mailing list %s does not exist" % list_name
62 class MissingEnvironmentVariable(EocException):
63 def __init__(self, name):
64 self.msg = "Environment variable %s does not exist" % name
66 class MissingTemplate(EocException):
67 def __init__(self, template):
68 self.msg = "Template %s does not exit" % template
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",
77 COMMANDS = SIMPLE_COMMANDS + SUB_COMMANDS + HASH_COMMANDS
81 return hashlib.md5(s).hexdigest()
83 def forkexec(argv, text):
84 """Run a command (given as argv array) and write text to its stdin"""
88 raise Exception("fork failed")
93 fd = os.open("/dev/null", os.O_RDWR)
96 os.execvp(argv[0], argv)
102 (pid2, exit) = os.waitpid(pid, 0)
104 raise Exception("os.waitpid for %d returned for %d" % (pid, pid2))
106 raise Exception("subprocess failed, exit=0x%x" % exit)
112 def set_environ(new_environ):
114 environ = new_environ
116 def get_from_environ(key):
123 return env[key].lower()
124 raise MissingEnvironmentVariable(key)
128 """A parser for incoming e-mail addresses."""
130 def __init__(self, lists):
131 self.set_lists(lists)
132 self.set_skip_prefix(None)
133 self.set_forced_domain(None)
135 def set_lists(self, lists):
136 """Set the list of canonical list names we should know about."""
139 def set_skip_prefix(self, skip_prefix):
140 """Set the prefix to be removed from an address."""
141 self.skip_prefix = skip_prefix
143 def set_forced_domain(self, forced_domain):
144 """Set the domain part we should force the address to have."""
145 self.forced_domain = forced_domain
147 def clean(self, address):
148 """Remove cruft from the address and convert the rest to lower case."""
150 n = self.skip_prefix and len(self.skip_prefix)
151 if address[:n] == self.skip_prefix:
152 address = address[n:]
153 if self.forced_domain:
154 parts = address.split("@", 1)
155 address = "%s@%s" % (parts[0], self.forced_domain)
156 return address.lower()
158 def split_address(self, address):
159 """Split an address to a local part and a domain."""
160 parts = address.lower().split("@", 1)
166 # Does an address refer to a list? If not, return None, else return a list
167 # of additional parts (separated by hyphens) in the address. Note that []
168 # is not the same as None.
170 def additional_address_parts(self, address, listname):
171 addr_local, addr_domain = self.split_address(address)
172 list_local, list_domain = self.split_address(listname)
174 if addr_domain != list_domain:
177 if addr_local.lower() == list_local.lower():
181 if addr_local[:n] != list_local or addr_local[n] != "-":
184 return addr_local[n+1:].split("-")
187 # Parse an address we have received that identifies a list we manage.
188 # The address may contain command and signature parts. Return the name
189 # of the list, and a sequence of the additional parts (split at hyphens).
190 # Raise exceptions for errors. Note that the command will be valid, but
191 # cryptographic signatures in the address is not checked.
193 def parse(self, address):
194 address = self.clean(address)
195 for listname in self.lists:
196 parts = self.additional_address_parts(address, listname)
200 return listname, parts
201 elif parts[0] in HASH_COMMANDS:
203 raise BadCommandAddress(address)
204 return listname, parts
205 elif parts[0] in COMMANDS:
206 return listname, parts
208 raise UnknownList(address)
211 class MailingListManager:
213 def __init__(self, dotdir, sendmail="/usr/sbin/sendmail", lists=[],
214 smtp_server=None, qmqp_server=None):
216 self.sendmail = sendmail
217 self.smtp_server = smtp_server
218 self.qmqp_server = qmqp_server
221 self.secret = self.make_and_read_secret()
224 lists = filter(lambda s: "@" in s, os.listdir(dotdir))
225 self.set_lists(lists)
227 self.simple_commands = ["help", "list", "owner", "setlist",
228 "setlistsilently", "ignore"]
229 self.sub_commands = ["subscribe", "unsubscribe"]
230 self.hash_commands = ["subyes", "subapprove", "subreject", "unsubyes",
231 "bounce", "probe", "approve", "reject",
232 "setlistyes", "setlistsilentyes"]
233 self.commands = self.simple_commands + self.sub_commands + \
240 # Create the dot directory for us, if it doesn't exist already.
241 def make_dotdir(self):
242 if not os.path.isdir(self.dotdir):
243 os.makedirs(self.dotdir, 0700)
245 # Create the "secret" file, with a random value used as cookie for
246 # verification addresses.
247 def make_and_read_secret(self):
248 secret_name = os.path.join(self.dotdir, "secret")
249 if not os.path.isfile(secret_name):
250 f = open("/dev/urandom", "r")
253 f = open(secret_name, "w")
257 f = open(secret_name, "r")
262 # Load the plugins from DOTDIR/plugins/*.py.
263 def load_plugins(self):
266 dirname = os.path.join(DOTDIR, "plugins")
268 plugins = os.listdir(dirname)
273 plugins = map(os.path.splitext, plugins)
274 plugins = filter(lambda p: p[1] == ".py", plugins)
275 plugins = map(lambda p: p[0], plugins)
277 pathname = os.path.join(dirname, name + ".py")
278 f = open(pathname, "r")
279 module = imp.load_module(name, f, pathname,
280 (".py", "r", imp.PY_SOURCE))
282 if module.PLUGIN_INTERFACE_VERSION == PLUGIN_INTERFACE_VERSION:
283 self.plugins.append(module)
285 # Call function named funcname (a string) in all plugins, giving as
286 # arguments all the remaining arguments preceded by ml. Return value
287 # of each function is the new list of arguments to the next function.
288 # Return value of this function is the return value of the last function.
289 def call_plugins(self, funcname, list, *args):
290 for plugin in self.plugins:
291 if plugin.__dict__.has_key(funcname):
292 args = apply(plugin.__dict__[funcname], (list,) + args)
293 if type(args) != type((0,)):
297 # Set the list of listnames. The list of lists needs to be sorted in
298 # length order so that test@example.com is matched before
299 # test-list@example.com
300 def set_lists(self, lists):
301 temp = map(lambda s: (len(s), s), lists)
303 self.lists = map(lambda t: t[1], temp)
305 # Return the list of listnames.
309 # Decode an address that has been encoded to be part of a local part.
310 def decode_address(self, parts):
311 return string.join(string.join(parts, "-").split("="), "@")
313 # Is local_part@domain an existing list?
314 def is_list_name(self, local_part, domain):
315 return ("%s@%s" % (local_part, domain)) in self.lists
317 # Compute the verification checksum for an address.
318 def compute_hash(self, address):
319 return md5sum_as_hex(address + self.secret)
321 # Is the verification signature in a parsed address bad? If so, return true,
322 # otherwise return false.
323 def signature_is_bad(self, dict, hash):
324 local_part, domain = dict["name"].split("@")
325 address = "%s-%s-%s@%s" % (local_part, dict["command"], dict["id"],
327 correct = self.compute_hash(address)
328 return correct != hash
330 # Parse a command address we have received and check its validity
331 # (including signature, if any). Return a dictionary with keys
332 # "command", "sender" (address that was encoded into address, if
333 # any), "id" (group ID).
335 def parse_recipient_address(self, address, skip_prefix, forced_domain):
336 ap = AddressParser(self.get_lists())
337 ap.set_lists(self.get_lists())
338 ap.set_skip_prefix(skip_prefix)
339 ap.set_forced_domain(forced_domain)
340 listname, parts = ap.parse(address)
342 dict = { "name": listname }
345 dict["command"] = "post"
347 command, args = parts[0], parts[1:]
348 dict["command"] = command
349 if command in SUB_COMMANDS:
350 dict["sender"] = self.decode_address(args)
351 elif command in HASH_COMMANDS:
354 if self.signature_is_bad(dict, hash):
355 raise BadSignature(address)
359 # Does an address refer to a mailing list?
360 def is_list(self, name, skip_prefix=None, domain=None):
362 self.parse_recipient_address(name, skip_prefix, domain)
363 except BadCommandAddress:
371 # Create a new list and return it.
372 def create_list(self, name):
373 if self.is_list(name):
374 raise ListExists(name)
375 self.set_lists(self.lists + [name])
376 return MailingList(self, name)
378 # Open an existing list.
379 def open_list(self, name):
380 if self.is_list(name):
381 return self.open_list_exact(name)
384 for list in self.lists:
385 if list[:len(x)] == x:
386 return self.open_list_exact(list)
387 raise ListDoesNotExist(name)
389 def open_list_exact(self, name):
390 for list in self.get_lists():
391 if list.lower() == name.lower():
392 return MailingList(self, list)
393 raise ListDoesNotExist(name)
395 # Process an incoming message.
396 def incoming_message(self, skip_prefix, domain, moderate, post):
397 debug("Processing incoming message.")
398 debug("$SENDER = <%s>" % get_from_environ("SENDER"))
399 debug("$RECIPIENT = <%s>" % get_from_environ("RECIPIENT"))
400 dict = self.parse_recipient_address(get_from_environ("RECIPIENT"),
403 dict["force-moderation"] = moderate
404 dict["force-posting"] = post
405 debug("List is <%(name)s>, command is <%(command)s>." % dict)
406 list = self.open_list_exact(dict["name"])
409 # Clean up bouncing address and do other janitorial work for all lists.
410 def cleaning_woman(self, send_mail=None):
412 for listname in self.lists:
413 list = self.open_list_exact(listname)
415 list.send_mail = send_mail
416 list.cleaning_woman(now)
418 # Send a mail to the desired recipients.
419 def send_mail(self, envelope_sender, recipients, text):
420 debug("send_mail:\n sender=%s\n recipients=%s\n text=\n %s" %
421 (envelope_sender, str(recipients),
422 "\n ".join(text[:text.find("\n\n")].split("\n"))))
426 smtp = smtplib.SMTP(self.smtp_server)
427 smtp.sendmail(envelope_sender, recipients, text)
430 error("Error sending SMTP mail, mail probably not sent")
432 elif self.qmqp_server:
434 q = qmqp.QMQP(self.qmqp_server)
435 q.sendmail(envelope_sender, recipients, text)
438 error("Error sending QMQP mail, mail probably not sent")
441 status = forkexec([self.sendmail, "-oi", "-f",
442 envelope_sender] + recipients, text)
444 error("%s returned %s, mail sending probably failed" %
445 (self.sendmail, status))
446 sys.exit((status >> 8) & 0xff)
448 debug("send_mail: no recipients, not sending")
454 posting_opts = ["auto", "free", "moderated"]
456 def __init__(self, mlm, name):
460 self.cp = ConfigParser.ConfigParser()
461 self.cp.add_section("list")
462 self.cp.set("list", "owners", "")
463 self.cp.set("list", "moderators", "")
464 self.cp.set("list", "subscription", "free")
465 self.cp.set("list", "posting", "free")
466 self.cp.set("list", "archived", "no")
467 self.cp.set("list", "mail-on-subscription-changes", "no")
468 self.cp.set("list", "mail-on-forced-unsubscribe", "no")
469 self.cp.set("list", "ignore-bounce", "no")
470 self.cp.set("list", "language", "")
471 self.cp.set("list", "pristine-headers", "")
473 self.dirname = os.path.join(self.mlm.dotdir, name)
475 self.cp.read(self.mkname("config"))
477 self.subscribers = SubscriberDatabase(self.dirname, "subscribers")
478 self.moderation_box = MessageBox(self.dirname, "moderation-box")
479 self.subscription_box = MessageBox(self.dirname, "subscription-box")
480 self.bounce_box = MessageBox(self.dirname, "bounce-box")
482 def make_listdir(self):
483 if not os.path.isdir(self.dirname):
484 os.mkdir(self.dirname, 0700)
486 f = open(self.mkname("subscribers"), "w")
489 def mkname(self, relative):
490 return os.path.join(self.dirname, relative)
492 def save_config(self):
493 f = open(self.mkname("config"), "w")
497 def read_stdin(self):
498 data = sys.stdin.read()
499 # Convert CRLF to plain LF
500 data = "\n".join(data.split("\r\n"))
501 # Skip Unix mbox "From " mail start indicator
502 if data[:5] == "From ":
503 data = string.split(data, "\n", 1)[1]
506 def invent_boundary(self):
507 return "%s/%s" % (md5sum_as_hex(str(time.time())),
508 md5sum_as_hex(self.name))
510 def command_address(self, command):
511 local_part, domain = self.name.split("@")
512 return "%s-%s@%s" % (local_part, command, domain)
514 def signed_address(self, command, id):
515 unsigned = self.command_address("%s-%s" % (command, id))
516 hash = self.mlm.compute_hash(unsigned)
517 return self.command_address("%s-%s-%s" % (command, id, hash))
520 return self.command_address("ignore")
522 def nice_7bit(self, str):
524 if (ord(c) < 32 and not c.isspace()) or ord(c) >= 127:
528 def mime_encode_headers(self, text):
530 headers, body = text.split("\n\n", 1)
533 for line in headers.split("\n"):
534 if line[0].isspace():
541 if self.nice_7bit(header):
542 headers.append(header)
545 name, content = header.split(": ", 1)
547 name, content = header.split(":", 1)
548 hdr = email.Header.Header(content, "utf-8")
549 headers.append(name + ": " + hdr.encode())
551 return "\n".join(headers) + "\n\n" + body
553 info("Cannot MIME encode header, using original ones, sorry")
556 def template(self, template_name, dict):
557 lang = self.cp.get("list", "language")
559 template_name_lang = template_name + "." + lang
561 template_name_lang = template_name
563 if not dict.has_key("list"):
564 dict["list"] = self.name
565 dict["local"], dict["domain"] = self.name.split("@")
566 if not dict.has_key("list"):
567 dict["list"] = self.name
569 for dir in [os.path.join(self.dirname, "templates")] + TEMPLATE_DIRS:
570 pathname = os.path.join(dir, template_name_lang)
571 if not os.path.exists(pathname):
572 pathname = os.path.join(dir, template_name)
573 if os.path.exists(pathname):
574 f = open(pathname, "r")
579 raise MissingTemplate(template_name)
581 def send_template(self, envelope_sender, sender, recipients,
582 template_name, dict):
583 dict["From"] = "EoC <%s>" % sender
584 dict["To"] = string.join(recipients, ", ")
585 text = self.template(template_name, dict)
588 if self.cp.get("list", "pristine-headers") != "yes":
589 text = self.mime_encode_headers(text)
590 self.mlm.send_mail(envelope_sender, recipients, text)
592 def send_info_message(self, recipients, template_name, dict):
593 self.send_template(self.command_address("ignore"),
594 self.command_address("help"),
600 return self.cp.get("list", "owners").split()
602 def moderators(self):
603 return self.cp.get("list", "moderators").split()
605 def is_list_owner(self, address):
606 return address in self.owners()
609 self.send_info_message([get_from_environ("SENDER")], "help", {})
612 recipient = get_from_environ("SENDER")
613 if self.is_list_owner(recipient):
614 addr_list = self.subscribers.get_all()
615 addr_text = string.join(addr_list, "\n")
616 self.send_info_message([recipient], "list",
618 "addresses": addr_text,
619 "count": len(addr_list),
622 self.send_info_message([recipient], "list-sorry", {})
624 def obey_setlist(self, origmail):
625 recipient = get_from_environ("SENDER")
626 if self.is_list_owner(recipient):
627 id = self.moderation_box.add(recipient, origmail)
628 if self.parse_setlist_addresses(origmail) == None:
629 self.send_bad_addresses_in_setlist(id)
630 self.moderation_box.remove(id)
632 confirm = self.signed_address("setlistyes", id)
633 self.send_info_message(self.owners(), "setlist-confirm",
636 "origmail": origmail,
637 "boundary": self.invent_boundary(),
641 self.send_info_message([recipient], "setlist-sorry", {})
643 def obey_setlistsilently(self, origmail):
644 recipient = get_from_environ("SENDER")
645 if self.is_list_owner(recipient):
646 id = self.moderation_box.add(recipient, origmail)
647 if self.parse_setlist_addresses(origmail) == None:
648 self.send_bad_addresses_in_setlist(id)
649 self.moderation_box.remove(id)
651 confirm = self.signed_address("setlistsilentyes", id)
652 self.send_info_message(self.owners(), "setlist-confirm",
655 "origmail": origmail,
656 "boundary": self.invent_boundary(),
659 self.send_info_message([recipient], "setlist-sorry", {})
661 def parse_setlist_addresses(self, text):
662 body = text.split("\n\n", 1)[1]
663 lines = body.split("\n")
664 lines = filter(lambda line: line != "", lines)
665 badlines = filter(lambda line: "@" not in line, lines)
671 def send_bad_addresses_in_setlist(self, id):
672 addr = self.moderation_box.get_address(id)
673 origmail = self.moderation_box.get(id)
674 self.send_info_message([addr], "setlist-badlist",
676 "origmail": origmail,
677 "boundary": self.invent_boundary(),
681 def obey_setlistyes(self, dict):
682 if self.moderation_box.has(dict["id"]):
683 text = self.moderation_box.get(dict["id"])
684 addresses = self.parse_setlist_addresses(text)
685 if addresses == None:
686 self.send_bad_addresses_in_setlist(id)
688 removed_subscribers = []
689 self.subscribers.lock()
690 old = self.subscribers.get_all()
692 if address.lower() not in map(string.lower, addresses):
693 self.subscribers.remove(address)
694 removed_subscribers.append(address)
697 if x.lower() == address.lower():
699 self.subscribers.add_many(addresses)
700 self.subscribers.save()
702 for recipient in addresses:
703 self.send_info_message([recipient], "sub-welcome", {})
704 for recipient in removed_subscribers:
705 self.send_info_message([recipient], "unsub-goodbye", {})
706 self.send_info_message(self.owners(), "setlist-done", {})
708 self.moderation_box.remove(dict["id"])
710 def obey_setlistsilentyes(self, dict):
711 if self.moderation_box.has(dict["id"]):
712 text = self.moderation_box.get(dict["id"])
713 addresses = self.parse_setlist_addresses(text)
714 if addresses == None:
715 self.send_bad_addresses_in_setlist(id)
717 self.subscribers.lock()
718 old = self.subscribers.get_all()
720 if address not in addresses:
721 self.subscribers.remove(address)
723 addresses.remove(address)
724 self.subscribers.add_many(addresses)
725 self.subscribers.save()
726 self.send_info_message(self.owners(), "setlist-done", {})
728 self.moderation_box.remove(dict["id"])
730 def obey_owner(self, text):
731 sender = get_from_environ("SENDER")
732 recipients = self.cp.get("list", "owners").split()
733 self.mlm.send_mail(sender, recipients, text)
735 def obey_subscribe_or_unsubscribe(self, dict, template_name, command,
738 requester = get_from_environ("SENDER")
739 subscriber = dict["sender"]
741 subscriber = requester
742 if subscriber.find("@") == -1:
743 info("Trying to (un)subscribe address without @: %s" % subscriber)
745 if self.cp.get("list", "ignore-bounce") == "yes":
746 info("Will not (un)subscribe address: %s from static list" %subscriber)
748 if requester in self.owners():
749 confirmers = self.owners()
751 confirmers = [subscriber]
753 id = self.subscription_box.add(subscriber, origmail)
754 confirm = self.signed_address(command, id)
755 self.send_info_message(confirmers, template_name,
758 "origmail": origmail,
759 "boundary": self.invent_boundary(),
762 def obey_subscribe(self, dict, origmail):
763 self.obey_subscribe_or_unsubscribe(dict, "sub-confirm", "subyes",
766 def obey_unsubscribe(self, dict, origmail):
767 self.obey_subscribe_or_unsubscribe(dict, "unsub-confirm", "unsubyes",
770 def obey_subyes(self, dict):
771 if self.subscription_box.has(dict["id"]):
772 if self.cp.get("list", "subscription") == "free":
773 recipient = self.subscription_box.get_address(dict["id"])
774 self.subscribers.lock()
775 self.subscribers.add(recipient)
776 self.subscribers.save()
777 sender = self.command_address("help")
778 self.send_template(self.ignore(), sender, [recipient],
780 self.subscription_box.remove(dict["id"])
781 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
782 self.send_info_message(self.owners(),
783 "sub-owner-notification",
785 "address": recipient,
788 recipients = self.cp.get("list", "owners").split()
789 confirm = self.signed_address("subapprove", dict["id"])
790 deny = self.signed_address("subreject", dict["id"])
791 subscriber = self.subscription_box.get_address(dict["id"])
792 origmail = self.subscription_box.get(dict["id"])
793 self.send_template(self.ignore(), deny, recipients,
798 "subscriber": subscriber,
799 "origmail": origmail,
800 "boundary": self.invent_boundary(),
802 recipient = self.subscription_box.get_address(dict["id"])
803 self.send_info_message([recipient], "sub-wait", {})
805 def obey_subapprove(self, dict):
806 if self.subscription_box.has(dict["id"]):
807 recipient = self.subscription_box.get_address(dict["id"])
808 self.subscribers.lock()
809 self.subscribers.add(recipient)
810 self.subscribers.save()
811 self.send_info_message([recipient], "sub-welcome", {})
812 self.subscription_box.remove(dict["id"])
813 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
814 self.send_info_message(self.owners(), "sub-owner-notification",
816 "address": recipient,
819 def obey_subreject(self, dict):
820 if self.subscription_box.has(dict["id"]):
821 recipient = self.subscription_box.get_address(dict["id"])
822 self.send_info_message([recipient], "sub-reject", {})
823 self.subscription_box.remove(dict["id"])
825 def obey_unsubyes(self, dict):
826 if self.subscription_box.has(dict["id"]):
827 recipient = self.subscription_box.get_address(dict["id"])
828 self.subscribers.lock()
829 self.subscribers.remove(recipient)
830 self.subscribers.save()
831 self.send_info_message([recipient], "unsub-goodbye", {})
832 self.subscription_box.remove(dict["id"])
833 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
834 self.send_info_message(self.owners(),
835 "unsub-owner-notification",
837 "address": recipient,
840 def store_into_archive(self, text):
841 if self.cp.get("list", "archived") == "yes":
842 archdir = os.path.join(self.dirname, "archive")
843 if not os.path.exists(archdir):
844 os.mkdir(archdir, 0700)
845 id = md5sum_as_hex(text)
846 f = open(os.path.join(archdir, id), "w")
850 def list_headers(self):
851 local, domain = self.name.split("@")
853 list.append("List-Id: <%s.%s>" % (local, domain))
854 list.append("List-Help: <mailto:%s-help@%s>" % (local, domain))
855 list.append("List-Unsubscribe: <mailto:%s-unsubscribe@%s>" %
857 list.append("List-Subscribe: <mailto:%s-subscribe@%s>" %
859 list.append("List-Post: <mailto:%s@%s>" % (local, domain))
860 list.append("List-Owner: <mailto:%s-owner@%s>" % (local, domain))
861 list.append("Precedence: bulk");
862 return string.join(list, "\n") + "\n"
864 def read_file(self, basename):
866 f = open(os.path.join(self.dirname, basename), "r")
873 def headers_to_add(self):
874 headers_to_add = self.read_file("headers-to-add").rstrip()
876 return headers_to_add + "\n"
880 def remove_some_headers(self, mail, headers_to_remove):
881 endpos = mail.find("\n\n")
883 endpos = mail.find("\n\r\n")
886 headers = mail[:endpos].split("\n")
889 headers_to_remove = [x.lower() for x in headers_to_remove]
892 add_continuation_lines = 0
894 for header in headers:
895 if header[0] in [' ','\t']:
896 # this is a continuation line
897 if add_continuation_lines:
898 remaining.append(header)
900 pos = header.find(":")
902 # malformed message, try to remove the junk
903 add_continuation_lines = 0
905 name = header[:pos].lower()
906 if name in headers_to_remove:
907 add_continuation_lines = 0
909 add_continuation_lines = 1
910 remaining.append(header)
912 return "\n".join(remaining) + body
914 def headers_to_remove(self, text):
915 headers_to_remove = self.read_file("headers-to-remove").split("\n")
916 headers_to_remove = map(lambda s: s.strip().lower(),
918 return self.remove_some_headers(text, headers_to_remove)
920 def append_footer(self, text):
921 if "base64" in text or "BASE64" in text:
923 for line in StringIO.StringIO(text):
924 if line.lower().startswith("content-transfer-encoding:") and \
925 "base64" in line.lower():
927 return text + self.template("footer", {})
929 def send_mail_to_subscribers(self, text):
930 text = self.remove_some_headers(text, ["list-id", "list-help",
932 "list-subscribe", "list-post",
933 "list-owner", "precedence"])
934 text = self.headers_to_add() + self.list_headers() + \
935 self.headers_to_remove(text)
936 text = self.append_footer(text)
937 text, = self.mlm.call_plugins("send_mail_to_subscribers_hook",
939 if have_email_module and \
940 self.cp.get("list", "pristine-headers") != "yes":
941 text = self.mime_encode_headers(text)
942 self.store_into_archive(text)
943 for group in self.subscribers.groups():
944 bounce = self.signed_address("bounce", group)
945 addresses = self.subscribers.in_group(group)
946 self.mlm.send_mail(bounce, addresses, text)
948 def post_into_moderate(self, poster, dict, text):
949 id = self.moderation_box.add(poster, text)
950 recipients = self.moderators()
952 recipients = self.owners()
954 confirm = self.signed_address("approve", id)
955 deny = self.signed_address("reject", id)
956 self.send_template(self.ignore(), deny, recipients, "msg-moderate",
961 "boundary": self.invent_boundary(),
963 self.send_info_message([poster], "msg-wait", {})
965 def should_be_moderated(self, posting, poster):
966 if posting == "moderated":
968 if posting == "auto":
969 if poster.lower() not in \
970 map(string.lower, self.subscribers.get_all()):
974 def obey_post(self, dict, text):
975 if dict.has_key("force-moderation") and dict["force-moderation"]:
979 if dict.has_key("force-posting") and dict["force-posting"]:
983 posting = self.cp.get("list", "posting")
984 if posting not in self.posting_opts:
985 error("You have a weird 'posting' config. Please, review it")
986 poster = get_from_environ("SENDER")
988 self.post_into_moderate(poster, dict, text)
990 self.send_mail_to_subscribers(text)
991 elif self.should_be_moderated(posting, poster):
992 self.post_into_moderate(poster, dict, text)
994 self.send_mail_to_subscribers(text)
996 def obey_approve(self, dict):
997 if self.moderation_box.lock(dict["id"]):
998 if self.moderation_box.has(dict["id"]):
999 text = self.moderation_box.get(dict["id"])
1000 self.send_mail_to_subscribers(text)
1001 self.moderation_box.remove(dict["id"])
1002 self.moderation_box.unlock(dict["id"])
1004 def obey_reject(self, dict):
1005 if self.moderation_box.lock(dict["id"]):
1006 if self.moderation_box.has(dict["id"]):
1007 self.moderation_box.remove(dict["id"])
1008 self.moderation_box.unlock(dict["id"])
1010 def split_address_list(self, addrs):
1013 userpart, domain = addr.split("@")
1014 if domains.has_key(domain):
1015 domains[domain].append(addr)
1017 domains[domain] = [addr]
1019 if len(domains.keys()) == 1:
1021 result.append([addr])
1023 result = domains.values()
1026 def obey_bounce(self, dict, text):
1027 if self.subscribers.has_group(dict["id"]):
1028 self.subscribers.lock()
1029 addrs = self.subscribers.in_group(dict["id"])
1031 if self.cp.get("list", "ignore-bounce") == "yes":
1032 info("Address <%s> bounced, ignoring bounce as configured." %
1034 self.subscribers.unlock()
1036 debug("Address <%s> bounced, setting state to bounce." %
1038 bounce_id = self.bounce_box.add(addrs[0], text[:4096])
1039 self.subscribers.set(dict["id"], "status", "bounced")
1040 self.subscribers.set(dict["id"], "timestamp-bounced",
1042 self.subscribers.set(dict["id"], "bounce-id",
1045 debug("Group %s bounced, splitting." % dict["id"])
1046 for new_addrs in self.split_address_list(addrs):
1047 self.subscribers.add_many(new_addrs)
1048 self.subscribers.remove_group(dict["id"])
1049 self.subscribers.save()
1051 debug("Ignoring bounce, group %s doesn't exist (anymore?)." %
1054 def obey_probe(self, dict, text):
1056 if self.subscribers.has_group(id):
1057 self.subscribers.lock()
1058 if self.subscribers.get(id, "status") == "probed":
1059 self.subscribers.set(id, "status", "probebounced")
1060 self.subscribers.save()
1062 def obey(self, dict):
1063 text = self.read_stdin()
1065 if dict["command"] in ["help", "list", "subscribe", "unsubscribe",
1066 "subyes", "subapprove", "subreject",
1067 "unsubyes", "post", "approve"]:
1068 sender = get_from_environ("SENDER")
1070 debug("Ignoring bounce message for %s command." %
1074 if dict["command"] == "help":
1076 elif dict["command"] == "list":
1078 elif dict["command"] == "owner":
1079 self.obey_owner(text)
1080 elif dict["command"] == "subscribe":
1081 self.obey_subscribe(dict, text)
1082 elif dict["command"] == "unsubscribe":
1083 self.obey_unsubscribe(dict, text)
1084 elif dict["command"] == "subyes":
1085 self.obey_subyes(dict)
1086 elif dict["command"] == "subapprove":
1087 self.obey_subapprove(dict)
1088 elif dict["command"] == "subreject":
1089 self.obey_subreject(dict)
1090 elif dict["command"] == "unsubyes":
1091 self.obey_unsubyes(dict)
1092 elif dict["command"] == "post":
1093 self.obey_post(dict, text)
1094 elif dict["command"] == "approve":
1095 self.obey_approve(dict)
1096 elif dict["command"] == "reject":
1097 self.obey_reject(dict)
1098 elif dict["command"] == "bounce":
1099 self.obey_bounce(dict, text)
1100 elif dict["command"] == "probe":
1101 self.obey_probe(dict, text)
1102 elif dict["command"] == "setlist":
1103 self.obey_setlist(text)
1104 elif dict["command"] == "setlistsilently":
1105 self.obey_setlistsilently(text)
1106 elif dict["command"] == "setlistyes":
1107 self.obey_setlistyes(dict)
1108 elif dict["command"] == "setlistsilentyes":
1109 self.obey_setlistsilentyes(dict)
1110 elif dict["command"] == "ignore":
1113 def get_bounce_text(self, id):
1114 bounce_id = self.subscribers.get(id, "bounce-id")
1115 if self.bounce_box.has(bounce_id):
1116 bounce_text = self.bounce_box.get(bounce_id)
1117 bounce_text = string.join(map(lambda s: "> " + s + "\n",
1118 bounce_text.split("\n")), "")
1120 bounce_text = "Bounce message not available."
1123 one_week = 7.0 * 24.0 * 60.0 * 60.0
1125 def handle_bounced_groups(self, now):
1126 for id in self.subscribers.groups():
1127 status = self.subscribers.get(id, "status")
1128 t = float(self.subscribers.get(id, "timestamp-bounced"))
1129 if status == "bounced":
1130 if now - t > self.one_week:
1131 sender = self.signed_address("probe", id)
1132 recipients = self.subscribers.in_group(id)
1133 self.send_template(sender, sender, recipients,
1135 "bounce": self.get_bounce_text(id),
1136 "boundary": self.invent_boundary(),
1138 self.subscribers.set(id, "status", "probed")
1139 elif status == "probed":
1140 if now - t > 2 * self.one_week:
1141 debug(("Cleaning woman: probe didn't bounce " +
1142 "for group <%s>, setting status to ok.") % id)
1143 self.subscribers.set(id, "status", "ok")
1144 self.bounce_box.remove(
1145 self.subscribers.get(id, "bounce-id"))
1146 elif status == "probebounced":
1147 sender = self.command_address("help")
1148 for address in self.subscribers.in_group(id):
1149 if self.cp.get("list", "mail-on-forced-unsubscribe") \
1151 self.send_template(sender, sender,
1153 "bounce-owner-notification",
1156 "bounce": self.get_bounce_text(id),
1157 "boundary": self.invent_boundary(),
1160 self.bounce_box.remove(
1161 self.subscribers.get(id, "bounce-id"))
1162 self.subscribers.remove(address)
1163 debug("Cleaning woman: removing <%s>." % address)
1164 self.send_template(sender, sender, [address],
1165 "bounce-goodbye", {})
1167 def join_nonbouncing_groups(self, now):
1169 for id in self.subscribers.groups():
1170 status = self.subscribers.get(id, "status")
1171 age1 = now - float(self.subscribers.get(id, "timestamp-bounced"))
1172 age2 = now - float(self.subscribers.get(id, "timestamp-created"))
1174 if age1 > self.one_week and age2 > self.one_week:
1175 to_be_joined.append(id)
1178 for id in to_be_joined:
1179 addrs = addrs + self.subscribers.in_group(id)
1180 self.subscribers.add_many(addrs)
1181 for id in to_be_joined:
1182 self.bounce_box.remove(self.subscribers.get(id, "bounce-id"))
1183 self.subscribers.remove_group(id)
1185 def remove_empty_groups(self):
1186 for id in self.subscribers.groups()[:]:
1187 if len(self.subscribers.in_group(id)) == 0:
1188 self.subscribers.remove_group(id)
1190 def cleaning_woman(self, now):
1191 if self.subscribers.lock():
1192 self.handle_bounced_groups(now)
1193 self.join_nonbouncing_groups(now)
1194 self.subscribers.save()
1196 class SubscriberDatabase:
1198 def __init__(self, dirname, name):
1200 self.filename = os.path.join(dirname, name)
1201 self.lockname = os.path.join(dirname, "lock")
1206 if os.system("lockfile -l 60 %s" % self.lockname) == 0:
1212 os.remove(self.lockname)
1216 if not self.loaded and not self.dict:
1217 f = open(self.filename, "r")
1218 for line in f.xreadlines():
1219 parts = line.split()
1220 self.dict[parts[0]] = {
1222 "timestamp-created": parts[2],
1223 "timestamp-bounced": parts[3],
1224 "bounce-id": parts[4],
1225 "addresses": parts[5:],
1233 f = open(self.filename + ".new", "w")
1234 for id in self.dict.keys():
1236 f.write("%s " % self.dict[id]["status"])
1237 f.write("%s " % self.dict[id]["timestamp-created"])
1238 f.write("%s " % self.dict[id]["timestamp-bounced"])
1239 f.write("%s " % self.dict[id]["bounce-id"])
1240 f.write("%s\n" % string.join(self.dict[id]["addresses"], " "))
1242 os.remove(self.filename)
1243 os.rename(self.filename + ".new", self.filename)
1246 def get(self, id, attribute):
1248 if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1249 return self.dict[id][attribute]
1252 def set(self, id, attribute, value):
1255 if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1256 self.dict[id][attribute] = value
1258 def add(self, address):
1259 return self.add_many([address])
1261 def add_many(self, addresses):
1264 for addr in addresses[:]:
1265 if addr.find("@") == -1:
1266 info("Address '%s' does not contain an @, ignoring it." % addr)
1267 addresses.remove(addr)
1268 for id in self.dict.keys():
1269 old_ones = self.dict[id]["addresses"]
1270 for addr in addresses:
1272 if x.lower() == addr.lower():
1274 self.dict[id]["addresses"] = old_ones
1275 id = self.new_group()
1278 "timestamp-created": self.timestamp(),
1279 "timestamp-bounced": "0",
1280 "bounce-id": "..notexist..",
1281 "addresses": addresses,
1285 def new_group(self):
1286 keys = self.dict.keys()
1288 keys = map(lambda x: int(x), keys)
1290 return "%d" % (keys[-1] + 1)
1294 def timestamp(self):
1295 return "%.0f" % time.time()
1300 for values in self.dict.values():
1301 list = list + values["addresses"]
1306 return self.dict.keys()
1308 def has_group(self, id):
1310 return self.dict.has_key(id)
1312 def in_group(self, id):
1314 return self.dict[id]["addresses"]
1316 def remove(self, address):
1319 for id in self.dict.keys():
1320 group = self.dict[id]
1321 for x in group["addresses"][:]:
1322 if x.lower() == address.lower():
1323 group["addresses"].remove(x)
1324 if len(group["addresses"]) == 0:
1327 def remove_group(self, id):
1335 def __init__(self, dirname, boxname):
1336 self.boxdir = os.path.join(dirname, boxname)
1337 if not os.path.isdir(self.boxdir):
1338 os.mkdir(self.boxdir, 0700)
1340 def filename(self, id):
1341 return os.path.join(self.boxdir, id)
1343 def add(self, address, message_text):
1344 id = self.make_id(message_text)
1345 filename = self.filename(id)
1346 f = open(filename + ".address", "w")
1349 f = open(filename + ".new", "w")
1350 f.write(message_text)
1352 os.rename(filename + ".new", filename)
1355 def make_id(self, message_text):
1356 return md5sum_as_hex(message_text)
1357 # XXX this might be unnecessarily long
1359 def remove(self, id):
1360 filename = self.filename(id)
1361 if os.path.isfile(filename):
1363 os.remove(filename + ".address")
1366 return os.path.isfile(self.filename(id))
1368 def get_address(self, id):
1369 f = open(self.filename(id) + ".address", "r")
1375 f = open(self.filename(id), "r")
1380 def lockname(self, id):
1381 return self.filename(id) + ".lock"
1384 if os.system("lockfile -l 600 %s" % self.lockname(id)) == 0:
1389 def unlock(self, id):
1391 os.remove(self.lockname(id))
1399 def write(self, str):
1403 log_file_handle = None
1405 global log_file_handle
1406 if log_file_handle is None:
1408 log_file_handle = open(os.path.join(DOTDIR, "logfile.txt"), "a")
1410 log_file_handle = DevNull()
1411 return log_file_handle
1414 tuple = time.localtime(time.time())
1415 return time.strftime("%Y-%m-%d %H:%M:%S", tuple) + " [%d]" % os.getpid()
1421 # No logging to stderr of debug messages. Some MTAs have a limit on how
1422 # much data they accept via stderr and debug logs will fill that quickly.
1424 log_file().write(timestamp() + " " + msg + "\n")
1427 # Log to log file first, in case MTA's stderr buffer fills up and we lose
1430 log_file().write(timestamp() + " " + msg + "\n")
1431 sys.stderr.write(msg + "\n")
1440 sys.stdout.write("""\
1441 Usage: enemies-of-carlotta [options] command
1442 Mailing list manager.
1445 --name=listname@domain
1446 --owner=address@domain
1447 --moderator=address@domain
1448 --subscription=free/moderated
1449 --posting=free/moderated/auto
1451 --ignore-bounce=yes/no
1452 --language=language code or empty
1453 --mail-on-forced-unsubscribe=yes/no
1454 --mail-on-subscription-changes=yes/no
1455 --skip-prefix=string
1456 --domain=domain.name
1457 --smtp-server=domain.name
1473 For more detailed information, please read the enemies-of-carlotta(1)
1479 def no_act_send_mail(sender, recipients, text):
1480 print "NOT SENDING MAIL FOR REAL!"
1481 print "Sender:", sender
1482 print "Recipients:", recipients
1484 print "\n".join(map(lambda s: " " + s, text.split("\n")))
1487 def set_list_options(list, owners, moderators, subscription, posting,
1488 archived, language, ignore_bounce,
1489 mail_on_sub_changes, mail_on_forced_unsub):
1491 list.cp.set("list", "owners", string.join(owners, " "))
1493 list.cp.set("list", "moderators", string.join(moderators, " "))
1494 if subscription != None:
1495 list.cp.set("list", "subscription", subscription)
1497 list.cp.set("list", "posting", posting)
1498 if archived != None:
1499 list.cp.set("list", "archived", archived)
1500 if language != None:
1501 list.cp.set("list", "language", language)
1502 if ignore_bounce != None:
1503 list.cp.set("list", "ignore-bounce", ignore_bounce)
1504 if mail_on_sub_changes != None:
1505 list.cp.set("list", "mail-on-subscription-changes",
1506 mail_on_sub_changes)
1507 if mail_on_forced_unsub != None:
1508 list.cp.set("list", "mail-on-forced-unsubscribe",
1509 mail_on_forced_unsub)
1514 opts, args = getopt.getopt(args, "h",
1523 "mail-on-forced-unsubscribe=",
1524 "mail-on-subscription-changes=",
1552 except getopt.GetoptError, detail:
1553 error("Error parsing command line options (see --help):\n%s" %
1563 ignore_bounce = None
1566 sendmail = "/usr/sbin/sendmail"
1574 mail_on_forced_unsub = None
1575 mail_on_sub_changes = None
1579 for opt, arg in opts:
1582 elif opt == "--owner":
1584 elif opt == "--moderator":
1585 moderators.append(arg)
1586 elif opt == "--subscription":
1588 elif opt == "--posting":
1590 elif opt == "--archived":
1592 elif opt == "--ignore-bounce":
1594 elif opt == "--skip-prefix":
1596 elif opt == "--domain":
1598 elif opt == "--sendmail":
1600 elif opt == "--smtp-server":
1602 elif opt == "--qmqp-server":
1604 elif opt == "--sender":
1606 elif opt == "--recipient":
1608 elif opt == "--language":
1610 elif opt == "--mail-on-forced-unsubscribe":
1611 mail_on_forced_unsub = arg
1612 elif opt == "--mail-on-subscription-changes":
1613 mail_on_sub_changes = arg
1614 elif opt == "--moderate":
1616 elif opt == "--post":
1618 elif opt == "--quiet":
1620 elif opt == "--no-act":
1625 if operation is None:
1626 error("No operation specified, see --help.")
1628 if list_name is None and operation not in ["--incoming", "--help", "-h",
1632 error("%s requires a list name specified with --name" % operation)
1634 if operation in ["--help", "-h"]:
1637 if sender or recipient:
1638 environ = os.environ.copy()
1640 environ["SENDER"] = sender
1642 environ["RECIPIENT"] = recipient
1643 set_environ(environ)
1645 mlm = MailingListManager(DOTDIR, sendmail=sendmail,
1646 smtp_server=smtp_server,
1647 qmqp_server=qmqp_server)
1649 mlm.send_mail = no_act_send_mail
1651 if operation == "--create":
1653 error("You must give at least one list owner with --owner.")
1654 list = mlm.create_list(list_name)
1655 set_list_options(list, owners, moderators, subscription, posting,
1656 archived, language, ignore_bounce,
1657 mail_on_sub_changes, mail_on_forced_unsub)
1659 debug("Created list %s." % list_name)
1660 elif operation == "--destroy":
1661 shutil.rmtree(os.path.join(DOTDIR, list_name))
1662 debug("Removed list %s." % list_name)
1663 elif operation == "--edit":
1664 list = mlm.open_list(list_name)
1665 set_list_options(list, owners, moderators, subscription, posting,
1666 archived, language, ignore_bounce,
1667 mail_on_sub_changes, mail_on_forced_unsub)
1669 elif operation == "--subscribe":
1670 list = mlm.open_list(list_name)
1671 list.subscribers.lock()
1672 for address in args:
1673 if address.find("@") == -1:
1674 error("Address '%s' does not contain an @." % address)
1675 list.subscribers.add(address)
1676 debug("Added subscriber <%s>." % address)
1677 list.subscribers.save()
1678 elif operation == "--unsubscribe":
1679 list = mlm.open_list(list_name)
1680 list.subscribers.lock()
1681 for address in args:
1682 list.subscribers.remove(address)
1683 debug("Removed subscriber <%s>." % address)
1684 list.subscribers.save()
1685 elif operation == "--list":
1686 list = mlm.open_list(list_name)
1687 for address in list.subscribers.get_all():
1689 elif operation == "--is-list":
1690 if mlm.is_list(list_name, skip_prefix, domain):
1691 debug("Indeed a mailing list: <%s>" % list_name)
1693 debug("Not a mailing list: <%s>" % list_name)
1695 elif operation == "--incoming":
1696 mlm.incoming_message(skip_prefix, domain, moderate, post)
1697 elif operation == "--cleaning-woman":
1698 mlm.cleaning_woman()
1699 elif operation == "--show-lists":
1700 listnames = mlm.get_lists()
1702 for listname in listnames:
1704 elif operation == "--get":
1705 list = mlm.open_list(list_name)
1707 print list.cp.get("list", name)
1708 elif operation == "--set":
1709 list = mlm.open_list(list_name)
1712 error("Error: --set arguments must be of form name=value")
1713 name, value = arg.split("=", 1)
1714 list.cp.set("list", name, value)
1716 elif operation == "--version":
1717 print "EoC, version %s" % VERSION
1718 print "Home page: http://liw.iki.fi/liw/eoc/"
1720 error("Internal error: unimplemented option <%s>." % operation)
1722 if __name__ == "__main__":
1725 except EocException, detail:
1726 error("Error: %s" % detail)