PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/Release_1_0b11/mailman/Mailman/MailList.py

#
Python | 1297 lines | 1159 code | 42 blank | 96 comment | 139 complexity | dede360830e5e2ec91ab6d108c03520b MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. # Copyright (C) 1998 by the Free Software Foundation, Inc.
  2. #
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; either version 2
  6. # of the License, or (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  16. """The class representing a Mailman mailing list.
  17. Mixes in many task-specific classes."""
  18. try:
  19. import mm_cfg
  20. except ImportError:
  21. raise RuntimeError, ('missing mm_cfg - has Config_dist been configured '
  22. 'for the site?')
  23. import sys, os, marshal, string, posixfile, time
  24. import re
  25. import Utils
  26. import Errors
  27. from types import StringType, IntType, DictType
  28. from ListAdmin import ListAdmin
  29. from Deliverer import Deliverer
  30. from MailCommandHandler import MailCommandHandler
  31. from HTMLFormatter import HTMLFormatter
  32. from Archiver import Archiver
  33. from Digester import Digester
  34. from SecurityManager import SecurityManager
  35. from Bouncer import Bouncer
  36. from GatewayManager import GatewayManager
  37. from Mailman.Logging.StampedLogger import StampedLogger
  38. # Note:
  39. # an _ in front of a member variable for the MailList class indicates
  40. # a variable that does not save when we marshal our state.
  41. # Use mixins here just to avoid having any one chunk be too large.
  42. class MailList(MailCommandHandler, HTMLFormatter, Deliverer, ListAdmin,
  43. Archiver, Digester, SecurityManager, Bouncer, GatewayManager):
  44. def __init__(self, name=None, lock=1):
  45. if name and name not in Utils.list_names():
  46. raise Errors.MMUnknownListError, 'list not found: %s' % name
  47. MailCommandHandler.__init__(self)
  48. self.InitTempVars(name, lock)
  49. if name:
  50. self._full_path = os.path.join(mm_cfg.LIST_DATA_DIR, name)
  51. self.Load()
  52. def __del__(self):
  53. try:
  54. for f in self._log_files.values():
  55. f.close()
  56. except AttributeError:
  57. # List may not have gotten far enough to have proper _log_files!
  58. pass
  59. def GetMembers(self):
  60. """returns a list of the members. (all lowercase)"""
  61. return self.members.keys()
  62. def GetDigestMembers(self):
  63. """returns a list of digest members. (all lowercase)"""
  64. return self.digest_members.keys()
  65. def GetDeliveryMembers(self):
  66. """returns a list of the members with username case preserved."""
  67. res = []
  68. for k, v in self.members.items():
  69. if type(v) is StringType:
  70. res.append(v)
  71. else:
  72. res.append(k)
  73. return res
  74. def GetDigestDeliveryMembers(self):
  75. """returns a list of the members with username case preserved."""
  76. res = []
  77. for k,v in self.digest_members.items():
  78. if type(v) is StringType:
  79. res.append(v)
  80. else:
  81. res.append(k)
  82. return res
  83. def __AddMember(self, addr, digest):
  84. """adds the appropriate data to the internal members dict.
  85. If the username has upercase letters in it, then the value
  86. in the members dict is the case preserved address, otherwise,
  87. the value is 0.
  88. """
  89. if Utils.LCDomain(addr) == string.lower(addr):
  90. if digest:
  91. self.digest_members[addr] = 0
  92. else:
  93. self.members[addr] = 0
  94. else:
  95. if digest:
  96. self.digest_members[string.lower(addr)] = addr
  97. else:
  98. self.members[string.lower(addr)] = addr
  99. def GetAdminEmail(self):
  100. return '%s-admin@%s' % (self._internal_name, self.host_name)
  101. def GetMemberAdminEmail(self, member):
  102. """Usually the member addr, but modified for umbrella lists.
  103. Umbrella lists have other maillists as members, and so admin stuff
  104. like confirmation requests and passwords must not be sent to the
  105. member addresses - the sublists - but rather to the administrators
  106. of the sublists. This routine picks the right address, considering
  107. regular member address to be their own administrative addresses.
  108. """
  109. if not self.umbrella_list:
  110. return member
  111. else:
  112. acct, host = tuple(string.split(member, '@'))
  113. return "%s%s@%s" % (acct, self.umbrella_member_suffix, host)
  114. def GetUserSubscribedAddress(self, member):
  115. """Return the member's case preserved address.
  116. """
  117. member = string.lower(member)
  118. cpuser = self.members.get(member)
  119. if type(cpuser) == IntType:
  120. return member
  121. elif type(cpuser) == StringType:
  122. return cpuser
  123. cpuser = self.digest_members.get(member)
  124. if type(cpuser) == IntType:
  125. return member
  126. elif type(cpuser) == StringType:
  127. return cpuser
  128. return None
  129. def GetUserCanonicalAddress(self, member):
  130. """Return the member's address lower cased."""
  131. cpuser = self.GetUserSubscribedAddress(member)
  132. if cpuser is not None:
  133. return string.lower(cpuser)
  134. return None
  135. def GetRequestEmail(self):
  136. return '%s-request@%s' % (self._internal_name, self.host_name)
  137. def GetListEmail(self):
  138. return '%s@%s' % (self._internal_name, self.host_name)
  139. def GetListIdentifier(self):
  140. """Return the unique (RFC draft-chandhok-listid-02) identifier."""
  141. return ("%s <%s.%s>" %
  142. (self.description, self._internal_name, self.host_name))
  143. def GetRelativeScriptURL(self, script_name):
  144. prefix = '../' * Utils.GetNestingLevel()
  145. return '%s%s%s/%s' % (prefix, script_name, mm_cfg.CGIEXT,
  146. self._internal_name)
  147. def GetAbsoluteScriptURL(self, script_name):
  148. if self.web_page_url:
  149. prefix = self.web_page_url
  150. else:
  151. prefix = mm_cfg.DEFAULT_URL
  152. while prefix[-1] == "/":
  153. prefix = prefix[:-1]
  154. return "%s/%s%s/%s" % (prefix, script_name, mm_cfg.CGIEXT,
  155. self._internal_name)
  156. def GetAbsoluteOptionsURL(self, addr, obscured=0):
  157. # address could come in case-preserved
  158. addr = string.lower(addr)
  159. options = self.GetAbsoluteScriptURL('options')
  160. if obscured:
  161. treated = Utils.ObscureEmail(addr, for_text=0)
  162. else:
  163. treated = addr
  164. return "%s/%s" % (options, treated)
  165. def GetUserOption(self, user, option):
  166. """Return user's setting for option, defaulting to 0 if no settings."""
  167. if option == mm_cfg.Digests:
  168. return self.digest_members.has_key(user)
  169. if not self.user_options.has_key(user):
  170. return 0
  171. return not not self.user_options[user] & option
  172. def SetUserOption(self, user, option, value):
  173. if not self.user_options.has_key(user):
  174. self.user_options[user] = 0
  175. if value:
  176. self.user_options[user] = self.user_options[user] | option
  177. else:
  178. self.user_options[user] = self.user_options[user] & ~(option)
  179. if not self.user_options[user]:
  180. del self.user_options[user]
  181. self.Save()
  182. # Here are the rules for the three dictionaries self.members,
  183. # self.digest_members, and self.passwords:
  184. #
  185. # The keys of all these dictionaries are the lowercased version of the
  186. # address. This makes finding a user very quick: just lowercase the name
  187. # you're matching against, and do a has_key() or get() on first
  188. # self.members, then if that returns false, self.digest_members
  189. #
  190. # The value of the key in self.members and self.digest_members is either
  191. # the integer 0, meaning the user was subscribed with an all-lowercase
  192. # address, or a string which would be the address with the username part
  193. # case preserved. Note that for Mailman versions before 1.0b11, the value
  194. # could also have been the integer 1. This is a bug that was caused when
  195. # a user switched from regular to/from digest membership. If this
  196. # happened, you're screwed because there's no way to recover the case
  197. # preserved address. :-(
  198. #
  199. # The keys for self.passwords is also lowercase, although for versions of
  200. # Mailman before 1.0b11, this was not always true. 1.0b11 has a hack in
  201. # Load() that forces the keys to lowercase. The value for the keys in
  202. # self.passwords is, of course the password in plain text.
  203. def FindUser(self, email):
  204. """Return the lowercased version of the subscribed email address.
  205. If email is not subscribed, either as a regular member or digest
  206. member, None is returned. If they are subscribed, the return value is
  207. guaranteed to be lowercased.
  208. """
  209. # shortcut
  210. lcuser = self.GetUserCanonicalAddress(email)
  211. if lcuser is not None:
  212. return lcuser
  213. matches = Utils.FindMatchingAddresses(email,
  214. self.members,
  215. self.digest_members)
  216. # sadly, matches may or may not be case preserved
  217. if not matches or not len(matches):
  218. return None
  219. return string.lower(matches[0])
  220. def InitTempVars(self, name, lock):
  221. """Set transient variables of this and inherited classes."""
  222. self._tmp_lock = lock
  223. self._lock_file = None
  224. self._internal_name = name
  225. self._ready = 0
  226. self._log_files = {} # 'class': log_file_obj
  227. if name:
  228. self._full_path = os.path.join(mm_cfg.LIST_DATA_DIR, name)
  229. Digester.InitTempVars(self)
  230. def InitVars(self, name=None, admin='', crypted_password=''):
  231. """Assign default values - some will be overriden by stored state."""
  232. # Non-configurable list info
  233. if name:
  234. self._internal_name = name
  235. # Must save this state, even though it isn't configurable
  236. self.volume = 1
  237. self.members = {} # self.digest_members is initted in mm_digest
  238. self.data_version = mm_cfg.VERSION
  239. self.last_post_time = 0
  240. self.post_id = 1. # A float so it never has a chance to overflow.
  241. self.user_options = {}
  242. # This stuff is configurable
  243. self.filter_prog = mm_cfg.DEFAULT_FILTER_PROG
  244. self.dont_respond_to_post_requests = 0
  245. self.num_spawns = mm_cfg.DEFAULT_NUM_SPAWNS
  246. self.advertised = mm_cfg.DEFAULT_LIST_ADVERTISED
  247. self.max_num_recipients = mm_cfg.DEFAULT_MAX_NUM_RECIPIENTS
  248. self.max_message_size = mm_cfg.DEFAULT_MAX_MESSAGE_SIZE
  249. self.web_page_url = mm_cfg.DEFAULT_URL
  250. self.owner = [admin]
  251. self.reply_goes_to_list = mm_cfg.DEFAULT_REPLY_GOES_TO_LIST
  252. self.posters = []
  253. self.forbidden_posters = []
  254. self.admin_immed_notify = mm_cfg.DEFAULT_ADMIN_IMMED_NOTIFY
  255. self.admin_notify_mchanges = \
  256. mm_cfg.DEFAULT_ADMIN_NOTIFY_MCHANGES
  257. self.moderated = mm_cfg.DEFAULT_MODERATED
  258. self.require_explicit_destination = \
  259. mm_cfg.DEFAULT_REQUIRE_EXPLICIT_DESTINATION
  260. self.acceptable_aliases = mm_cfg.DEFAULT_ACCEPTABLE_ALIASES
  261. self.umbrella_list = mm_cfg.DEFAULT_UMBRELLA_LIST
  262. self.umbrella_member_suffix = \
  263. mm_cfg.DEFAULT_UMBRELLA_MEMBER_ADMIN_SUFFIX
  264. self.send_reminders = mm_cfg.DEFAULT_SEND_REMINDERS
  265. self.send_welcome_msg = mm_cfg.DEFAULT_SEND_WELCOME_MSG
  266. self.bounce_matching_headers = \
  267. mm_cfg.DEFAULT_BOUNCE_MATCHING_HEADERS
  268. self.anonymous_list = mm_cfg.DEFAULT_ANONYMOUS_LIST
  269. self.real_name = '%s%s' % (string.upper(self._internal_name[0]),
  270. self._internal_name[1:])
  271. self.description = ''
  272. self.info = ''
  273. self.welcome_msg = ''
  274. self.goodbye_msg = ''
  275. self.subscribe_policy = mm_cfg.DEFAULT_SUBSCRIBE_POLICY
  276. self.private_roster = mm_cfg.DEFAULT_PRIVATE_ROSTER
  277. self.obscure_addresses = mm_cfg.DEFAULT_OBSCURE_ADDRESSES
  278. self.member_posting_only = mm_cfg.DEFAULT_MEMBER_POSTING_ONLY
  279. self.host_name = mm_cfg.DEFAULT_HOST_NAME
  280. self.admin_member_chunksize = mm_cfg.DEFAULT_ADMIN_MEMBER_CHUNKSIZE
  281. # Analogs to these are initted in Digester.InitVars
  282. self.nondigestable = mm_cfg.DEFAULT_NONDIGESTABLE
  283. Digester.InitVars(self) # has configurable stuff
  284. SecurityManager.InitVars(self, crypted_password)
  285. Archiver.InitVars(self) # has configurable stuff
  286. ListAdmin.InitVars(self)
  287. Bouncer.InitVars(self)
  288. GatewayManager.InitVars(self)
  289. HTMLFormatter.InitVars(self)
  290. # These need to come near the bottom because they're dependent on
  291. # other settings.
  292. self.subject_prefix = mm_cfg.DEFAULT_SUBJECT_PREFIX % self.__dict__
  293. self.msg_header = mm_cfg.DEFAULT_MSG_HEADER
  294. self.msg_footer = mm_cfg.DEFAULT_MSG_FOOTER
  295. def GetConfigInfo(self):
  296. config_info = {}
  297. config_info['digest'] = Digester.GetConfigInfo(self)
  298. config_info['archive'] = Archiver.GetConfigInfo(self)
  299. config_info['gateway'] = GatewayManager.GetConfigInfo(self)
  300. # XXX: Should this text be migrated into the templates dir?
  301. config_info['general'] = [
  302. "Fundamental list characteristics, including descriptive"
  303. " info and basic behaviors.",
  304. ('real_name', mm_cfg.String, 50, 0,
  305. 'The public name of this list (make case-changes only).',
  306. "The capitalization of this name can be changed to make it"
  307. " presentable in polite company as a proper noun, or to make an"
  308. " acronym part all upper case, etc. However, the name"
  309. " will be advertised as the email address (e.g., in subscribe"
  310. " confirmation notices), so it should <em>not</em> be otherwise"
  311. " altered. (Email addresses are not case sensitive, but"
  312. " they are sensitive to almost everything else:-)"),
  313. ('owner', mm_cfg.EmailList, (3,30), 0,
  314. "The list admin's email address - having multiple"
  315. " admins/addresses (on separate lines) is ok."),
  316. ('description', mm_cfg.String, 50, 0,
  317. 'A terse phrase identifying this list.',
  318. "This description is used when the maillist is listed with"
  319. " other maillists, or in headers, and so forth. It should"
  320. " be as succinct as you can get it, while still identifying"
  321. " what the list is."),
  322. ('info', mm_cfg.Text, (7, 50), 0,
  323. ' An introductory description - a few paragraphs - about the'
  324. ' list. It will be included, as html, at the top of the'
  325. ' listinfo page. Carriage returns will end a paragraph - see'
  326. ' the details for more info.',
  327. "The text will be treated as html <em>except</em> that newlines"
  328. " newlines will be translated to &lt;br&gt; - so you can use"
  329. " links, preformatted text, etc, but don't put in carriage"
  330. " returns except where you mean to separate paragraphs. And"
  331. " review your changes - bad html (like some unterminated HTML"
  332. " constructs) can prevent display of the entire listinfo page."),
  333. ('subject_prefix', mm_cfg.String, 10, 0,
  334. 'Prefix for subject line of list postings.',
  335. "This text will be prepended to subject lines of messages"
  336. " posted to the list, to distinguish maillist messages in"
  337. " in mailbox summaries. Brevity is premium here, it's ok"
  338. " to shorten long maillist names to something more concise,"
  339. " as long as it still identifies the maillist."),
  340. ('welcome_msg', mm_cfg.Text, (4, 50), 0,
  341. 'List-specific text prepended to new-subscriber welcome message',
  342. "This value, if any, will be added to the front of the"
  343. " new-subscriber welcome message. The rest of the"
  344. " welcome message already describes the important addresses"
  345. " and URLs for the maillist, so you don't need to include"
  346. " any of that kind of stuff here. This should just contain"
  347. " mission-specific kinds of things, like etiquette policies"
  348. " or team orientation, or that kind of thing."),
  349. ('goodbye_msg', mm_cfg.Text, (4, 50), 0,
  350. 'Text sent to people leaving the list. If empty, no special'
  351. ' text will be added to the unsubscribe message.'),
  352. ('reply_goes_to_list', mm_cfg.Radio, ('Poster', 'List'), 0,
  353. 'Are replies to a post directed to the original poster'
  354. ' or to the list? <tt>Poster</tt> is <em>strongly</em>'
  355. ' recommended.',
  356. "There are many reasons not to introduce headers like reply-to"
  357. " into other peoples messages - one is that some posters depend"
  358. " on their own reply-to setting to convey their valid email"
  359. " addr. See"
  360. ' <a href="http://www.unicom.com/pw/reply-to-harmful.html">'
  361. '"Reply-To" Munging Considered Harmful</a> for a general.'
  362. " discussion of this issue."),
  363. ('administrivia', mm_cfg.Radio, ('No', 'Yes'), 0,
  364. "(Administrivia filter) Check postings and intercept ones"
  365. " that seem to be administrative requests?",
  366. "Administrivia tests will check postings to see whether"
  367. " it's really meant as an administrative request (like"
  368. " subscribe, unsubscribe, etc), and will add it to the"
  369. " the administrative requests queue, notifying the "
  370. " administrator of the new request, in the process. "),
  371. ('umbrella_list', mm_cfg.Radio, ('No', 'Yes'), 0,
  372. 'Send password reminders to, eg, "-owner" address instead of'
  373. ' directly to user.',
  374. "Set this to yes when this list is intended to cascade only to"
  375. " other maillists. When set, meta notices like confirmations"
  376. " and password reminders will be directed to an address derived"
  377. " from the member\'s address - it will have the value of"
  378. ' \"umbrella_member_suffix\" appended to the'
  379. " member\'s account name."),
  380. ('umbrella_member_suffix', mm_cfg.String, 8, 0,
  381. 'Suffix for use when this list is an umbrella for other lists,'
  382. ' according to setting of previous "umbrella_list" setting.',
  383. 'When \"umbrella_list\" is set to indicate that this list has'
  384. " other maillists as members, then administrative notices like"
  385. " confirmations and password reminders need to not be sent"
  386. " to the member list addresses, but rather to the owner of those"
  387. " member lists. In that case, the value of this setting is"
  388. " appended to the member\'s account name for such notices."
  389. " \'-owner\' is the typical choice. This setting has no"
  390. ' effect when \"umbrella_list\" is \"No\".'),
  391. ('send_reminders', mm_cfg.Radio, ('No', 'Yes'), 0,
  392. 'Send monthly password reminders or no? Overrides the previous '
  393. 'option.'),
  394. ('send_welcome_msg', mm_cfg.Radio, ('No', 'Yes'), 0,
  395. 'Send welcome message when people subscribe?',
  396. "Turn this on only if you plan on subscribing people manually "
  397. "and don't want them to know that you did so. This option "
  398. "is most useful for transparently migrating lists from "
  399. "some other mailing list manager to Mailman."),
  400. ('admin_immed_notify', mm_cfg.Radio, ('No', 'Yes'), 0,
  401. 'Should administrator get immediate notice of new requests, '
  402. 'as well as daily notices about collected ones?',
  403. "List admins are sent daily reminders of pending admin approval"
  404. " requests, like subscriptions to a moderated list or postings"
  405. " that are being held for one reason or another. Setting this"
  406. " option causes notices to be sent immediately on the arrival"
  407. " of new requests, as well."),
  408. ('admin_notify_mchanges', mm_cfg.Radio, ('No', 'Yes'), 0,
  409. 'Should administrator get notices of subscribes/unsubscribes?'),
  410. ('dont_respond_to_post_requests', mm_cfg.Radio, ('Yes', 'No'), 0,
  411. 'Send mail to poster when their posting is held for approval?',
  412. "Approval notices are sent when mail triggers certain of the"
  413. " limits <em>except</em> routine list moderation and spam"
  414. " filters, for which notices are <em>not</em> sent. This"
  415. " option overrides ever sending the notice."),
  416. ('max_message_size', mm_cfg.Number, 3, 0,
  417. 'Maximum length in Kb of a message body. Use 0 for no limit.'),
  418. ('num_spawns', mm_cfg.Number, 3, 0,
  419. 'Number of outgoing connections to open at once '
  420. '(expert users only).',
  421. "This determines the maximum number of batches into which"
  422. " a mass posting will be divided."),
  423. ('host_name', mm_cfg.Host, 50, 0, 'Host name this list prefers.',
  424. "The host_name is the preferred name for email to mailman-related"
  425. " addresses on this host, and generally should be the mail"
  426. " host's exchanger address, if any. This setting can be useful"
  427. " for selecting among alternative names of a host that has"
  428. " multiple addresses."),
  429. ('web_page_url', mm_cfg.String, 50, 0,
  430. 'Base URL for Mailman web interface',
  431. "This is the common root for all mailman URLs concerning this"
  432. " list. It is also used in the listinfo overview of maillists"
  433. " to identify whether or not this list resides on the virtual"
  434. " host identified by the overview URL - if this value is found"
  435. " (anywhere) in the URL, then this list is considered to be"
  436. " on that virtual host, and if not, then it is excluded from"
  437. " the listing. Note that you should use the \'advertised\'"
  438. " privacy option to inhibit any listing of the host."),
  439. ]
  440. if mm_cfg.ALLOW_OPEN_SUBSCRIBE:
  441. sub_cfentry = ('subscribe_policy', mm_cfg.Radio,
  442. ('none', 'confirm', 'require approval',
  443. 'confirm+approval'), 0,
  444. "What steps are required for subscription?<br>",
  445. "None - no verification steps (<em>Not"
  446. " Recommended </em>)<br>"
  447. "confirm (*) - email confirmation step"
  448. " required <br>"
  449. "require approval - require list administrator"
  450. " approval for subscriptions <br>"
  451. "confirm+approval - both confirm and approve"
  452. "<p> (*) when someone requests a subscription,"
  453. " mailman sends them a notice with a unique"
  454. " subscription request number that they must"
  455. " reply to in order to subscribe.<br> This"
  456. " prevents mischievous (or malicious) people"
  457. " from creating subscriptions for others"
  458. " without their consent."
  459. )
  460. else:
  461. sub_cfentry = ('subscribe_policy', mm_cfg.Radio,
  462. ('confirm', 'require approval',
  463. 'confirm+approval'), 1,
  464. "What steps are required for subscription?<br>",
  465. "confirm (*) - email confirmation required <br>"
  466. "require approval - require list administrator"
  467. " approval for subscriptions <br>"
  468. "confirm+approval - both confirm and approve"
  469. "<p> (*) when someone requests a subscription,"
  470. " mailman sends them a notice with a unique"
  471. " subscription request number that they must"
  472. " reply to in order to subscribe.<br> This"
  473. " prevents mischievous (or malicious) people"
  474. " from creating subscriptions for others"
  475. " without their consent."
  476. )
  477. config_info['privacy'] = [
  478. "List access policies, including anti-spam measures,"
  479. " covering members and outsiders."
  480. ' (See also the <a href="%s/archive">Archival Options'
  481. ' section</a> for separate archive-privacy settings.)'
  482. % (self.GetRelativeScriptURL('admin')),
  483. "Subscribing",
  484. ('advertised', mm_cfg.Radio, ('No', 'Yes'), 0,
  485. 'Advertise this list when people ask what lists are on '
  486. 'this machine?'),
  487. sub_cfentry,
  488. "Membership exposure",
  489. ('private_roster', mm_cfg.Radio,
  490. ('Anyone', 'List members', 'List admin only'), 0,
  491. 'Who can view subscription list?',
  492. "When set, the list of subscribers is protected by"
  493. " member or admin password authentication."),
  494. ('obscure_addresses', mm_cfg.Radio, ('No', 'Yes'), 0,
  495. "Show member addrs so they're not directly recognizable"
  496. ' as email addrs?',
  497. "Setting this option causes member email addresses to be"
  498. " transformed when they are presented on list web pages (both"
  499. " in text and as links), so they're not trivially"
  500. " recognizable as email addresses. The intention is to"
  501. " to prevent the addresses from being snarfed up by"
  502. " automated web scanners for use by spammers."),
  503. "General posting filters",
  504. ('moderated', mm_cfg.Radio, ('No', 'Yes'), 0,
  505. 'Must posts be approved by an administrator?'),
  506. ('member_posting_only', mm_cfg.Radio, ('No', 'Yes'), 0,
  507. 'Restrict posting privilege to list members?'
  508. ' (<i>member_posting_only</i>)',
  509. "Use this option if you want to restrict posting to list members."
  510. " If you want list members to be able to"
  511. " post, plus a handful of other posters, see the <i> posters </i>"
  512. " setting below"),
  513. ('posters', mm_cfg.EmailList, (5, 30), 1,
  514. 'Addresses of members accepted for posting to this'
  515. ' list without implicit approval requirement. (See'
  516. ' "Restrict ... to list members"'
  517. ' for whether or not this is in addition to allowing posting'
  518. ' by list members',
  519. "Adding entries here will have one of two effects,"
  520. " according to whether another option restricts posting to"
  521. " members. <ul>"
  522. " <li> If <i>member_posting_only</i> is 'yes', then entries"
  523. " added here will have posting privilege in addition to"
  524. " list members."
  525. " <li> If <i>member_posting_only</i> is 'no', then <em>only</em>"
  526. " the posters listed here will be able to post without admin"
  527. " approval. </ul>"),
  528. "Spam-specific posting filters",
  529. ('require_explicit_destination', mm_cfg.Radio, ('No', 'Yes'), 0,
  530. 'Must posts have list named in destination (to, cc) field'
  531. ' (or be among the acceptable alias names, specified below)?',
  532. "Many (in fact, most) spams do not explicitly name their myriad"
  533. " destinations in the explicit destination addresses - in fact,"
  534. " often the to field has a totally bogus address for"
  535. " obfuscation. The constraint applies only to the stuff in"
  536. " the address before the '@' sign, but still catches all such"
  537. " spams."
  538. "<p>The cost is that the list will not accept unhindered any"
  539. " postings relayed from other addresses, unless <ol>"
  540. " <li>The relaying address has the same name, or"
  541. " <li>The relaying address name is included on the options that"
  542. " specifies acceptable aliases for the list. </ol>"),
  543. ('acceptable_aliases', mm_cfg.Text, ('4', '30'), 0,
  544. 'Alias names (regexps) which qualify as explicit to or cc'
  545. ' destination names for this list.',
  546. "Alternate list names (the stuff before the '@') that are to be"
  547. " accepted when the explicit-destination constraint (a prior"
  548. " option) is active. This enables things like cascading"
  549. " maillists and relays while the constraint is still"
  550. " preventing random spams."),
  551. ('max_num_recipients', mm_cfg.Number, 3, 0,
  552. 'Ceiling on acceptable number of recipients for a posting.',
  553. "If a posting has this number, or more, of recipients, it is"
  554. " held for admin approval. Use 0 for no ceiling."),
  555. ('forbidden_posters', mm_cfg.EmailList, (5, 30), 1,
  556. 'Addresses whose postings are always held for approval.',
  557. "Email addresses whose posts should always be held for"
  558. " approval, no matter what other options you have set."
  559. " See also the subsequent option which applies to arbitrary"
  560. " content of arbitrary headers."),
  561. ('bounce_matching_headers', mm_cfg.Text, ('6', '50'), 0,
  562. 'Hold posts with header value matching a specified regexp.',
  563. "Use this option to prohibit posts according to specific header"
  564. " values. The target value is a regular-expression for"
  565. " matching against the specified header. The match is done"
  566. " disregarding letter case. Lines beginning with '#' are"
  567. " ignored as comments."
  568. "<p>For example:<pre>to: .*@public.com </pre> says"
  569. " to hold all postings with a <em>to</em> mail header"
  570. " containing '@public.com' anywhere among the addresses."
  571. "<p>Note that leading whitespace is trimmed from the"
  572. " regexp. This can be circumvented in a number of ways, eg"
  573. " by escaping or bracketing it."
  574. "<p> See also the <em>forbidden_posters</em> option for"
  575. " a related mechanism."),
  576. ('anonymous_list', mm_cfg.Radio, ('No', 'Yes'), 0,
  577. 'Hide the sender of a message, replacing it with the list '
  578. 'address (Removes From, Sender and Reply-To fields)'),
  579. ]
  580. config_info['nondigest'] = [
  581. "Policies concerning immediately delivered list traffic.",
  582. ('nondigestable', mm_cfg.Toggle, ('No', 'Yes'), 1,
  583. 'Can subscribers choose to receive mail immediately,'
  584. ' rather than in batched digests?'),
  585. ('msg_header', mm_cfg.Text, (4, 55), 0,
  586. 'Header added to mail sent to regular list members',
  587. "Text prepended to the top of every immediately-delivery"
  588. " message. <p>" + Errors.MESSAGE_DECORATION_NOTE),
  589. ('msg_footer', mm_cfg.Text, (4, 55), 0,
  590. 'Footer added to mail sent to regular list members',
  591. "Text appended to the bottom of every immediately-delivery"
  592. " message. <p>" + Errors.MESSAGE_DECORATION_NOTE),
  593. ]
  594. config_info['bounce'] = Bouncer.GetConfigInfo(self)
  595. return config_info
  596. def Create(self, name, admin, crypted_password):
  597. if name in Utils.list_names():
  598. raise ValueError, 'List %s already exists.' % name
  599. else:
  600. Utils.MakeDirTree(os.path.join(mm_cfg.LIST_DATA_DIR, name))
  601. self._full_path = os.path.join(mm_cfg.LIST_DATA_DIR, name)
  602. self._internal_name = name
  603. self.Lock()
  604. self.InitVars(name, admin, crypted_password)
  605. self._ready = 1
  606. self.InitTemplates()
  607. self.Save()
  608. self.CreateFiles()
  609. def CreateFiles(self):
  610. # Touch these files so they have the right dir perms no matter what.
  611. # A "just-in-case" thing. This shouldn't have to be here.
  612. ou = os.umask(002)
  613. try:
  614. open(os.path.join(mm_cfg.LOCK_DIR, '%s.lock' %
  615. self._internal_name), 'a+').close()
  616. open(os.path.join(self._full_path, "next-digest"), "a+").close()
  617. open(os.path.join(self._full_path, "next-digest-topics"),
  618. "a+").close()
  619. finally:
  620. os.umask(ou)
  621. def Save(self):
  622. # If more than one client is manipulating the database at once, we're
  623. # pretty hosed. That's a good reason to make this a daemon not a
  624. # program.
  625. self.IsListInitialized()
  626. fname = os.path.join(self._full_path, 'config.db')
  627. fname_last = fname + ".last"
  628. file = aside_new(fname, fname_last, reopen=1)
  629. dict = {}
  630. for key, value in self.__dict__.items():
  631. if key[0] <> '_':
  632. dict[key] = value
  633. try:
  634. marshal.dump(dict, file)
  635. file.close()
  636. except IOError, status:
  637. # Darn - try to resurrect the old config.db.
  638. file = aside_new(fname_last, fname, reopen=0)
  639. self.LogMsg("error",
  640. "Failed config file write '%s',"
  641. " old config resurrected." % `status.args`)
  642. Utils.reraise()
  643. self.CheckHTMLArchiveDir()
  644. def Load(self, check_version = 1):
  645. if self._tmp_lock:
  646. self.Lock()
  647. try:
  648. file = open(os.path.join(self._full_path, 'config.db'), 'r')
  649. except IOError:
  650. raise Errors.MMBadListError, 'Failed to access config info'
  651. try:
  652. dict = marshal.load(file)
  653. if type(dict) <> DictType:
  654. raise Errors.MMBadListError, \
  655. 'Unmarshaled config info is not a dictionary'
  656. except (EOFError, ValueError, TypeError), e:
  657. raise Errors.MMBadListError, ('Failed to unmarshal config info: '
  658. + e)
  659. for key, value in dict.items():
  660. setattr(self, key, value)
  661. file.close()
  662. self._ready = 1
  663. if check_version:
  664. self.CheckValues()
  665. self.CheckVersion(dict)
  666. def LogMsg(self, kind, msg, *args):
  667. """Append a message to the log file for messages of specified kind."""
  668. # For want of a better fallback, we use sys.stderr if we can't get
  669. # a log file. We need a better way to warn of failed log access...
  670. if self._log_files.has_key(kind):
  671. logf = self._log_files[kind]
  672. else:
  673. logf = self._log_files[kind] = StampedLogger(kind)
  674. logf.write(msg % args + '\n')
  675. logf.flush()
  676. def CheckVersion(self, stored_state):
  677. """Migrate prior version's state to new structure, if changed."""
  678. if (self.data_version >= mm_cfg.DATA_FILE_VERSION and
  679. type(self.data_version) == type(mm_cfg.DATA_FILE_VERSION)):
  680. return
  681. else:
  682. self.InitVars() # Init any new variables,
  683. self.Load(check_version = 0) # then reload the file
  684. from versions import Update
  685. Update(self, stored_state)
  686. self.data_version = mm_cfg.DATA_FILE_VERSION
  687. self.Save()
  688. def CheckValues(self):
  689. """Normalize selected values to known formats."""
  690. if self.web_page_url and self.web_page_url[-1] != '/':
  691. self.web_page_url = self.web_page_url + '/'
  692. def IsListInitialized(self):
  693. if not self._ready:
  694. raise Errors.MMListNotReady
  695. def AddMember(self, name, password, digest=0, remote=None):
  696. self.IsListInitialized()
  697. # normalize the name, it could be of the form
  698. #
  699. # <person@place.com> User Name
  700. # person@place.com (User Name)
  701. # etc
  702. #
  703. name = Utils.ParseAddrs(name)
  704. # Remove spaces... it's a common thing for people to add...
  705. name = string.join(string.split(name), '')
  706. # lower case only the domain part
  707. name = Utils.LCDomain(name)
  708. # Validate the e-mail address to some degree.
  709. Utils.ValidateEmail(name)
  710. if self.IsMember(name):
  711. raise Errors.MMAlreadyAMember
  712. if name == string.lower(self.GetListEmail()):
  713. # Trying to subscribe the list to itself!
  714. raise Errors.MMBadEmailError
  715. if digest and not self.digestable:
  716. raise Errors.MMCantDigestError
  717. elif not digest and not self.nondigestable:
  718. raise Errors.MMMustDigestError
  719. if self.subscribe_policy == 0:
  720. # no confirmation or approval necessary:
  721. self.ApprovedAddMember(name, password, digest)
  722. elif self.subscribe_policy == 1 or self.subscribe_policy == 3:
  723. # confirmation:
  724. from Pending import Pending
  725. cookie = Pending().new(name, password, digest)
  726. if remote is not None:
  727. by = " " + remote
  728. remote = " from %s" % remote
  729. else:
  730. by = ""
  731. remote = ""
  732. recipient = self.GetMemberAdminEmail(name)
  733. text = Utils.maketext('verify.txt',
  734. {"email" : name,
  735. "listaddr" : self.GetListEmail(),
  736. "listname" : self.real_name,
  737. "cookie" : cookie,
  738. "hostname" : remote,
  739. "requestaddr": self.GetRequestEmail(),
  740. "remote" : remote,
  741. "listadmin" : self.GetAdminEmail(),
  742. })
  743. self.SendTextToUser(
  744. subject=("%s -- confirmation of subscription -- request %d" %
  745. (self.real_name, cookie)),
  746. recipient = recipient,
  747. sender = self.GetRequestEmail(),
  748. text = text,
  749. add_headers = ["Reply-to: %s" % self.GetRequestEmail(),
  750. "Errors-To: %s" % self.GetAdminEmail()])
  751. if recipient != name:
  752. who = "%s (%s)" % (name, string.split(recipient, '@')[0])
  753. else: who = name
  754. self.LogMsg("subscribe", "%s: pending %s %s",
  755. self._internal_name,
  756. who,
  757. by)
  758. raise Errors.MMSubscribeNeedsConfirmation
  759. else: # approval needed
  760. self.AddRequest('add_member', digest, name, password)
  761. raise Errors.MMNeedApproval, self.GetAdminEmail()
  762. def ApprovedAddMember(self, name, password, digest,
  763. ack=None, admin_notif=None):
  764. if ack is None:
  765. if self.send_welcome_msg:
  766. ack = 1
  767. else:
  768. ack = 0
  769. if admin_notif is None:
  770. if self.admin_notify_mchanges:
  771. admin_notif = 1
  772. else:
  773. admin_notif = 0
  774. # normalize the name, it could be of the form
  775. #
  776. # <person@place.com> User Name
  777. # person@place.com (User Name)
  778. # etc
  779. #
  780. name = Utils.ParseAddrs(name)
  781. Utils.ValidateEmail(name)
  782. name = Utils.LCDomain(name)
  783. if self.IsMember(name):
  784. raise Errors.MMAlreadyAMember
  785. self.__AddMember(name, digest)
  786. if digest:
  787. kind = " (D)"
  788. else:
  789. kind = ""
  790. self.SetUserOption(name, mm_cfg.DisableMime,
  791. 1 - self.mime_is_default_digest)
  792. self.LogMsg("subscribe", "%s: new%s %s",
  793. self._internal_name, kind, name)
  794. self.passwords[string.lower(name)] = password
  795. if ack:
  796. self.SendSubscribeAck(name, password, digest)
  797. if admin_notif:
  798. import Message
  799. txt = Utils.maketext("adminsubscribeack.txt",
  800. {"mmowner": mm_cfg.MAILMAN_OWNER,
  801. "admin_email": self.GetAdminEmail(),
  802. "listname": self.real_name,
  803. "member": name}, 1)
  804. msg = Message.IncomingMessage(txt)
  805. self.DeliverToOwner(msg, self.owner)
  806. def ProcessConfirmation(self, cookie):
  807. from Pending import Pending
  808. got = Pending().confirmed(cookie)
  809. if not got:
  810. raise Errors.MMBadConfirmation
  811. else:
  812. (email_addr, password, digest) = got
  813. if self.subscribe_policy == 3: # confirm + approve
  814. self.AddRequest('add_member', digest, email_addr, password)
  815. raise Errors.MMNeedApproval, self.GetAdminEmail()
  816. self.ApprovedAddMember(email_addr, password, digest)
  817. self.Save()
  818. def DeleteMember(self, name, whence=None, admin_notif=None):
  819. self.IsListInitialized()
  820. # FindMatchingAddresses *should* never return more than 1 address.
  821. # However, should log this, just to make sure.
  822. aliases = Utils.FindMatchingAddresses(name, self.members,
  823. self.digest_members)
  824. if not len(aliases):
  825. raise Errors.MMNoSuchUserError
  826. def DoActualRemoval(alias, me=self):
  827. kind = "(unfound)"
  828. try:
  829. del me.passwords[alias]
  830. except KeyError:
  831. pass
  832. if me.user_options.has_key(alias):
  833. del me.user_options[alias]
  834. try:
  835. del me.members[alias]
  836. kind = "regular"
  837. except KeyError:
  838. pass
  839. try:
  840. del me.digest_members[alias]
  841. kind = "digest"
  842. except KeyError:
  843. pass
  844. map(DoActualRemoval, aliases)
  845. if self.goodbye_msg and len(self.goodbye_msg):
  846. self.SendUnsubscribeAck(name)
  847. self.ClearBounceInfo(name)
  848. self.Save()
  849. if admin_notif is None:
  850. if self.admin_notify_mchanges:
  851. admin_notif = 1
  852. else:
  853. admin_notif = 0
  854. if admin_notif:
  855. import Message
  856. txt = Utils.maketext("adminunsubscribeack.txt",
  857. {"mmowner": mm_cfg.MAILMAN_OWNER,
  858. "admin_email": self.GetAdminEmail(),
  859. "listname": self.real_name,
  860. "member": name}, 1)
  861. msg = Message.IncomingMessage(txt)
  862. self.DeliverToOwner(msg, self.owner)
  863. if whence: whence = "; %s" % whence
  864. else: whence = ""
  865. self.LogMsg("subscribe", "%s: deleted %s%s",
  866. self._internal_name, name, whence)
  867. def IsMember(self, address):
  868. return len(Utils.FindMatchingAddresses(address, self.members,
  869. self.digest_members))
  870. def HasExplicitDest(self, msg):
  871. """True if list name or any acceptable_alias is included among the
  872. to or cc addrs."""
  873. # Note that qualified host can be different! This allows, eg, for
  874. # relaying from remote lists that have the same name. Still
  875. # stringent, but offers a way to provide for remote exploders.
  876. lowname = string.lower(self.real_name)
  877. recips = []
  878. # First check all dests against simple name:
  879. for recip in msg.getaddrlist('to') + msg.getaddrlist('cc'):
  880. curr = string.lower(string.split(recip[1], '@')[0])
  881. if lowname == curr:
  882. return 1
  883. recips.append(curr)
  884. # ... and only then try the regexp acceptable aliases.
  885. for recip in recips:
  886. for alias in string.split(self.acceptable_aliases, '\n'):
  887. stripped = string.strip(alias)
  888. try:
  889. # The list alias in `stripped` is a user supplied regexp,
  890. # which could be malformed.
  891. if stripped and re.match(stripped, recip):
  892. return 1
  893. except re.error:
  894. # `stripped' is a malformed regexp -- try matching
  895. # safely, with all non-alphanumerics backslashed:
  896. if stripped and re.match(re.escape(stripped), recip):
  897. return 1
  898. return 0
  899. def parse_matching_header_opt(self):
  900. """Return a list of triples [(field name, regex, line), ...]."""
  901. # - Blank lines and lines with '#' as first char are skipped.
  902. # - Leading whitespace in the matchexp is trimmed - you can defeat
  903. # that by, eg, containing it in gratuitous square brackets.
  904. all = []
  905. for line in string.split(self.bounce_matching_headers, '\n'):
  906. stripped = string.strip(line)
  907. if not stripped or (stripped[0] == "#"):
  908. # Skip blank lines and lines *starting* with a '#'.
  909. continue
  910. else:
  911. try:
  912. h, e = re.split(":[ \t]*", stripped, 1)
  913. try:
  914. re.compile(e)
  915. all.append((h, e, stripped))
  916. except re.error, cause:
  917. # The regexp in this line is malformed -- log it
  918. # and ignore it
  919. self.LogMsg("config", "%s - "
  920. "bad regexp %s [%s] "
  921. "in bounce_matching_header line %s"
  922. % (self.real_name, `e`,
  923. `cause`, `stripped`))
  924. except ValueError:
  925. # Whoops - some bad data got by:
  926. self.LogMsg("config", "%s - "
  927. "bad bounce_matching_header line %s"
  928. % (self.real_name, `stripped`))
  929. return all
  930. def HasMatchingHeader(self, msg):
  931. """True if named header field (case-insensitive) matches regexp.
  932. Case insensitive.
  933. Returns constraint line which matches or empty string for no
  934. matches."""
  935. pairs = self.parse_matching_header_opt()
  936. for field, matchexp, line in pairs:
  937. fragments = msg.getallmatchingheaders(field)
  938. subjs = []
  939. l = len(field)
  940. for f in fragments:
  941. # Consolidate header lines, stripping header name & whitespace.
  942. if (len(f) > l
  943. and f[l] == ":"
  944. and string.lower(field) == string.lower(f[0:l])):
  945. # Non-continuation line - trim header name:
  946. subjs.append(f[l+2:])
  947. elif not subjs:
  948. # Whoops - non-continuation that matches?
  949. subjs.append(f)
  950. else:
  951. # Continuation line.
  952. subjs[-1] = subjs[-1] + f
  953. for s in subjs:
  954. # This is safe because parse_matching_header_opt only
  955. # returns valid regexps
  956. if re.search(matchexp, s, re.I):
  957. return line
  958. return 0
  959. # msg should be an IncomingMessage object.
  960. def Post(self, msg, approved=0):
  961. self.IsListInitialized()
  962. # Be sure to ExtractApproval, whether or not flag is already set!
  963. msgapproved = self.ExtractApproval(msg)
  964. if not approved:
  965. approved = msgapproved
  966. sender = None
  967. if mm_cfg.USE_ENVELOPE_SENDER:
  968. sender = msg.GetEnvelopeSender()
  969. if not sender:
  970. sender = msg.GetSender()
  971. ## sys.stderr.write('envsend: %s, sender: %s\n' %
  972. ## (msg.GetEnvelopeSender(), msg.GetSender()))
  973. # If it's the admin, which we know by the approved variable,
  974. # we can skip a large number of checks.
  975. if not approved:
  976. beentheres = map(lambda x: string.split(x, ": ")[1][:-1],
  977. msg.getallmatchingheaders('x-beenthere'))
  978. if self.GetListEmail() in beentheres:
  979. self.AddRequest('post', Utils.SnarfMessage(msg),
  980. Errors.LOOPING_POST,
  981. msg.getheader('subject'))
  982. if len(self.forbidden_posters):
  983. forbidden_posters = Utils.List2Dict(self.forbidden_posters)
  984. addrs = Utils.FindMatchingAddresses(sender, forbidden_posters)
  985. if len(addrs):
  986. self.AddRequest('post', Utils.SnarfMessage(msg),
  987. Errors.FORBIDDEN_SENDER_MSG,
  988. msg.getheader('subject'))
  989. if self.moderated and not len(self.posters):
  990. self.AddRequest('post', Utils.SnarfMessage(msg),
  991. Errors.MODERATED_LIST_MSG,
  992. msg.getheader('subject'))
  993. elif self.moderated and len(self.posters):
  994. addrs = Utils.FindMatchingAddresses(
  995. sender, Utils.List2Dict(self.posters))
  996. if not len(addrs):
  997. self.AddRequest('post', Utils.SnarfMessage(msg),
  998. Errors.MODERATED_LIST_MSG,
  999. msg.getheader('subject'))
  1000. #
  1001. # not moderated
  1002. #
  1003. elif len(self.posters):
  1004. addrs = Utils.FindMatchingAddresses(
  1005. sender, Utils.List2Dict(self.posters))
  1006. if not len(addrs):
  1007. if self.member_posting_only:
  1008. if not self.IsMember(sender):
  1009. self.AddRequest('post', Utils.SnarfMessage(msg),
  1010. 'Only approved posters may post'
  1011. ' without moderator approval.',
  1012. msg.getheader('subject'))
  1013. else:
  1014. self.AddRequest('post', Utils.SnarfMessage(msg),
  1015. 'Only approved posters may post'
  1016. ' without moderator approval.',
  1017. msg.getheader('subject'))
  1018. elif self.member_posting_only and not self.IsMember(sender):
  1019. self.AddRequest('post', Utils.SnarfMessage(msg),
  1020. 'Postings from member addresses only.',
  1021. msg.getheader('subject'))
  1022. if self.max_num_recipients > 0:
  1023. recips = []
  1024. toheader = msg.getheader('to')
  1025. if toheader:
  1026. recips = recips + string.split(toheader, ',')
  1027. ccheader = msg.getheader('cc')
  1028. if ccheader:
  1029. recips = recips + string.split(ccheader, ',')
  1030. if len(recips) > self.max_num_recipients:
  1031. self.AddRequest('post', Utils.SnarfMessage(msg),
  1032. 'Too many recipients.',
  1033. msg.getheader('subject'))
  1034. if (self.require_explicit_destination and
  1035. not self.HasExplicitDest(msg)):
  1036. self.AddRequest('post', Utils.SnarfMessage(msg),
  1037. Errors.IMPLICIT_DEST_MSG,
  1038. msg.getheader('subject'))
  1039. if self.administrivia and Utils.IsAdministrivia(msg):
  1040. self.AddRequest('post', Utils.SnarfMessage(msg),
  1041. 'possible administrivia to list',
  1042. msg.getheader("subject"))
  1043. if self.bounce_matching_headers:
  1044. triggered = self.HasMatchingHeader(msg)
  1045. if triggered:
  1046. # Darn - can't include the matching line for the admin
  1047. # message because the info would also go to the sender.
  1048. self.AddRequest('post', Utils.SnarfMessage(msg),
  1049. Errors.SUSPICIOUS_HEADER_MSG,
  1050. msg.getheader('subject'))
  1051. if self.max_message_size > 0:
  1052. if len(msg.body)/1024. > self.max_message_size:
  1053. self.AddRequest('post', Utils.S…

Large files files are truncated, but you can click here to view the full file