PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/Release_1_1/mailman/Mailman/MailList.py

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