PageRenderTime 73ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Release_2_0_12/mailman/Mailman/MailList.py

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

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