PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/Release_1_0rc2/mailman/Mailman/MailList.py

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

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