def kill(userdesc, perms, vhost, forlife, promo, del_from_promo): """ Remove a user from all the lists. Args: forlife: the user's forlife email promo: the user's promo, if any (format: X2006) del_from_promo: bool, whether to delete from the promo lists as well. """ exclude = [] if promo and promo[0] == 'X' and not del_from_promo: exclude.append(PLATAL_DOMAIN + VHOST_SEP + 'promo' + promo[1:]) for list in Utils.list_names(): if list in exclude: continue try: mlist = MailList.MailList(list, lock=0) except: continue try: mlist.Lock() mlist.ApprovedDeleteMember(forlife, None, 0, 0) mlist.Save() mlist.Unlock() except: mlist.Unlock() return 1
def main(): doc = Document() doc.set_language(mm_cfg.DEFAULT_SERVER_LANGUAGE) parts = Utils.GetPathPieces() lenparts = parts and len(parts) if not parts or lenparts < 1: title = _('CGI script error') doc.SetTitle(title) doc.AddItem(Header(2, title)) doc.addError(_('Invalid options to CGI script.')) doc.AddItem('<hr>') doc.AddItem(MailmanLogo()) print doc.Format() return # get the list and user's name listname = parts[0].lower() # open list try: mlist = MailList.MailList(listname, lock=0) except Errors.MMListError, e: # Avoid cross-site scripting attacks safelistname = Utils.websafe(listname) title = _('CGI script error') doc.SetTitle(title) doc.AddItem(Header(2, title)) doc.addError(_('No such list <em>%(safelistname)s</em>')) doc.AddItem('<hr>') doc.AddItem(MailmanLogo()) # Send this with a 404 status. print 'Status: 404 Not Found' print doc.Format() syslog('error', 'No such list "%s": %s\n', listname, e) return
def get_lists(): names = Utils.list_names() names.sort() committees = OfficerPosition.objects.all() committee_lists = {} for committee in committees: if committee.mailing_list: committee_lists[committee.mailing_list] = committee mlists = [] for name in names: try: mlist = MailList.MailList(name, lock=False) except IOError: continue mlist_item = { 'name': mlist.internal_name(), 'url': mlist.GetScriptURL('listinfo', absolute=1), 'adminurl': mlist.GetScriptURL('admin', absolute=1), 'description': mlist.description, 'public': True if mlist.advertised else False, } if mlist.internal_name() in committee_lists: mlist_item['position'] = committee_lists[mlist.internal_name()] mlists.append(mlist_item) return mlists
def get_owner(name): ''' Get the email address of the person who runs this list ''' l = MailList.MailList(name.lower(), lock=0) return l.owner
def subscribe_member(user, list): ''' Adds a compsoc member to a mailing list ''' try: mailman_list = MailList.MailList(list.list) try: # ack = send notification to user about being subscribed to list # just easier not to do this especially when testing :P mailman_list.ApprovedAddMember(UserDesc( user.member.all_name(), user.email), ack=False, admin_notif=False) mailman_list.Save() except Errors.MMAlreadyAMember: raise MailmanError('User is already a member') except Errors.MembershipIsBanned, pattern: raise MailmanError("User's email is banned by pattern %s " % pattern) except Errors.MMBadEmailError: raise MailmanError("Mailman has rejected the user's email") except Errors.MMHostileAddress: raise MailmanError('User is considered hostile by mailman') finally: mailman_list.Unlock()
def list_call_dispatcher(method, userdesc, perms, vhost, *arg): """Dispatch the call to the right handler. This function checks the options of the called method the set the environment of the call. The dispatcher uses method annotation (special tokens in the documentation of the method) to guess the requested environment: @mlist: the handler requires a mlist object instead of the vhost/listname couple @lock: the handler requires the mlist to be locked (@mlist MUST be specified) @edit: the handler edit the mlist (@mlist MUST be specified) @admin: the handler requires admin rights on the list (@mlist MUST be specified) @root: the handler requires site admin rights """ try: print >> sys.stderr, "calling method: %s" % method if has_annotation(method, "root") and perms != "admin": return 0 if has_annotation(method, "mlist"): listname = str(arg[0]) arg = arg[1:] mlist = MailList.MailList(vhost + VHOST_SEP + listname.lower(), lock=0) if has_annotation(method, "admin") and not is_admin_on(userdesc, perms, mlist): return 0 if has_annotation(method, "edit") or has_annotation(method, "lock"): return list_call_locked(method, userdesc, perms, mlist, has_annotation(method, "edit"), *arg) else: return method(userdesc, perms, mlist, *arg) else: return method(userdesc, perms, vhost, *arg) except Exception, e: sys.stderr.write('Exception in dispatcher %s\n' % str(e)) raise e return 0
def gen_dot(): d = Dot() nodes = dict() login = read_ssv_file('vpopmail.login') db = MySQLdb.connect(host='localhost', user=login[0], passwd=login[2], db=login[1]) c = db.cursor() c.execute("SELECT alias, valias_line FROM valias WHERE domain=%s", (MAILDOMAIN, )) for alias, target in c.fetchall(): assert target[0] == '&' target = target[1:] alias += "@" + MAILDOMAIN if not alias in nodes: nodes[alias] = Node(alias) d.add_node(nodes[alias]) if not target in nodes: nodes[target] = Node(target) d.add_node(nodes[target]) d.add_edge(Edge(nodes[alias], nodes[target])) for list in Utils.list_names(): if list == 'plukdenacht2008': continue source = list + "@" + LISTDOMAIN if not source in nodes: nodes[source] = Node(source) d.add_node(nodes[source]) m = MailList.MailList(list, lock=False) for member in m.members: if not member in nodes: nodes[member] = Node(member) d.add_node(nodes[member]) d.add_edge(Edge(nodes[source], nodes[member])) d.write('the.dot')
def get_lists(userdesc, perms, vhost, email=None): """ List available lists for the given vhost """ if email is None: udesc = userdesc else: udesc = UserDesc(email.lower(), email.lower(), None, 0) prefix = vhost.lower()+VHOST_SEP names = Utils.list_names() names.sort() result = [] for name in names: if not name.startswith(prefix): continue try: mlist = MailList.MailList(name, lock=0) except: continue try: details = get_list_info(udesc, perms, mlist, (email is None and vhost == PLATAL_DOMAIN)) if details is not None: result.append(details[0]) except Exception, e: sys.stderr.write('Can\'t get list %s: %s\n' % (name, str(e))) continue
def setUp(self): mlist = MailList.MailList() mlist.Create('_xtest', '*****@*****.**', 'xxxxx') mlist.host_name = 'dom.ain' mlist.web_page_url = 'http://www.dom.ain/mailman/' mlist.Save() # This leaves the list in a locked state self._mlist = mlist
def main(): doc = Document() doc.set_language(mm_cfg.DEFAULT_SERVER_LANGUAGE) parts = Utils.GetPathPieces() if not parts: doc.SetTitle(_("Private Archive Error")) doc.AddItem(Header(3, _("You must specify a list."))) print doc.Format() return path = os.environ.get('PATH_INFO') tpath = true_path(path) if tpath <> path[1:]: msg = _('Private archive - "./" and "../" not allowed in URL.') doc.SetTitle(msg) doc.AddItem(Header(2, msg)) print doc.Format() syslog('mischief', 'Private archive hostile path: %s', path) return # BAW: This needs to be converted to the Site module abstraction true_filename = os.path.join( mm_cfg.PRIVATE_ARCHIVE_FILE_DIR, tpath) listname = parts[0].lower() mboxfile = '' if len(parts) > 1: mboxfile = parts[1] # See if it's the list's mbox file is being requested if listname.endswith('.mbox') and mboxfile.endswith('.mbox') and \ listname[:-5] == mboxfile[:-5]: listname = listname[:-5] else: mboxfile = '' # If it's a directory, we have to append index.html in this script. We # must also check for a gzipped file, because the text archives are # usually stored in compressed form. if os.path.isdir(true_filename): true_filename = true_filename + '/index.html' if not os.path.exists(true_filename) and \ os.path.exists(true_filename + '.gz'): true_filename = true_filename + '.gz' try: mlist = MailList.MailList(listname, lock=0) except Errors.MMListError, e: # Avoid cross-site scripting attacks safelistname = Utils.websafe(listname) msg = _('No such list <em>%(safelistname)s</em>') doc.SetTitle(_("Private Archive Error - %(msg)s")) doc.AddItem(Header(2, msg)) # Send this with a 404 status. print 'Status: 404 Not Found' print doc.Format() syslog('error', 'private: No such list "%s": %s\n', listname, e) return
def test_list_lists_private(self): lists = [] for list_name in self.list_names: list_ = MailList.MailList(list_name, False) lists.append([list_name, bool(list_.archive_private)]) resp = self.client.get('/?private=1', expect_errors=True) self.assertEqual(resp.status_code, 200) self.assertEqual(sorted(lists), sorted(resp.json))
def ensure_opened(l): if l in mlo: return True try: mlo[l] = MailList.MailList(l) return True except Errors.MMUnknownListError: logging.warn("mailman: could not open %s" % l) return False
def test_list_lists_description(self): lists = [] for list_name in self.list_names: list_ = MailList.MailList(list_name, False) lists.append([list_name, list_.description]) resp = self.client.get('/?description=1', expect_errors=True) self.assertEqual(resp.status_code, 200) self.assertEqual(sorted(lists), sorted(resp.json))
def check_list_password(name, password): ''' Test if password matches the admin password for this list. ''' l = MailList.MailList(name.lower(), lock=0) auth = l.Authenticate([mm_cfg.AuthListAdmin], password) if auth == mm_cfg.UnAuthorized: return False return True
def create_list(cls, list_name, list_admin='*****@*****.**', list_pass='******', subscribe_policy=0): if list_name in Utils.list_names(): return m = MailList.MailList() m.Create(list_name, list_admin, list_pass) m.subscribe_policy = subscribe_policy m.Save() m.Unlock()
def check_options(userdesc, perms, vhost, listname, correct=False): """ Check the list. @root """ listname = listname.lower() mlist = MailList.MailList(vhost + VHOST_SEP + listname, lock=0) if correct: return list_call_locked(check_options_runner, userdesc, perms, mlist, True, listname, True) else: return check_options_runner(userdesc, perms, mlist, listname, False)
def process_message(self, peer, mailfrom, rcpttos, data): from cStringIO import StringIO from Mailman import Utils from Mailman import Message from Mailman import MailList listnames = [] for rcpt in rcpttos: local = rcpt.lower().split('@')[0] parts = local.split('-') if len(parts) > 2: continue listname = parts[0] if len(parts) == 2: command = parts[1] else: command = '' if not Utils.list_exists(listname) or command not in ( '', 'admin', 'owner', 'request', 'join', 'leave'): continue listnames.append((rcpt, listname, command)) for rcpt, listname, command in listnames: rcpttos.remove(rcpt) print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos) if rcpttos: refused = self._deliver(mailfrom, rcpttos, data) print >> DEBUGSTREAM, 'we got refusals:', refused mlists = {} s = StringIO(data) msg = Message.Message(s) if not msg.getheader('from'): msg['From'] = mailfrom if not msg.getheader('date'): msg['Date'] = time.ctime(time.time()) for rcpt, listname, command in listnames: print >> DEBUGSTREAM, 'sending message to', rcpt mlist = mlists.get(listname) if not mlist: mlist = MailList.MailList(listname, lock=0) mlists[listname] = mlist if command == '': msg.Enqueue(mlist, tolist=1) elif command == 'admin': msg.Enqueue(mlist, toadmin=1) elif command == 'owner': msg.Enqueue(mlist, toowner=1) elif command == 'request': msg.Enqueue(mlist, torequest=1) elif command in ('join', 'leave'): if command == 'join': msg['Subject'] = 'subscribe' else: msg['Subject'] = 'unsubscribe' msg.Enqueue(mlist, torequest=1)
def __init__(self, listname): try: mailman_list_object = MailList.MailList(listname, False) except Errors.MMUnknownListError: mailman_list_object = False self.listname = listname self.hostname = mailman_list_object.host_name self.description = mailman_list_object.description self.subscribe_policy = mailman_list_object.subscribe_policy self.members = set(mailman_list_object.members) self.archive = mailman_list_object.GetBaseArchiveURL()
def test_subscribe_banned(self): path = 'subscribe/' mlist = MailList.MailList(self.list_name) mlist.ban_list.append(self.data['address']) mlist.Save() mlist.Unlock() resp = self.client.put(self.url + path + self.list_name, self.data, expect_errors=True) self.assertEqual(resp.status_code, 200) self.assertEqual(4, resp.json)
def add_owner(vhost,listname,forlife): try: mlist = MailList.MailList(vhost+'-'+listname) except: return 0 try: if forlife+'@polytechnique.org' not in mlist.owner: mlist.owner.append(forlife+'@polytechnique.org') mlist.Save() finally: mlist.Unlock() return True
def _open_list(self, listname): # We no longer cache the list instances. Because of changes to # MailList.py needed to avoid not reloading an updated list, caching # is not as effective as it once was. Also, with OldStyleMemberships # as the MemberAdaptor, there was a self-reference to the list which # kept all lists in the cache. Changing this reference to a # weakref.proxy created other issues. try: mlist = MailList.MailList(listname, lock=False) except Errors.MMListError, e: syslog('error', 'error opening list: %s\n%s', listname, e) return None
def makeMailmanListWithoutTeam(self, list_name, owner_email): # This utility is based on mailman/tests/TestBase.py. self.cleanMailmanList(None, list_name) mlist = MailList.MailList() mlist.Create(list_name, owner_email, 'password') mlist.host_name = mm_cfg.DEFAULT_URL_HOST mlist.web_page_url = 'http://%s/mailman/' % mm_cfg.DEFAULT_URL_HOST mlist.personalize = 1 mlist.include_rfc2369_headers = False mlist.use_dollar_strings = True mlist.Save() mlist.addNewMember(owner_email) return mlist
def members(listname): """Lists subscribers for the `listname` list. **Method**: GET **URI**: /v2/members/<listname> Returns an array of email addresses.""" try: mlist = MailList.MailList(listname.lower(), lock=False) except Errors.MMUnknownListError, e: return jsonify(ERRORS_CODE[e.__class__.__name__])
def setupClass(cls): lists = [ ['public', '*****@*****.**', 'Public List'], ['private', '*****@*****.**', 'Private List'], ] for l in lists: cls.create_list(l[0], list_admin=l[1]) mlist = MailList.MailList(l[0]) mlist.description = l[2] mlist.Save() mlist.Unlock()
def _open_list(self, listname): # Cache the open list so that any use of the list within this process # uses the same object. We use a WeakValueDictionary so that when the # list is no longer necessary, its memory is freed. mlist = self._listcache.get(listname) if not mlist: try: mlist = MailList.MailList(listname, lock=0) except Errors.MMListError, e: syslog('error', 'error opening list: %s\n%s', listname, e) return None else: self._listcache[listname] = mlist
def test_unsubscribe(self): path = 'subscribe/' user_desc = UserDesc.UserDesc(self.data['address'], 'fullname', 1) mlist = MailList.MailList(self.list_name) mlist.AddMember(user_desc) mlist.Save() mlist.Unlock() resp = self.client.delete(self.url + path + self.list_name, self.data, expect_errors=True) self.assertEqual(resp.status_code, 200) self.assertEqual(0, resp.json)
def main(): # Trick out pygettext since we want to mark template_data as translatable, # but we don't want to actually translate it here. def _(s): return s template_data = ( ('listinfo.html', _('General list information page')), ('subscribe.html', _('Subscribe results page')), ('options.html', _('User specific options page')), ('subscribeack.txt', _('Welcome email text file')), ('masthead.txt', _('Digest masthead')), ('postheld.txt', _('User notice of held post')), ('approve.txt', _('User notice of held subscription')), ('refuse.txt', _('Notice of post refused by moderator')), ('invite.txt', _('Invitation to join list')), ('verify.txt', _('Request to confirm subscription')), ('unsub.txt', _('Request to confirm unsubscription')), ('nomoretoday.txt', _('User notice of autoresponse limit')), ('postack.txt', _('User post acknowledgement')), ('disabled.txt', _('Subscription disabled by bounce warning')), ('admlogin.html', _('Admin/moderator login page')), ('private.html', _('Private archive login page')), ('userpass.txt', _('On demand password reminder')), ) _ = i18n._ doc = Document() # Set up the system default language i18n.set_language(mm_cfg.DEFAULT_SERVER_LANGUAGE) doc.set_language(mm_cfg.DEFAULT_SERVER_LANGUAGE) parts = Utils.GetPathPieces() if not parts: doc.AddItem(Header(2, _("List name is required."))) print doc.Format() return listname = parts[0].lower() try: mlist = MailList.MailList(listname, lock=0) except Errors.MMListError, e: # Avoid cross-site scripting attacks safelistname = Utils.websafe(listname) doc.AddItem(Header(2, _('No such list <em>%(safelistname)s</em>'))) # Send this with a 404 status. print 'Status: 404 Not Found' print doc.Format() syslog('error', 'edithtml: No such list "%s": %s', listname, e) return
def _get_maillist(listname): try: if not listname: listname = config_value('NEWSLETTER', 'NEWSLETTER_NAME') if listname == "": log.warn("NEWSLETTER_NAME not set in store settings") raise NameError('No NEWSLETTER_NAME in settings') return MailList.MailList(listname, lock=0), listname except Errors.MMUnknownListError: print >> sys.stderr, "Can't find the MailMan newsletter: %s" % listname raise NameError('No such newsletter, "%s"' % listname)
def lists_of_member(mlist, user): hostname = mlist.host_name onlists = [] for listname in Utils.list_names(): # The current list will always handle things in the mainline if listname == mlist.internal_name(): continue glist = MailList.MailList(listname, lock=0) if glist.host_name != hostname: continue if not glist.isMember(user): continue onlists.append(glist) return onlists
def test_create(self): # Lists are created in mailman after they are created in Lp. team = self.factory.makeTeam(name='team-1') # The factory cannot be used because it forces the list into a # usable state. mailing_list = getUtility(IMailingListSet).new(team, team.teamowner) self.runner._oneloop() self.assertContentEqual([mm_cfg.MAILMAN_SITE_LIST, 'team-1'], list_names()) mm_list = MailList.MailList('team-1') self.addCleanup(self.cleanMailmanList, mm_list) self.assertEqual('*****@*****.**', mm_list.getListAddress()) self.assertEqual(MailingListStatus.ACTIVE, mailing_list.status)