PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Release_1_0/mailman/Mailman/MailList.py

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

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