PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Release_1_0b6/mailman/Mailman/MailList.py

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