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 md5.new(s).hexdigest()
85 def set_environ(new_environ):
89 def get_from_environ(key):
96 return env[key].lower()
97 raise MissingEnvironmentVariable(key)
101 """A parser for incoming e-mail addresses."""
103 def __init__(self, lists):
104 self.set_lists(lists)
105 self.set_skip_prefix(None)
106 self.set_forced_domain(None)
108 def set_lists(self, lists):
109 """Set the list of canonical list names we should know about."""
112 def set_skip_prefix(self, skip_prefix):
113 """Set the prefix to be removed from an address."""
114 self.skip_prefix = skip_prefix
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
120 def clean(self, address):
121 """Remove cruft from the address and convert the rest to lower case."""
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()
131 def split_address(self, address):
132 """Split an address to a local part and a domain."""
133 parts = address.lower().split("@", 1)
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.
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)
147 if addr_domain != list_domain:
150 if addr_local.lower() == list_local.lower():
154 if addr_local[:n] != list_local or addr_local[n] != "-":
157 return addr_local[n+1:].split("-")
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.
166 def parse(self, address):
167 address = self.clean(address)
168 for listname in self.lists:
169 parts = self.additional_address_parts(address, listname)
173 return listname, parts
174 elif parts[0] in HASH_COMMANDS:
176 raise BadCommandAddress(address)
177 return listname, parts
178 elif parts[0] in COMMANDS:
179 return listname, parts
181 raise UnknownList(address)
184 class MailingListManager:
186 def __init__(self, dotdir, sendmail="/usr/sbin/sendmail", lists=[],
187 smtp_server=None, qmqp_server=None):
189 self.sendmail = sendmail
190 self.smtp_server = smtp_server
191 self.qmqp_server = qmqp_server
194 self.secret = self.make_and_read_secret()
197 lists = filter(lambda s: "@" in s, os.listdir(dotdir))
198 self.set_lists(lists)
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 + \
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)
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")
226 f = open(secret_name, "w")
230 f = open(secret_name, "r")
235 # Load the plugins from DOTDIR/plugins/*.py.
236 def load_plugins(self):
239 dirname = os.path.join(DOTDIR, "plugins")
241 plugins = os.listdir(dirname)
246 plugins = map(os.path.splitext, plugins)
247 plugins = filter(lambda p: p[1] == ".py", plugins)
248 plugins = map(lambda p: p[0], 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))
255 if module.PLUGIN_INTERFACE_VERSION == PLUGIN_INTERFACE_VERSION:
256 self.plugins.append(module)
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,)):
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)
276 self.lists = map(lambda t: t[1], temp)
278 # Return the list of listnames.
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("="), "@")
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
290 # Compute the verification checksum for an address.
291 def compute_hash(self, address):
292 return md5sum_as_hex(address + self.secret)
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"],
300 correct = self.compute_hash(address)
301 return correct != hash
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).
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)
315 dict = { "name": listname }
318 dict["command"] = "post"
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:
327 if self.signature_is_bad(dict, hash):
328 raise BadSignature(address)
332 # Does an address refer to a mailing list?
333 def is_list(self, name, skip_prefix=None, domain=None):
335 self.parse_recipient_address(name, skip_prefix, domain)
336 except BadCommandAddress:
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)
351 # Open an existing list.
352 def open_list(self, name):
353 if self.is_list(name):
354 return self.open_list_exact(name)
357 for list in self.lists:
358 if list[:len(x)] == x:
359 return self.open_list_exact(list)
360 raise ListDoesNotExist(name)
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)
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"),
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"])
382 # Clean up bouncing address and do other janitorial work for all lists.
383 def cleaning_woman(self, send_mail=None):
385 for listname in self.lists:
386 list = self.open_list_exact(listname)
388 list.send_mail = send_mail
389 list.cleaning_woman(now)
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"))))
398 smtp = smtplib.SMTP(self.smtp_server)
399 smtp.sendmail(envelope_sender, recipients, text)
401 elif self.qmqp_server:
402 q = qmqp.QMQP(self.qmqp_server)
403 q.sendmail(envelope_sender, recipients, text)
406 recipients = string.join(recipients, " ")
407 f = os.popen("%s -oi -f '%s' %s" %
415 debug("send_mail: no recipients, not sending")
421 posting_opts = ["auto", "free", "moderated"]
423 def __init__(self, mlm, name):
427 self.cp = ConfigParser.ConfigParser()
428 self.cp.add_section("list")
429 self.cp.set("list", "owners", "")
430 self.cp.set("list", "moderators", "")
431 self.cp.set("list", "subscription", "free")
432 self.cp.set("list", "posting", "free")
433 self.cp.set("list", "archived", "no")
434 self.cp.set("list", "mail-on-subscription-changes", "no")
435 self.cp.set("list", "mail-on-forced-unsubscribe", "no")
436 self.cp.set("list", "ignore-bounce", "no")
437 self.cp.set("list", "language", "")
438 self.cp.set("list", "pristine-headers", "")
440 self.dirname = os.path.join(self.mlm.dotdir, name)
442 self.cp.read(self.mkname("config"))
444 self.subscribers = SubscriberDatabase(self.dirname, "subscribers")
445 self.moderation_box = MessageBox(self.dirname, "moderation-box")
446 self.subscription_box = MessageBox(self.dirname, "subscription-box")
447 self.bounce_box = MessageBox(self.dirname, "bounce-box")
449 def make_listdir(self):
450 if not os.path.isdir(self.dirname):
451 os.mkdir(self.dirname, 0700)
453 f = open(self.mkname("subscribers"), "w")
456 def mkname(self, relative):
457 return os.path.join(self.dirname, relative)
459 def save_config(self):
460 f = open(self.mkname("config"), "w")
464 def read_stdin(self):
465 data = sys.stdin.read()
466 # Skip Unix mbox "From " mail start indicator
467 if data[:5] == "From ":
468 data = string.split(data, "\n", 1)[1]
471 def invent_boundary(self):
472 return "%s/%s" % (md5sum_as_hex(str(time.time())),
473 md5sum_as_hex(self.name))
475 def command_address(self, command):
476 local_part, domain = self.name.split("@")
477 return "%s-%s@%s" % (local_part, command, domain)
479 def signed_address(self, command, id):
480 unsigned = self.command_address("%s-%s" % (command, id))
481 hash = self.mlm.compute_hash(unsigned)
482 return self.command_address("%s-%s-%s" % (command, id, hash))
485 return self.command_address("ignore")
487 def nice_7bit(self, str):
489 if (ord(c) < 32 and not c.isspace()) or ord(c) >= 127:
493 def mime_encode_headers(self, text):
494 headers, body = text.split("\n\n", 1)
497 for line in headers.split("\n"):
498 if line[0].isspace():
505 if self.nice_7bit(header):
506 headers.append(header)
509 name, content = header.split(": ", 1)
511 name, content = header.split(":", 1)
512 hdr = email.Header.Header(content, "utf-8")
513 headers.append(name + ": " + hdr.encode())
515 return "\n".join(headers) + "\n\n" + body
517 def template(self, template_name, dict):
518 lang = self.cp.get("list", "language")
520 template_name_lang = template_name + "." + lang
522 template_name_lang = template_name
524 if not dict.has_key("list"):
525 dict["list"] = self.name
526 dict["local"], dict["domain"] = self.name.split("@")
527 if not dict.has_key("list"):
528 dict["list"] = self.name
530 for dir in [os.path.join(self.dirname, "templates")] + TEMPLATE_DIRS:
531 pathname = os.path.join(dir, template_name_lang)
532 if not os.path.exists(pathname):
533 pathname = os.path.join(dir, template_name)
534 if os.path.exists(pathname):
535 f = open(pathname, "r")
540 raise MissingTemplate(template_name)
542 def send_template(self, envelope_sender, sender, recipients,
543 template_name, dict):
544 dict["From"] = "EoC <%s>" % sender
545 dict["To"] = string.join(recipients, ", ")
546 text = self.template(template_name, dict)
549 if self.cp.get("list", "pristine-headers") != "yes":
550 text = self.mime_encode_headers(text)
551 self.mlm.send_mail(envelope_sender, recipients, text)
553 def send_info_message(self, recipients, template_name, dict):
554 self.send_template(self.command_address("ignore"),
555 self.command_address("help"),
561 return self.cp.get("list", "owners").split()
563 def moderators(self):
564 return self.cp.get("list", "moderators").split()
566 def is_list_owner(self, address):
567 return address in self.owners()
570 self.send_info_message([get_from_environ("SENDER")], "help", {})
573 recipient = get_from_environ("SENDER")
574 if self.is_list_owner(recipient):
575 addr_list = self.subscribers.get_all()
576 addr_text = string.join(addr_list, "\n")
577 self.send_info_message([recipient], "list",
579 "addresses": addr_text,
580 "count": len(addr_list),
583 self.send_info_message([recipient], "list-sorry", {})
585 def obey_setlist(self, origmail):
586 recipient = get_from_environ("SENDER")
587 if self.is_list_owner(recipient):
588 id = self.moderation_box.add(recipient, origmail)
589 if self.parse_setlist_addresses(origmail) == None:
590 self.send_bad_addresses_in_setlist(id)
591 self.moderation_box.remove(id)
593 confirm = self.signed_address("setlistyes", id)
594 self.send_info_message(self.owners(), "setlist-confirm",
597 "origmail": origmail,
598 "boundary": self.invent_boundary(),
602 self.send_info_message([recipient], "setlist-sorry", {})
604 def obey_setlistsilently(self, origmail):
605 recipient = get_from_environ("SENDER")
606 if self.is_list_owner(recipient):
607 id = self.moderation_box.add(recipient, origmail)
608 if self.parse_setlist_addresses(origmail) == None:
609 self.send_bad_addresses_in_setlist(id)
610 self.moderation_box.remove(id)
612 confirm = self.signed_address("setlistsilentyes", id)
613 self.send_info_message(self.owners(), "setlist-confirm",
616 "origmail": origmail,
617 "boundary": self.invent_boundary(),
620 self.info_message([recipient], "setlist-sorry", {})
622 def parse_setlist_addresses(self, text):
623 body = text.split("\n\n", 1)[1]
624 lines = body.split("\n")
625 lines = filter(lambda line: line != "", lines)
626 badlines = filter(lambda line: "@" not in line, lines)
632 def send_bad_addresses_in_setlist(self, id):
633 addr = self.moderation_box.get_address(id)
634 origmail = self.moderation_box.get(id)
635 self.send_info_message([addr], "setlist-badlist",
637 "origmail": origmail,
638 "boundary": self.invent_boundary(),
642 def obey_setlistyes(self, dict):
643 if self.moderation_box.has(dict["id"]):
644 text = self.moderation_box.get(dict["id"])
645 addresses = self.parse_setlist_addresses(text)
646 if addresses == None:
647 self.send_bad_addresses_in_setlist(id)
649 removed_subscribers = []
650 self.subscribers.lock()
651 old = self.subscribers.get_all()
653 if address.lower() not in map(string.lower, addresses):
654 self.subscribers.remove(address)
655 removed_subscribers.append(address)
658 if x.lower() == address.lower():
660 self.subscribers.add_many(addresses)
661 self.subscribers.save()
663 for recipient in addresses:
664 self.send_info_message([recipient], "sub-welcome", {})
665 for recipient in removed_subscribers:
666 self.send_info_message([recipient], "unsub-goodbye", {})
667 self.send_info_message(self.owners(), "setlist-done", {})
669 self.moderation_box.remove(dict["id"])
671 def obey_setlistsilentyes(self, dict):
672 if self.moderation_box.has(dict["id"]):
673 text = self.moderation_box.get(dict["id"])
674 addresses = self.parse_setlist_addresses(text)
675 if addresses == None:
676 self.send_bad_addresses_in_setlist(id)
678 self.subscribers.lock()
679 old = self.subscribers.get_all()
681 if address not in addresses:
682 self.subscribers.remove(address)
684 addresses.remove(address)
685 self.subscribers.add_many(addresses)
686 self.subscribers.save()
687 self.send_info_message(self.owners(), "setlist-done", {})
689 self.moderation_box.remove(dict["id"])
691 def obey_owner(self, text):
692 sender = get_from_environ("SENDER")
693 recipients = self.cp.get("list", "owners").split()
694 self.mlm.send_mail(sender, recipients, text)
696 def obey_subscribe_or_unsubscribe(self, dict, template_name, command,
699 requester = get_from_environ("SENDER")
700 subscriber = dict["sender"]
702 subscriber = requester
703 if subscriber.find("@") == -1:
704 info("Trying to (un)subscribe address without @: %s" % subscriber)
706 if self.cp.get("list", "ignore-bounce") == "yes":
707 info("Will not (un)subscribe address: %s from static list" %subscriber)
709 if requester in self.owners():
710 confirmers = self.owners()
712 confirmers = [subscriber]
714 id = self.subscription_box.add(subscriber, origmail)
715 confirm = self.signed_address(command, id)
716 self.send_info_message(confirmers, template_name,
719 "origmail": origmail,
720 "boundary": self.invent_boundary(),
723 def obey_subscribe(self, dict, origmail):
724 self.obey_subscribe_or_unsubscribe(dict, "sub-confirm", "subyes",
727 def obey_unsubscribe(self, dict, origmail):
728 self.obey_subscribe_or_unsubscribe(dict, "unsub-confirm", "unsubyes",
731 def obey_subyes(self, dict):
732 if self.subscription_box.has(dict["id"]):
733 if self.cp.get("list", "subscription") == "free":
734 recipient = self.subscription_box.get_address(dict["id"])
735 self.subscribers.lock()
736 self.subscribers.add(recipient)
737 self.subscribers.save()
738 sender = self.command_address("help")
739 self.send_template(self.ignore(), sender, [recipient],
741 self.subscription_box.remove(dict["id"])
742 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
743 self.send_info_message(self.owners(),
744 "sub-owner-notification",
746 "address": recipient,
749 recipients = self.cp.get("list", "owners").split()
750 confirm = self.signed_address("subapprove", dict["id"])
751 deny = self.signed_address("subreject", dict["id"])
752 subscriber = self.subscription_box.get_address(dict["id"])
753 origmail = self.subscription_box.get(dict["id"])
754 self.send_template(self.ignore(), deny, recipients,
759 "subscriber": subscriber,
760 "origmail": origmail,
761 "boundary": self.invent_boundary(),
763 recipient = self.subscription_box.get_address(dict["id"])
764 self.send_info_message([recipient], "sub-wait", {})
766 def obey_subapprove(self, dict):
767 if self.subscription_box.has(dict["id"]):
768 recipient = self.subscription_box.get_address(dict["id"])
769 self.subscribers.lock()
770 self.subscribers.add(recipient)
771 self.subscribers.save()
772 self.send_info_message([recipient], "sub-welcome", {})
773 self.subscription_box.remove(dict["id"])
774 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
775 self.send_info_message(self.owners(), "sub-owner-notification",
777 "address": recipient,
780 def obey_subreject(self, dict):
781 if self.subscription_box.has(dict["id"]):
782 recipient = self.subscription_box.get_address(dict["id"])
783 self.send_info_message([recipient], "sub-reject", {})
784 self.subscription_box.remove(dict["id"])
786 def obey_unsubyes(self, dict):
787 if self.subscription_box.has(dict["id"]):
788 recipient = self.subscription_box.get_address(dict["id"])
789 self.subscribers.lock()
790 self.subscribers.remove(recipient)
791 self.subscribers.save()
792 self.send_info_message([recipient], "unsub-goodbye", {})
793 self.subscription_box.remove(dict["id"])
794 if self.cp.get("list", "mail-on-subscription-changes")=="yes":
795 self.send_info_message(self.owners(),
796 "unsub-owner-notification",
798 "address": recipient,
801 def store_into_archive(self, text):
802 if self.cp.get("list", "archived") == "yes":
803 archdir = os.path.join(self.dirname, "archive")
804 if not os.path.exists(archdir):
805 os.mkdir(archdir, 0700)
806 id = md5sum_as_hex(text)
807 f = open(os.path.join(archdir, id), "w")
811 def list_headers(self):
812 local, domain = self.name.split("@")
814 list.append("List-Id: <%s.%s>" % (local, domain))
815 list.append("List-Help: <mailto:%s-help@%s>" % (local, domain))
816 list.append("List-Unsubscribe: <mailto:%s-unsubscribe@%s>" %
818 list.append("List-Subscribe: <mailto:%s-subscribe@%s>" %
820 list.append("List-Post: <mailto:%s@%s>" % (local, domain))
821 list.append("List-Owner: <mailto:%s-owner@%s>" % (local, domain))
822 list.append("Precedence: bulk");
823 return string.join(list, "\n") + "\n"
825 def read_file(self, basename):
827 f = open(os.path.join(self.dirname, basename), "r")
834 def headers_to_add(self):
835 headers_to_add = self.read_file("headers-to-add").rstrip()
837 return headers_to_add + "\n"
841 def remove_some_headers(self, mail, headers_to_remove):
842 endpos = mail.find("\n\n")
844 endpos = mail.find("\n\r\n")
847 headers = mail[:endpos].split("\n")
851 add_continuation_lines = 0
852 for header in headers:
853 pos = header.find(":")
855 if add_continuation_lines:
856 remaining.append(header)
858 name = header[:pos].lower()
859 if name in headers_to_remove:
860 add_continuation_lines = 0
862 add_continuation_lines = 1
863 remaining.append(header)
865 return "\n".join(remaining) + body
867 def headers_to_remove(self, text):
868 headers_to_remove = self.read_file("headers-to-remove").split("\n")
869 headers_to_remove = map(lambda s: s.strip().lower(),
871 return self.remove_some_headers(text, headers_to_remove)
873 def append_footer(self, text):
874 if "base64" in text or "BASE64" in text:
876 for line in StringIO.StringIO(text):
877 if line.lower.startswith("content-transfer-encoding:") and \
878 "base64" in line.lower():
880 return text + self.template("footer", {})
882 def send_mail_to_subscribers(self, text):
883 text = self.headers_to_add() + self.list_headers() + \
884 self.headers_to_remove(text)
885 text = self.append_footer(text)
886 text, = self.mlm.call_plugins("send_mail_to_subscribers_hook",
888 if have_email_module and \
889 self.cp.get("list", "pristine-headers") != "yes":
890 text = self.mime_encode_headers(text)
891 self.store_into_archive(text)
892 for group in self.subscribers.groups():
893 bounce = self.signed_address("bounce", group)
894 addresses = self.subscribers.in_group(group)
895 self.mlm.send_mail(bounce, addresses, text)
897 def post_into_moderate(self, poster, dict, text):
898 id = self.moderation_box.add(poster, text)
899 recipients = self.moderators()
901 recipients = self.owners()
903 confirm = self.signed_address("approve", id)
904 deny = self.signed_address("reject", id)
905 self.send_template(self.ignore(), deny, recipients, "msg-moderate",
910 "boundary": self.invent_boundary(),
912 self.send_info_message([poster], "msg-wait", {})
914 def should_be_moderated(self, posting, poster):
915 if posting == "moderated":
917 if posting == "auto":
918 if poster.lower() not in \
919 map(string.lower, self.subscribers.get_all()):
923 def obey_post(self, dict, text):
924 if dict.has_key("force-moderation") and dict["force-moderation"]:
928 if dict.has_key("force-posting") and dict["force-posting"]:
932 posting = self.cp.get("list", "posting")
933 if posting not in self.posting_opts:
934 error("You have a weird 'posting' config. Please, review it")
935 poster = get_from_environ("SENDER")
937 self.post_into_moderate(poster, dict, text)
939 self.send_mail_to_subscribers(text)
940 elif self.should_be_moderated(posting, poster):
941 self.post_into_moderate(poster, dict, text)
943 self.send_mail_to_subscribers(text)
945 def obey_approve(self, dict):
946 if self.moderation_box.lock(dict["id"]):
947 if self.moderation_box.has(dict["id"]):
948 text = self.moderation_box.get(dict["id"])
949 self.send_mail_to_subscribers(text)
950 self.moderation_box.remove(dict["id"])
951 self.moderation_box.unlock(dict["id"])
953 def obey_reject(self, dict):
954 if self.moderation_box.lock(dict["id"]):
955 if self.moderation_box.has(dict["id"]):
956 self.moderation_box.remove(dict["id"])
957 self.moderation_box.unlock(dict["id"])
959 def split_address_list(self, addrs):
962 userpart, domain = addr.split("@")
963 if domains.has_key(domain):
964 domains[domain].append(addr)
966 domains[domain] = [addr]
968 if len(domains.keys()) == 1:
970 result.append([addr])
972 result = domains.values()
975 def obey_bounce(self, dict, text):
976 if self.subscribers.has_group(dict["id"]):
977 self.subscribers.lock()
978 addrs = self.subscribers.in_group(dict["id"])
980 if self.cp.get("list", "ignore-bounce") == "yes":
981 info("Address <%s> bounced, ignoring bounce as configured." %
983 self.subscribers.unlock()
985 debug("Address <%s> bounced, setting state to bounce." %
987 bounce_id = self.bounce_box.add(addrs[0], text[:4096])
988 self.subscribers.set(dict["id"], "status", "bounced")
989 self.subscribers.set(dict["id"], "timestamp-bounced",
991 self.subscribers.set(dict["id"], "bounce-id",
994 debug("Group %s bounced, splitting." % dict["id"])
995 for new_addrs in self.split_address_list(addrs):
996 self.subscribers.add_many(new_addrs)
997 self.subscribers.remove_group(dict["id"])
998 self.subscribers.save()
1000 debug("Ignoring bounce, group %s doesn't exist (anymore?)." %
1003 def obey_probe(self, dict, text):
1005 if self.subscribers.has_group(id):
1006 self.subscribers.lock()
1007 if self.subscribers.get(id, "status") == "probed":
1008 self.subscribers.set(id, "status", "probebounced")
1009 self.subscribers.save()
1011 def obey(self, dict):
1012 text = self.read_stdin()
1014 if dict["command"] in ["help", "list", "subscribe", "unsubscribe",
1015 "subyes", "subapprove", "subreject",
1016 "unsubyes", "post", "approve"]:
1017 sender = get_from_environ("SENDER")
1019 debug("Ignoring bounce message for %s command." %
1023 if dict["command"] == "help":
1025 elif dict["command"] == "list":
1027 elif dict["command"] == "owner":
1028 self.obey_owner(text)
1029 elif dict["command"] == "subscribe":
1030 self.obey_subscribe(dict, text)
1031 elif dict["command"] == "unsubscribe":
1032 self.obey_unsubscribe(dict, text)
1033 elif dict["command"] == "subyes":
1034 self.obey_subyes(dict)
1035 elif dict["command"] == "subapprove":
1036 self.obey_subapprove(dict)
1037 elif dict["command"] == "subreject":
1038 self.obey_subreject(dict)
1039 elif dict["command"] == "unsubyes":
1040 self.obey_unsubyes(dict)
1041 elif dict["command"] == "post":
1042 self.obey_post(dict, text)
1043 elif dict["command"] == "approve":
1044 self.obey_approve(dict)
1045 elif dict["command"] == "reject":
1046 self.obey_reject(dict)
1047 elif dict["command"] == "bounce":
1048 self.obey_bounce(dict, text)
1049 elif dict["command"] == "probe":
1050 self.obey_probe(dict, text)
1051 elif dict["command"] == "setlist":
1052 self.obey_setlist(text)
1053 elif dict["command"] == "setlistsilently":
1054 self.obey_setlistsilently(text)
1055 elif dict["command"] == "setlistyes":
1056 self.obey_setlistyes(dict)
1057 elif dict["command"] == "setlistsilentyes":
1058 self.obey_setlistsilentyes(dict)
1059 elif dict["command"] == "ignore":
1062 def get_bounce_text(self, id):
1063 bounce_id = self.subscribers.get(id, "bounce-id")
1064 if self.bounce_box.has(bounce_id):
1065 bounce_text = self.bounce_box.get(bounce_id)
1066 bounce_text = string.join(map(lambda s: "> " + s + "\n",
1067 bounce_text.split("\n")), "")
1069 bounce_text = "Bounce message not available."
1072 one_week = 7.0 * 24.0 * 60.0 * 60.0
1074 def handle_bounced_groups(self, now):
1075 for id in self.subscribers.groups():
1076 status = self.subscribers.get(id, "status")
1077 t = float(self.subscribers.get(id, "timestamp-bounced"))
1078 if status == "bounced":
1079 if now - t > self.one_week:
1080 sender = self.signed_address("probe", id)
1081 recipients = self.subscribers.in_group(id)
1082 self.send_template(sender, sender, recipients,
1084 "bounce": self.get_bounce_text(id),
1085 "boundary": self.invent_boundary(),
1087 self.subscribers.set(id, "status", "probed")
1088 elif status == "probed":
1089 if now - t > 2 * self.one_week:
1090 debug(("Cleaning woman: probe didn't bounce " +
1091 "for group <%s>, setting status to ok.") % id)
1092 self.subscribers.set(id, "status", "ok")
1093 self.bounce_box.remove(
1094 self.subscribers.get(id, "bounce-id"))
1095 elif status == "probebounced":
1096 sender = self.command_address("help")
1097 for address in self.subscribers.in_group(id):
1098 if self.cp.get("list", "mail-on-forced-unsubscribe") \
1100 self.send_template(sender, sender,
1102 "bounce-owner-notification",
1105 "bounce": self.get_bounce_text(id),
1106 "boundary": self.invent_boundary(),
1109 self.bounce_box.remove(
1110 self.subscribers.get(id, "bounce-id"))
1111 self.subscribers.remove(address)
1112 debug("Cleaning woman: removing <%s>." % address)
1113 self.send_template(sender, sender, [address],
1114 "bounce-goodbye", {})
1116 def join_nonbouncing_groups(self, now):
1118 for id in self.subscribers.groups():
1119 status = self.subscribers.get(id, "status")
1120 age1 = now - float(self.subscribers.get(id, "timestamp-bounced"))
1121 age2 = now - float(self.subscribers.get(id, "timestamp-created"))
1123 if age1 > self.one_week and age2 > self.one_week:
1124 to_be_joined.append(id)
1127 for id in to_be_joined:
1128 addrs = addrs + self.subscribers.in_group(id)
1129 self.subscribers.add_many(addrs)
1130 for id in to_be_joined:
1131 self.bounce_box.remove(self.subscribers.get(id, "bounce-id"))
1132 self.subscribers.remove_group(id)
1134 def remove_empty_groups(self):
1135 for id in self.subscribers.groups()[:]:
1136 if len(self.subscribers.in_group(id)) == 0:
1137 self.subscribers.remove_group(id)
1139 def cleaning_woman(self, now):
1140 if self.subscribers.lock():
1141 self.handle_bounced_groups(now)
1142 self.join_nonbouncing_groups(now)
1143 self.subscribers.save()
1145 class SubscriberDatabase:
1147 def __init__(self, dirname, name):
1149 self.filename = os.path.join(dirname, name)
1150 self.lockname = os.path.join(dirname, "lock")
1155 if os.system("lockfile -l 60 %s" % self.lockname) == 0:
1161 os.remove(self.lockname)
1165 if not self.loaded and not self.dict:
1166 f = open(self.filename, "r")
1167 for line in f.xreadlines():
1168 parts = line.split()
1169 self.dict[parts[0]] = {
1171 "timestamp-created": parts[2],
1172 "timestamp-bounced": parts[3],
1173 "bounce-id": parts[4],
1174 "addresses": parts[5:],
1182 f = open(self.filename + ".new", "w")
1183 for id in self.dict.keys():
1185 f.write("%s " % self.dict[id]["status"])
1186 f.write("%s " % self.dict[id]["timestamp-created"])
1187 f.write("%s " % self.dict[id]["timestamp-bounced"])
1188 f.write("%s " % self.dict[id]["bounce-id"])
1189 f.write("%s\n" % string.join(self.dict[id]["addresses"], " "))
1191 os.remove(self.filename)
1192 os.rename(self.filename + ".new", self.filename)
1195 def get(self, id, attribute):
1197 if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1198 return self.dict[id][attribute]
1201 def set(self, id, attribute, value):
1204 if self.dict.has_key(id) and self.dict[id].has_key(attribute):
1205 self.dict[id][attribute] = value
1207 def add(self, address):
1208 return self.add_many([address])
1210 def add_many(self, addresses):
1213 for addr in addresses[:]:
1214 if addr.find("@") == -1:
1215 info("Address '%s' does not contain an @, ignoring it." % addr)
1216 addresses.remove(addr)
1217 for id in self.dict.keys():
1218 old_ones = self.dict[id]["addresses"]
1219 for addr in addresses:
1221 if x.lower() == addr.lower():
1223 self.dict[id]["addresses"] = old_ones
1224 id = self.new_group()
1227 "timestamp-created": self.timestamp(),
1228 "timestamp-bounced": "0",
1229 "bounce-id": "..notexist..",
1230 "addresses": addresses,
1234 def new_group(self):
1235 keys = self.dict.keys()
1237 keys = map(lambda x: int(x), keys)
1239 return "%d" % (keys[-1] + 1)
1243 def timestamp(self):
1244 return "%.0f" % time.time()
1249 for values in self.dict.values():
1250 list = list + values["addresses"]
1255 return self.dict.keys()
1257 def has_group(self, id):
1259 return self.dict.has_key(id)
1261 def in_group(self, id):
1263 return self.dict[id]["addresses"]
1265 def remove(self, address):
1268 for id in self.dict.keys():
1269 group = self.dict[id]
1270 for x in group["addresses"][:]:
1271 if x.lower() == address.lower():
1272 group["addresses"].remove(x)
1273 if len(group["addresses"]) == 0:
1276 def remove_group(self, id):
1284 def __init__(self, dirname, boxname):
1285 self.boxdir = os.path.join(dirname, boxname)
1286 if not os.path.isdir(self.boxdir):
1287 os.mkdir(self.boxdir, 0700)
1289 def filename(self, id):
1290 return os.path.join(self.boxdir, id)
1292 def add(self, address, message_text):
1293 id = self.make_id(message_text)
1294 filename = self.filename(id)
1295 f = open(filename + ".address", "w")
1298 f = open(filename + ".new", "w")
1299 f.write(message_text)
1301 os.rename(filename + ".new", filename)
1304 def make_id(self, message_text):
1305 return md5sum_as_hex(message_text)
1306 # XXX this might be unnecessarily long
1308 def remove(self, id):
1309 filename = self.filename(id)
1310 if os.path.isfile(filename):
1312 os.remove(filename + ".address")
1315 return os.path.isfile(self.filename(id))
1317 def get_address(self, id):
1318 f = open(self.filename(id) + ".address", "r")
1324 f = open(self.filename(id), "r")
1329 def lockname(self, id):
1330 return self.filename(id) + ".lock"
1333 if os.system("lockfile -l 600 %s" % self.lockname(id)) == 0:
1338 def unlock(self, id):
1340 os.remove(self.lockname(id))
1348 def write(self, str):
1352 log_file_handle = None
1354 global log_file_handle
1355 if log_file_handle is None:
1357 log_file_handle = open(os.path.join(DOTDIR, "logfile.txt"), "a")
1359 log_file_handle = DevNull()
1360 return log_file_handle
1363 tuple = time.localtime(time.time())
1364 return time.strftime("%Y-%m-%d %H:%M:%S", tuple) + " [%d]" % os.getpid()
1370 # No logging to stderr of debug messages. Some MTAs have a limit on how
1371 # much data they accept via stderr and debug logs will fill that quickly.
1373 log_file().write(timestamp() + " " + msg + "\n")
1376 # Log to log file first, in case MTA's stderr buffer fills up and we lose
1379 log_file().write(timestamp() + " " + msg + "\n")
1380 sys.stderr.write(msg + "\n")
1389 sys.stdout.write("""\
1390 Usage: enemies-of-carlotta [options] command
1391 Mailing list manager.
1394 --name=listname@domain
1395 --owner=address@domain
1396 --moderator=address@domain
1397 --subscription=free/moderated
1398 --posting=free/moderated/auto
1400 --ignore-bounce=yes/no
1401 --language=language code or empty
1402 --mail-on-forced-unsubscribe=yes/no
1403 --mail-on-subscription-changes=yes/no
1404 --skip-prefix=string
1405 --domain=domain.name
1406 --smtp-server=domain.name
1422 For more detailed information, please read the enemies-of-carlotta(1)
1428 def no_act_send_mail(sender, recipients, text):
1429 print "NOT SENDING MAIL FOR REAL!"
1430 print "Sender:", sender
1431 print "Recipients:", recipients
1433 print "\n".join(map(lambda s: " " + s, text.split("\n")))
1436 def set_list_options(list, owners, moderators, subscription, posting,
1437 archived, language, ignore_bounce,
1438 mail_on_sub_changes, mail_on_forced_unsub):
1440 list.cp.set("list", "owners", string.join(owners, " "))
1442 list.cp.set("list", "moderators", string.join(moderators, " "))
1443 if subscription != None:
1444 list.cp.set("list", "subscription", subscription)
1446 list.cp.set("list", "posting", posting)
1447 if archived != None:
1448 list.cp.set("list", "archived", archived)
1449 if language != None:
1450 list.cp.set("list", "language", language)
1451 if ignore_bounce != None:
1452 list.cp.set("list", "ignore-bounce", ignore_bounce)
1453 if mail_on_sub_changes != None:
1454 list.cp.set("list", "mail-on-subscription-changes",
1455 mail_on_sub_changes)
1456 if mail_on_forced_unsub != None:
1457 list.cp.set("list", "mail-on-forced-unsubscribe",
1458 mail_on_forced_unsub)
1463 opts, args = getopt.getopt(args, "h",
1472 "mail-on-forced-unsubscribe=",
1473 "mail-on-subscription-changes=",
1501 except getopt.GetoptError, detail:
1502 error("Error parsing command line options (see --help):\n%s" %
1512 ignore_bounce = None
1515 sendmail = "/usr/sbin/sendmail"
1523 mail_on_forced_unsub = None
1524 mail_on_sub_changes = None
1528 for opt, arg in opts:
1531 elif opt == "--owner":
1533 elif opt == "--moderator":
1534 moderators.append(arg)
1535 elif opt == "--subscription":
1537 elif opt == "--posting":
1539 elif opt == "--archived":
1541 elif opt == "--ignore-bounce":
1543 elif opt == "--skip-prefix":
1545 elif opt == "--domain":
1547 elif opt == "--sendmail":
1549 elif opt == "--smtp-server":
1551 elif opt == "--qmqp-server":
1553 elif opt == "--sender":
1555 elif opt == "--recipient":
1557 elif opt == "--language":
1559 elif opt == "--mail-on-forced-unsubscribe":
1560 mail_on_forced_unsub = arg
1561 elif opt == "--mail-on-subscription-changes":
1562 mail_on_sub_changes = arg
1563 elif opt == "--moderate":
1565 elif opt == "--post":
1567 elif opt == "--quiet":
1569 elif opt == "--no-act":
1574 if operation is None:
1575 error("No operation specified, see --help.")
1577 if list_name is None and operation not in ["--incoming", "--help", "-h",
1581 error("%s requires a list name specified with --name" % operation)
1583 if operation in ["--help", "-h"]:
1586 if sender or recipient:
1587 environ = os.environ.copy()
1589 environ["SENDER"] = sender
1591 environ["RECIPIENT"] = recipient
1592 set_environ(environ)
1594 mlm = MailingListManager(DOTDIR, sendmail=sendmail,
1595 smtp_server=smtp_server,
1596 qmqp_server=qmqp_server)
1598 mlm.send_mail = no_act_send_mail
1600 if operation == "--create":
1602 error("You must give at least one list owner with --owner.")
1603 list = mlm.create_list(list_name)
1604 set_list_options(list, owners, moderators, subscription, posting,
1605 archived, language, ignore_bounce,
1606 mail_on_sub_changes, mail_on_forced_unsub)
1608 debug("Created list %s." % list_name)
1609 elif operation == "--destroy":
1610 shutil.rmtree(os.path.join(DOTDIR, list_name))
1611 debug("Removed list %s." % list_name)
1612 elif operation == "--edit":
1613 list = mlm.open_list(list_name)
1614 set_list_options(list, owners, moderators, subscription, posting,
1615 archived, language, ignore_bounce,
1616 mail_on_sub_changes, mail_on_forced_unsub)
1618 elif operation == "--subscribe":
1619 list = mlm.open_list(list_name)
1620 list.subscribers.lock()
1621 for address in args:
1622 if address.find("@") == -1:
1623 error("Address '%s' does not contain an @." % address)
1624 list.subscribers.add(address)
1625 debug("Added subscriber <%s>." % address)
1626 list.subscribers.save()
1627 elif operation == "--unsubscribe":
1628 list = mlm.open_list(list_name)
1629 list.subscribers.lock()
1630 for address in args:
1631 list.subscribers.remove(address)
1632 debug("Removed subscriber <%s>." % address)
1633 list.subscribers.save()
1634 elif operation == "--list":
1635 list = mlm.open_list(list_name)
1636 for address in list.subscribers.get_all():
1638 elif operation == "--is-list":
1639 if mlm.is_list(list_name, skip_prefix, domain):
1640 debug("Indeed a mailing list: <%s>" % list_name)
1642 debug("Not a mailing list: <%s>" % list_name)
1644 elif operation == "--incoming":
1645 mlm.incoming_message(skip_prefix, domain, moderate, post)
1646 elif operation == "--cleaning-woman":
1647 mlm.cleaning_woman()
1648 elif operation == "--show-lists":
1649 listnames = mlm.get_lists()
1651 for listname in listnames:
1653 elif operation == "--get":
1654 list = mlm.open_list(list_name)
1656 print list.cp.get("list", name)
1657 elif operation == "--set":
1658 list = mlm.open_list(list_name)
1661 error("Error: --set arguments must be of form name=value")
1662 name, value = arg.split("=", 1)
1663 list.cp.set("list", name, value)
1665 elif operation == "--version":
1666 print "EoC, version %s" % VERSION
1667 print "Home page: http://liw.iki.fi/liw/eoc/"
1669 error("Internal error: unimplemented option <%s>." % operation)
1671 if __name__ == "__main__":
1674 except EocException, detail:
1675 error("Error: %s" % detail)