PageRenderTime 67ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Release_2_0beta4/mailman/Mailman/MailList.py

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

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