PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Release_2_0beta1/mailman/Mailman/MailList.py

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

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