7a71d6a7017dc9e90705ec7b0c0335d600342696
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
4 # This module is free software, and you may redistribute it and/or modify
5 # under the same terms as Python, so long as this copyright message and
6 # disclaimer are retained in their original form.
7 #
8 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
9 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
10 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
11 # POSSIBILITY OF SUCH DAMAGE.
12 #
13 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
14 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
15 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
16 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
17 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
18 #
20 """An e-mail gateway for Roundup.
22 Incoming messages are examined for multiple parts:
23 . In a multipart/mixed message or part, each subpart is extracted and
24 examined. The text/plain subparts are assembled to form the textual
25 body of the message, to be stored in the file associated with a "msg"
26 class node. Any parts of other types are each stored in separate files
27 and given "file" class nodes that are linked to the "msg" node.
28 . In a multipart/alternative message or part, we look for a text/plain
29 subpart and ignore the other parts.
30 . A message/rfc822 is treated similar tomultipart/mixed (except for
31 special handling of the first text part) if unpack_rfc822 is set in
32 the mailgw config section.
34 Summary
35 -------
36 The "summary" property on message nodes is taken from the first non-quoting
37 section in the message body. The message body is divided into sections by
38 blank lines. Sections where the second and all subsequent lines begin with
39 a ">" or "|" character are considered "quoting sections". The first line of
40 the first non-quoting section becomes the summary of the message.
42 Addresses
43 ---------
44 All of the addresses in the To: and Cc: headers of the incoming message are
45 looked up among the user nodes, and the corresponding users are placed in
46 the "recipients" property on the new "msg" node. The address in the From:
47 header similarly determines the "author" property of the new "msg"
48 node. The default handling for addresses that don't have corresponding
49 users is to create new users with no passwords and a username equal to the
50 address. (The web interface does not permit logins for users with no
51 passwords.) If we prefer to reject mail from outside sources, we can simply
52 register an auditor on the "user" class that prevents the creation of user
53 nodes with no passwords.
55 Actions
56 -------
57 The subject line of the incoming message is examined to determine whether
58 the message is an attempt to create a new item or to discuss an existing
59 item. A designator enclosed in square brackets is sought as the first thing
60 on the subject line (after skipping any "Fwd:" or "Re:" prefixes).
62 If an item designator (class name and id number) is found there, the newly
63 created "msg" node is added to the "messages" property for that item, and
64 any new "file" nodes are added to the "files" property for the item.
66 If just an item class name is found there, we attempt to create a new item
67 of that class with its "messages" property initialized to contain the new
68 "msg" node and its "files" property initialized to contain any new "file"
69 nodes.
71 Triggers
72 --------
73 Both cases may trigger detectors (in the first case we are calling the
74 set() method to add the message to the item's spool; in the second case we
75 are calling the create() method to create a new node). If an auditor raises
76 an exception, the original message is bounced back to the sender with the
77 explanatory message given in the exception.
79 $Id: mailgw.py,v 1.196 2008-07-23 03:04:44 richard Exp $
80 """
81 __docformat__ = 'restructuredtext'
83 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
84 import time, random, sys, logging
85 import traceback, rfc822
87 from email.Header import decode_header
89 from roundup import configuration, hyperdb, date, password, rfc2822, exceptions
90 from roundup.mailer import Mailer, MessageSendError
91 from roundup.i18n import _
92 from roundup.hyperdb import iter_roles
94 try:
95 import pyme, pyme.core, pyme.gpgme
96 except ImportError:
97 pyme = None
99 SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '')
101 class MailGWError(ValueError):
102 pass
104 class MailUsageError(ValueError):
105 pass
107 class MailUsageHelp(Exception):
108 """ We need to send the help message to the user. """
109 pass
111 class Unauthorized(Exception):
112 """ Access denied """
113 pass
115 class IgnoreMessage(Exception):
116 """ A general class of message that we should ignore. """
117 pass
118 class IgnoreBulk(IgnoreMessage):
119 """ This is email from a mailing list or from a vacation program. """
120 pass
121 class IgnoreLoop(IgnoreMessage):
122 """ We've seen this message before... """
123 pass
125 def initialiseSecurity(security):
126 ''' Create some Permissions and Roles on the security object
128 This function is directly invoked by security.Security.__init__()
129 as a part of the Security object instantiation.
130 '''
131 p = security.addPermission(name="Email Access",
132 description="User may use the email interface")
133 security.addPermissionToRole('Admin', p)
135 def getparam(str, param):
136 ''' From the rfc822 "header" string, extract "param" if it appears.
137 '''
138 if ';' not in str:
139 return None
140 str = str[str.index(';'):]
141 while str[:1] == ';':
142 str = str[1:]
143 if ';' in str:
144 # XXX Should parse quotes!
145 end = str.index(';')
146 else:
147 end = len(str)
148 f = str[:end]
149 if '=' in f:
150 i = f.index('=')
151 if f[:i].strip().lower() == param:
152 return rfc822.unquote(f[i+1:].strip())
153 return None
155 def gpgh_key_getall(key, attr):
156 ''' return list of given attribute for all uids in
157 a key
158 '''
159 u = key.uids
160 while u:
161 yield getattr(u, attr)
162 u = u.next
164 def gpgh_sigs(sig):
165 ''' more pythonic iteration over GPG signatures '''
166 while sig:
167 yield sig
168 sig = sig.next
170 def check_pgp_sigs(sig, gpgctx, author):
171 ''' Theoretically a PGP message can have several signatures. GPGME
172 returns status on all signatures in a linked list. Walk that
173 linked list looking for the author's signature
174 '''
175 for sig in gpgh_sigs(sig):
176 key = gpgctx.get_key(sig.fpr, False)
177 # we really only care about the signature of the user who
178 # submitted the email
179 if key and (author in gpgh_key_getall(key, 'email')):
180 if sig.summary & pyme.gpgme.GPGME_SIGSUM_VALID:
181 return True
182 else:
183 # try to narrow down the actual problem to give a more useful
184 # message in our bounce
185 if sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_MISSING:
186 raise MailUsageError, \
187 _("Message signed with unknown key: %s") % sig.fpr
188 elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_EXPIRED:
189 raise MailUsageError, \
190 _("Message signed with an expired key: %s") % sig.fpr
191 elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_REVOKED:
192 raise MailUsageError, \
193 _("Message signed with a revoked key: %s") % sig.fpr
194 else:
195 raise MailUsageError, \
196 _("Invalid PGP signature detected.")
198 # we couldn't find a key belonging to the author of the email
199 raise MailUsageError, _("Message signed with unknown key: %s") % sig.fpr
201 class Message(mimetools.Message):
202 ''' subclass mimetools.Message so we can retrieve the parts of the
203 message...
204 '''
205 def getpart(self):
206 ''' Get a single part of a multipart message and return it as a new
207 Message instance.
208 '''
209 boundary = self.getparam('boundary')
210 mid, end = '--'+boundary, '--'+boundary+'--'
211 s = cStringIO.StringIO()
212 while 1:
213 line = self.fp.readline()
214 if not line:
215 break
216 if line.strip() in (mid, end):
217 # according to rfc 1431 the preceding line ending is part of
218 # the boundary so we need to strip that
219 length = s.tell()
220 s.seek(-2, 1)
221 lineending = s.read(2)
222 if lineending == '\r\n':
223 s.truncate(length - 2)
224 elif lineending[1] in ('\r', '\n'):
225 s.truncate(length - 1)
226 else:
227 raise ValueError('Unknown line ending in message.')
228 break
229 s.write(line)
230 if not s.getvalue().strip():
231 return None
232 s.seek(0)
233 return Message(s)
235 def getparts(self):
236 """Get all parts of this multipart message."""
237 # skip over the intro to the first boundary
238 self.fp.seek(0)
239 self.getpart()
241 # accumulate the other parts
242 parts = []
243 while 1:
244 part = self.getpart()
245 if part is None:
246 break
247 parts.append(part)
248 return parts
250 def _decode_header_to_utf8(self, hdr):
251 l = []
252 prev_encoded = False
253 for part, encoding in decode_header(hdr):
254 if encoding:
255 part = part.decode(encoding)
256 # RFC 2047 specifies that between encoded parts spaces are
257 # swallowed while at the borders from encoded to non-encoded
258 # or vice-versa we must preserve a space. Multiple adjacent
259 # non-encoded parts should not occur.
260 if l and prev_encoded != bool(encoding):
261 l.append(' ')
262 prev_encoded = bool(encoding)
263 l.append(part)
264 return ''.join([s.encode('utf-8') for s in l])
266 def getheader(self, name, default=None):
267 hdr = mimetools.Message.getheader(self, name, default)
268 # TODO are there any other False values possible?
269 # TODO if not hdr: return hdr
270 if hdr is None:
271 return None
272 if not hdr:
273 return ''
274 if hdr:
275 hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders
276 return self._decode_header_to_utf8(hdr)
278 def getaddrlist(self, name):
279 # overload to decode the name part of the address
280 l = []
281 for (name, addr) in mimetools.Message.getaddrlist(self, name):
282 name = self._decode_header_to_utf8(name)
283 l.append((name, addr))
284 return l
286 def getname(self):
287 """Find an appropriate name for this message."""
288 name = None
289 if self.gettype() == 'message/rfc822':
290 # handle message/rfc822 specially - the name should be
291 # the subject of the actual e-mail embedded here
292 # we add a '.eml' extension like other email software does it
293 self.fp.seek(0)
294 s = cStringIO.StringIO(self.getbody())
295 name = Message(s).getheader('subject')
296 if name:
297 name = name + '.eml'
298 if not name:
299 # try name on Content-Type
300 name = self.getparam('name')
301 if not name:
302 disp = self.getheader('content-disposition', None)
303 if disp:
304 name = getparam(disp, 'filename')
306 if name:
307 return name.strip()
309 def getbody(self):
310 """Get the decoded message body."""
311 self.rewindbody()
312 encoding = self.getencoding()
313 data = None
314 if encoding == 'base64':
315 # BUG: is base64 really used for text encoding or
316 # are we inserting zip files here.
317 data = binascii.a2b_base64(self.fp.read())
318 elif encoding == 'quoted-printable':
319 # the quopri module wants to work with files
320 decoded = cStringIO.StringIO()
321 quopri.decode(self.fp, decoded)
322 data = decoded.getvalue()
323 elif encoding == 'uuencoded':
324 data = binascii.a2b_uu(self.fp.read())
325 else:
326 # take it as text
327 data = self.fp.read()
329 # Encode message to unicode
330 charset = rfc2822.unaliasCharset(self.getparam("charset"))
331 if charset:
332 # Do conversion only if charset specified - handle
333 # badly-specified charsets
334 edata = unicode(data, charset, 'replace').encode('utf-8')
335 # Convert from dos eol to unix
336 edata = edata.replace('\r\n', '\n')
337 else:
338 # Leave message content as is
339 edata = data
341 return edata
343 # General multipart handling:
344 # Take the first text/plain part, anything else is considered an
345 # attachment.
346 # multipart/mixed:
347 # Multiple "unrelated" parts.
348 # multipart/Alternative (rfc 1521):
349 # Like multipart/mixed, except that we'd only want one of the
350 # alternatives. Generally a top-level part from MUAs sending HTML
351 # mail - there will be a text/plain version.
352 # multipart/signed (rfc 1847):
353 # The control information is carried in the second of the two
354 # required body parts.
355 # ACTION: Default, so if content is text/plain we get it.
356 # multipart/encrypted (rfc 1847):
357 # The control information is carried in the first of the two
358 # required body parts.
359 # ACTION: Not handleable as the content is encrypted.
360 # multipart/related (rfc 1872, 2112, 2387):
361 # The Multipart/Related content-type addresses the MIME
362 # representation of compound objects, usually HTML mail with embedded
363 # images. Usually appears as an alternative.
364 # ACTION: Default, if we must.
365 # multipart/report (rfc 1892):
366 # e.g. mail system delivery status reports.
367 # ACTION: Default. Could be ignored or used for Delivery Notification
368 # flagging.
369 # multipart/form-data:
370 # For web forms only.
371 # message/rfc822:
372 # Only if configured in [mailgw] unpack_rfc822
374 def extract_content(self, parent_type=None, ignore_alternatives=False,
375 unpack_rfc822=False):
376 """Extract the body and the attachments recursively.
378 If the content is hidden inside a multipart/alternative part,
379 we use the *last* text/plain part of the *first*
380 multipart/alternative in the whole message.
381 """
382 content_type = self.gettype()
383 content = None
384 attachments = []
386 if content_type == 'text/plain':
387 content = self.getbody()
388 elif content_type[:10] == 'multipart/':
389 content_found = bool (content)
390 ig = ignore_alternatives and not content_found
391 for part in self.getparts():
392 new_content, new_attach = part.extract_content(content_type,
393 not content and ig, unpack_rfc822)
395 # If we haven't found a text/plain part yet, take this one,
396 # otherwise make it an attachment.
397 if not content:
398 content = new_content
399 cpart = part
400 elif new_content:
401 if content_found or content_type != 'multipart/alternative':
402 attachments.append(part.text_as_attachment())
403 else:
404 # if we have found a text/plain in the current
405 # multipart/alternative and find another one, we
406 # use the first as an attachment (if configured)
407 # and use the second one because rfc 2046, sec.
408 # 5.1.4. specifies that later parts are better
409 # (thanks to Philipp Gortan for pointing this
410 # out)
411 attachments.append(cpart.text_as_attachment())
412 content = new_content
413 cpart = part
415 attachments.extend(new_attach)
416 if ig and content_type == 'multipart/alternative' and content:
417 attachments = []
418 elif unpack_rfc822 and content_type == 'message/rfc822':
419 s = cStringIO.StringIO(self.getbody())
420 m = Message(s)
421 ig = ignore_alternatives and not content
422 new_content, attachments = m.extract_content(m.gettype(), ig,
423 unpack_rfc822)
424 attachments.insert(0, m.text_as_attachment())
425 elif (parent_type == 'multipart/signed' and
426 content_type == 'application/pgp-signature'):
427 # ignore it so it won't be saved as an attachment
428 pass
429 else:
430 attachments.append(self.as_attachment())
431 return content, attachments
433 def text_as_attachment(self):
434 """Return first text/plain part as Message"""
435 if not self.gettype().startswith ('multipart/'):
436 return self.as_attachment()
437 for part in self.getparts():
438 content_type = part.gettype()
439 if content_type == 'text/plain':
440 return part.as_attachment()
441 elif content_type.startswith ('multipart/'):
442 p = part.text_as_attachment()
443 if p:
444 return p
445 return None
447 def as_attachment(self):
448 """Return this message as an attachment."""
449 return (self.getname(), self.gettype(), self.getbody())
451 def pgp_signed(self):
452 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
453 '''
454 return self.gettype() == 'multipart/signed' \
455 and self.typeheader.find('protocol="application/pgp-signature"') != -1
457 def pgp_encrypted(self):
458 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
459 '''
460 return self.gettype() == 'multipart/encrypted' \
461 and self.typeheader.find('protocol="application/pgp-encrypted"') != -1
463 def decrypt(self, author):
464 ''' decrypt an OpenPGP MIME message
465 This message must be signed as well as encrypted using the "combined"
466 method. The decrypted contents are returned as a new message.
467 '''
468 (hdr, msg) = self.getparts()
469 # According to the RFC 3156 encrypted mail must have exactly two parts.
470 # The first part contains the control information. Let's verify that
471 # the message meets the RFC before we try to decrypt it.
472 if hdr.getbody() != 'Version: 1' or hdr.gettype() != 'application/pgp-encrypted':
473 raise MailUsageError, \
474 _("Unknown multipart/encrypted version.")
476 context = pyme.core.Context()
477 ciphertext = pyme.core.Data(msg.getbody())
478 plaintext = pyme.core.Data()
480 result = context.op_decrypt_verify(ciphertext, plaintext)
482 if result:
483 raise MailUsageError, _("Unable to decrypt your message.")
485 # we've decrypted it but that just means they used our public
486 # key to send it to us. now check the signatures to see if it
487 # was signed by someone we trust
488 result = context.op_verify_result()
489 check_pgp_sigs(result.signatures, context, author)
491 plaintext.seek(0,0)
492 # pyme.core.Data implements a seek method with a different signature
493 # than roundup can handle. So we'll put the data in a container that
494 # the Message class can work with.
495 c = cStringIO.StringIO()
496 c.write(plaintext.read())
497 c.seek(0)
498 return Message(c)
500 def verify_signature(self, author):
501 ''' verify the signature of an OpenPGP MIME message
502 This only handles detached signatures. Old style
503 PGP mail (i.e. '-----BEGIN PGP SIGNED MESSAGE----')
504 is archaic and not supported :)
505 '''
506 # we don't check the micalg parameter...gpgme seems to
507 # figure things out on its own
508 (msg, sig) = self.getparts()
510 if sig.gettype() != 'application/pgp-signature':
511 raise MailUsageError, \
512 _("No PGP signature found in message.")
514 context = pyme.core.Context()
515 # msg.getbody() is skipping over some headers that are
516 # required to be present for verification to succeed so
517 # we'll do this by hand
518 msg.fp.seek(0)
519 # according to rfc 3156 the data "MUST first be converted
520 # to its content-type specific canonical form. For
521 # text/plain this means conversion to an appropriate
522 # character set and conversion of line endings to the
523 # canonical <CR><LF> sequence."
524 # TODO: what about character set conversion?
525 canonical_msg = re.sub('(?<!\r)\n', '\r\n', msg.fp.read())
526 msg_data = pyme.core.Data(canonical_msg)
527 sig_data = pyme.core.Data(sig.getbody())
529 context.op_verify(sig_data, msg_data, None)
531 # check all signatures for validity
532 result = context.op_verify_result()
533 check_pgp_sigs(result.signatures, context, author)
535 class parsedMessage:
537 def __init__(self, mailgw, message):
538 self.mailgw = mailgw
539 self.config = mailgw.instance.config
540 self.db = mailgw.db
541 self.message = message
542 self.subject = message.getheader('subject', '')
543 self.has_prefix = False
544 self.matches = dict.fromkeys(['refwd', 'quote', 'classname',
545 'nodeid', 'title', 'args', 'argswhole'])
546 self.from_list = message.getaddrlist('resent-from') \
547 or message.getaddrlist('from')
548 self.pfxmode = self.config['MAILGW_SUBJECT_PREFIX_PARSING']
549 self.sfxmode = self.config['MAILGW_SUBJECT_SUFFIX_PARSING']
550 # these are filled in by subsequent parsing steps
551 self.classname = None
552 self.properties = None
553 self.cl = None
554 self.nodeid = None
555 self.author = None
556 self.recipients = None
557 self.msg_props = {}
558 self.props = None
559 self.content = None
560 self.attachments = None
562 def handle_ignore(self):
563 ''' Check to see if message can be safely ignored:
564 detect loops and
565 Precedence: Bulk, or Microsoft Outlook autoreplies
566 '''
567 if self.message.getheader('x-roundup-loop', ''):
568 raise IgnoreLoop
569 if (self.message.getheader('precedence', '') == 'bulk'
570 or self.subject.lower().find("autoreply") > 0):
571 raise IgnoreBulk
573 def handle_help(self):
574 ''' Check to see if the message contains a usage/help request
575 '''
576 if self.subject.strip().lower() == 'help':
577 raise MailUsageHelp
579 def check_subject(self):
580 ''' Check to see if the message contains a valid subject line
581 '''
582 if not self.subject:
583 raise MailUsageError, _("""
584 Emails to Roundup trackers must include a Subject: line!
585 """)
587 def parse_subject(self):
588 ''' Matches subjects like:
589 Re: "[issue1234] title of issue [status=resolved]"
591 Each part of the subject is matched, stored, then removed from the
592 start of the subject string as needed. The stored values are then
593 returned
594 '''
596 tmpsubject = self.subject
598 sd_open, sd_close = self.config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
599 delim_open = re.escape(sd_open)
600 if delim_open in '[(': delim_open = '\\' + delim_open
601 delim_close = re.escape(sd_close)
602 if delim_close in '[(': delim_close = '\\' + delim_close
604 # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
605 re_re = r"(?P<refwd>%s)\s*" % self.config["MAILGW_REFWD_RE"].pattern
606 m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
607 if m:
608 m = m.groupdict()
609 if m['refwd']:
610 self.matches.update(m)
611 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
613 # Look for Leading "
614 m = re.match(r'(?P<quote>\s*")', tmpsubject,
615 re.IGNORECASE)
616 if m:
617 self.matches.update(m.groupdict())
618 tmpsubject = tmpsubject[len(self.matches['quote']):] # Consume quote
620 # Check if the subject includes a prefix
621 self.has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
622 delim_close), tmpsubject.strip())
624 # Match the classname if specified
625 class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
626 "|".join(self.db.getclasses()), delim_close)
627 # Note: re.search, not re.match as there might be garbage
628 # (mailing list prefix, etc.) before the class identifier
629 m = re.search(class_re, tmpsubject, re.IGNORECASE)
630 if m:
631 self.matches.update(m.groupdict())
632 # Skip to the end of the class identifier, including any
633 # garbage before it.
635 tmpsubject = tmpsubject[m.end():]
637 # Match the title of the subject
638 # if we've not found a valid classname prefix then force the
639 # scanning to handle there being a leading delimiter
640 title_re = r'(?P<title>%s[^%s]*)'%(
641 not self.matches['classname'] and '.' or '', delim_open)
642 m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
643 if m:
644 self.matches.update(m.groupdict())
645 tmpsubject = tmpsubject[len(self.matches['title']):] # Consume title
647 if self.matches['title']:
648 self.matches['title'] = self.matches['title'].strip()
649 else:
650 self.matches['title'] = ''
652 # strip off the quotes that dumb emailers put around the subject, like
653 # Re: "[issue1] bla blah"
654 if self.matches['quote'] and self.matches['title'].endswith('"'):
655 self.matches['title'] = self.matches['title'][:-1]
657 # Match any arguments specified
658 args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
659 delim_close)
660 m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
661 if m:
662 self.matches.update(m.groupdict())
664 def rego_confirm(self):
665 ''' Check for registration OTK and confirm the registration if found
666 '''
668 if self.config['EMAIL_REGISTRATION_CONFIRMATION']:
669 otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
670 otk = otk_re.search(self.matches['title'] or '')
671 if otk:
672 self.db.confirm_registration(otk.group('otk'))
673 subject = 'Your registration to %s is complete' % \
674 self.config['TRACKER_NAME']
675 sendto = [self.from_list[0][1]]
676 self.mailgw.mailer.standard_message(sendto, subject, '')
677 return 1
678 return 0
680 def get_classname(self):
681 ''' Determine the classname of the node being created/edited
682 '''
683 subject = self.subject
685 # get the classname
686 if self.pfxmode == 'none':
687 classname = None
688 else:
689 classname = self.matches['classname']
691 if not classname and self.has_prefix and self.pfxmode == 'strict':
692 raise MailUsageError, _("""
693 The message you sent to roundup did not contain a properly formed subject
694 line. The subject must contain a class name or designator to indicate the
695 'topic' of the message. For example:
696 Subject: [issue] This is a new issue
697 - this will create a new issue in the tracker with the title 'This is
698 a new issue'.
699 Subject: [issue1234] This is a followup to issue 1234
700 - this will append the message's contents to the existing issue 1234
701 in the tracker.
703 Subject was: '%(subject)s'
704 """) % locals()
706 # try to get the class specified - if "loose" or "none" then fall
707 # back on the default
708 attempts = []
709 if classname:
710 attempts.append(classname)
712 if self.mailgw.default_class:
713 attempts.append(self.mailgw.default_class)
714 else:
715 attempts.append(self.config['MAILGW_DEFAULT_CLASS'])
717 # first valid class name wins
718 self.cl = None
719 for trycl in attempts:
720 try:
721 self.cl = self.db.getclass(trycl)
722 classname = self.classname = trycl
723 break
724 except KeyError:
725 pass
727 if not self.cl:
728 validname = ', '.join(self.db.getclasses())
729 if classname:
730 raise MailUsageError, _("""
731 The class name you identified in the subject line ("%(classname)s") does
732 not exist in the database.
734 Valid class names are: %(validname)s
735 Subject was: "%(subject)s"
736 """) % locals()
737 else:
738 raise MailUsageError, _("""
739 You did not identify a class name in the subject line and there is no
740 default set for this tracker. The subject must contain a class name or
741 designator to indicate the 'topic' of the message. For example:
742 Subject: [issue] This is a new issue
743 - this will create a new issue in the tracker with the title 'This is
744 a new issue'.
745 Subject: [issue1234] This is a followup to issue 1234
746 - this will append the message's contents to the existing issue 1234
747 in the tracker.
749 Subject was: '%(subject)s'
750 """) % locals()
751 # get the class properties
752 self.properties = self.cl.getprops()
755 def get_nodeid(self):
756 ''' Determine the nodeid from the message and return it if found
757 '''
758 title = self.matches['title']
759 subject = self.subject
761 if self.pfxmode == 'none':
762 nodeid = None
763 else:
764 nodeid = self.matches['nodeid']
766 # try in-reply-to to match the message if there's no nodeid
767 inreplyto = self.message.getheader('in-reply-to') or ''
768 if nodeid is None and inreplyto:
769 l = self.db.getclass('msg').stringFind(messageid=inreplyto)
770 if l:
771 nodeid = self.cl.filter(None, {'messages':l})[0]
774 # but we do need either a title or a nodeid...
775 if nodeid is None and not title:
776 raise MailUsageError, _("""
777 I cannot match your message to a node in the database - you need to either
778 supply a full designator (with number, eg "[issue123]") or keep the
779 previous subject title intact so I can match that.
781 Subject was: "%(subject)s"
782 """) % locals()
784 # If there's no nodeid, check to see if this is a followup and
785 # maybe someone's responded to the initial mail that created an
786 # entry. Try to find the matching nodes with the same title, and
787 # use the _last_ one matched (since that'll _usually_ be the most
788 # recent...). The subject_content_match config may specify an
789 # additional restriction based on the matched node's creation or
790 # activity.
791 tmatch_mode = self.config['MAILGW_SUBJECT_CONTENT_MATCH']
792 if tmatch_mode != 'never' and nodeid is None and self.matches['refwd']:
793 l = self.cl.stringFind(title=title)
794 limit = None
795 if (tmatch_mode.startswith('creation') or
796 tmatch_mode.startswith('activity')):
797 limit, interval = tmatch_mode.split(' ', 1)
798 threshold = date.Date('.') - date.Interval(interval)
799 for id in l:
800 if limit:
801 if threshold < self.cl.get(id, limit):
802 nodeid = id
803 else:
804 nodeid = id
806 # if a nodeid was specified, make sure it's valid
807 if nodeid is not None and not self.cl.hasnode(nodeid):
808 if self.pfxmode == 'strict':
809 raise MailUsageError, _("""
810 The node specified by the designator in the subject of your message
811 ("%(nodeid)s") does not exist.
813 Subject was: "%(subject)s"
814 """) % locals()
815 else:
816 nodeid = None
817 self.nodeid = nodeid
819 def get_author_id(self):
820 ''' Attempt to get the author id from the existing registered users,
821 otherwise attempt to register a new user and return their id
822 '''
823 # Don't create users if anonymous isn't allowed to register
824 create = 1
825 anonid = self.db.user.lookup('anonymous')
826 if not (self.db.security.hasPermission('Register', anonid, 'user')
827 and self.db.security.hasPermission('Email Access', anonid)):
828 create = 0
830 # ok, now figure out who the author is - create a new user if the
831 # "create" flag is true
832 author = uidFromAddress(self.db, self.from_list[0], create=create)
834 # if we're not recognised, and we don't get added as a user, then we
835 # must be anonymous
836 if not author:
837 author = anonid
839 # make sure the author has permission to use the email interface
840 if not self.db.security.hasPermission('Email Access', author):
841 if author == anonid:
842 # we're anonymous and we need to be a registered user
843 from_address = self.from_list[0][1]
844 registration_info = ""
845 if self.db.security.hasPermission('Web Access', author) and \
846 self.db.security.hasPermission('Register', anonid, 'user'):
847 tracker_web = self.config.TRACKER_WEB
848 registration_info = """ Please register at:
850 %(tracker_web)suser?template=register
852 ...before sending mail to the tracker.""" % locals()
854 raise Unauthorized, _("""
855 You are not a registered user.%(registration_info)s
857 Unknown address: %(from_address)s
858 """) % locals()
859 else:
860 # we're registered and we're _still_ not allowed access
861 raise Unauthorized, _(
862 'You are not permitted to access this tracker.')
863 self.author = author
865 def check_node_permissions(self):
866 ''' Check if the author has permission to edit or create this
867 class of node
868 '''
869 if self.nodeid:
870 if not self.db.security.hasPermission('Edit', self.author,
871 self.classname, itemid=self.nodeid):
872 raise Unauthorized, _(
873 'You are not permitted to edit %(classname)s.'
874 ) % self.__dict__
875 else:
876 if not self.db.security.hasPermission('Create', self.author,
877 self.classname):
878 raise Unauthorized, _(
879 'You are not permitted to create %(classname)s.'
880 ) % self.__dict__
882 def commit_and_reopen_as_author(self):
883 ''' the author may have been created - make sure the change is
884 committed before we reopen the database
885 then re-open the database as the author
886 '''
887 self.db.commit()
889 # set the database user as the author
890 username = self.db.user.get(self.author, 'username')
891 self.db.setCurrentUser(username)
893 # re-get the class with the new database connection
894 self.cl = self.db.getclass(self.classname)
896 def get_recipients(self):
897 ''' Get the list of recipients who were included in message and
898 register them as users if possible
899 '''
900 # Don't create users if anonymous isn't allowed to register
901 create = 1
902 anonid = self.db.user.lookup('anonymous')
903 if not (self.db.security.hasPermission('Register', anonid, 'user')
904 and self.db.security.hasPermission('Email Access', anonid)):
905 create = 0
907 # get the user class arguments from the commandline
908 user_props = self.mailgw.get_class_arguments('user')
910 # now update the recipients list
911 recipients = []
912 tracker_email = self.config['TRACKER_EMAIL'].lower()
913 msg_to = self.message.getaddrlist('to')
914 msg_cc = self.message.getaddrlist('cc')
915 for recipient in msg_to + msg_cc:
916 r = recipient[1].strip().lower()
917 if r == tracker_email or not r:
918 continue
920 # look up the recipient - create if necessary (and we're
921 # allowed to)
922 recipient = uidFromAddress(self.db, recipient, create, **user_props)
924 # if all's well, add the recipient to the list
925 if recipient:
926 recipients.append(recipient)
927 self.recipients = recipients
929 def get_props(self):
930 ''' Generate all the props for the new/updated node and return them
931 '''
932 subject = self.subject
934 # get the commandline arguments for issues
935 issue_props = self.mailgw.get_class_arguments('issue', self.classname)
937 #
938 # handle the subject argument list
939 #
940 # figure what the properties of this Class are
941 props = {}
942 args = self.matches['args']
943 argswhole = self.matches['argswhole']
944 title = self.matches['title']
946 # Reform the title
947 if self.matches['nodeid'] and self.nodeid is None:
948 title = subject
950 if args:
951 if self.sfxmode == 'none':
952 title += ' ' + argswhole
953 else:
954 errors, props = setPropArrayFromString(self, self.cl, args,
955 self.nodeid)
956 # handle any errors parsing the argument list
957 if errors:
958 if self.sfxmode == 'strict':
959 errors = '\n- '.join(map(str, errors))
960 raise MailUsageError, _("""
961 There were problems handling your subject line argument list:
962 - %(errors)s
964 Subject was: "%(subject)s"
965 """) % locals()
966 else:
967 title += ' ' + argswhole
970 # set the issue title to the subject
971 title = title.strip()
972 if (title and self.properties.has_key('title') and not
973 issue_props.has_key('title')):
974 issue_props['title'] = title
975 if (self.nodeid and self.properties.has_key('title') and not
976 self.config['MAILGW_SUBJECT_UPDATES_TITLE']):
977 issue_props['title'] = self.cl.get(self.nodeid,'title')
979 # merge the command line props defined in issue_props into
980 # the props dictionary because function(**props, **issue_props)
981 # is a syntax error.
982 for prop in issue_props.keys() :
983 if not props.has_key(prop) :
984 props[prop] = issue_props[prop]
986 self.props = props
988 def get_pgp_message(self):
989 ''' If they've enabled PGP processing then verify the signature
990 or decrypt the message
991 '''
992 def pgp_role():
993 """ if PGP_ROLES is specified the user must have a Role in the list
994 or we will skip PGP processing
995 """
996 if self.config.PGP_ROLES:
997 return self.db.user.has_role(self.author,
998 iter_roles(self.config.PGP_ROLES))
999 else:
1000 return True
1002 if self.config.PGP_ENABLE and pgp_role():
1003 assert pyme, 'pyme is not installed'
1004 # signed/encrypted mail must come from the primary address
1005 author_address = self.db.user.get(self.author, 'address')
1006 if self.config.PGP_HOMEDIR:
1007 os.environ['GNUPGHOME'] = self.config.PGP_HOMEDIR
1008 if self.message.pgp_signed():
1009 self.message.verify_signature(author_address)
1010 elif self.message.pgp_encrypted():
1011 # replace message with the contents of the decrypted
1012 # message for content extraction
1013 # TODO: encrypted message handling is far from perfect
1014 # bounces probably include the decrypted message, for
1015 # instance :(
1016 self.message = self.message.decrypt(author_address)
1017 else:
1018 raise MailUsageError, _("""
1019 This tracker has been configured to require all email be PGP signed or
1020 encrypted.""")
1022 def get_content_and_attachments(self):
1023 ''' get the attachments and first text part from the message
1024 '''
1025 ig = self.config.MAILGW_IGNORE_ALTERNATIVES
1026 self.content, self.attachments = self.message.extract_content(
1027 ignore_alternatives=ig,
1028 unpack_rfc822=self.config.MAILGW_UNPACK_RFC822)
1031 def create_files(self):
1032 ''' Create a file for each attachment in the message
1033 '''
1034 if not self.properties.has_key('files'):
1035 return
1036 files = []
1037 file_props = self.mailgw.get_class_arguments('file')
1039 if self.attachments:
1040 for (name, mime_type, data) in self.attachments:
1041 if not self.db.security.hasPermission('Create', self.author,
1042 'file'):
1043 raise Unauthorized, _(
1044 'You are not permitted to create files.')
1045 if not name:
1046 name = "unnamed"
1047 try:
1048 fileid = self.db.file.create(type=mime_type, name=name,
1049 content=data, **file_props)
1050 except exceptions.Reject:
1051 pass
1052 else:
1053 files.append(fileid)
1054 # allowed to attach the files to an existing node?
1055 if self.nodeid and not self.db.security.hasPermission('Edit',
1056 self.author, self.classname, 'files'):
1057 raise Unauthorized, _(
1058 'You are not permitted to add files to %(classname)s.'
1059 ) % self.__dict__
1061 self.msg_props['files'] = files
1062 if self.nodeid:
1063 # extend the existing files list
1064 fileprop = self.cl.get(self.nodeid, 'files')
1065 fileprop.extend(files)
1066 files = fileprop
1068 self.props['files'] = files
1070 def create_msg(self):
1071 ''' Create msg containing all the relevant information from the message
1072 '''
1073 if not self.properties.has_key('messages'):
1074 return
1075 msg_props = self.mailgw.get_class_arguments('msg')
1076 self.msg_props.update (msg_props)
1078 # Get the message ids
1079 inreplyto = self.message.getheader('in-reply-to') or ''
1080 messageid = self.message.getheader('message-id')
1081 # generate a messageid if there isn't one
1082 if not messageid:
1083 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1084 self.classname, self.nodeid, self.config['MAIL_DOMAIN'])
1086 if self.content is None:
1087 raise MailUsageError, _("""
1088 Roundup requires the submission to be plain text. The message parser could
1089 not find a text/plain part to use.
1090 """)
1092 # parse the body of the message, stripping out bits as appropriate
1093 summary, content = parseContent(self.content, config=self.config)
1094 content = content.strip()
1096 if content:
1097 if not self.db.security.hasPermission('Create', self.author, 'msg'):
1098 raise Unauthorized, _(
1099 'You are not permitted to create messages.')
1101 try:
1102 message_id = self.db.msg.create(author=self.author,
1103 recipients=self.recipients, date=date.Date('.'),
1104 summary=summary, content=content,
1105 messageid=messageid, inreplyto=inreplyto, **self.msg_props)
1106 except exceptions.Reject, error:
1107 raise MailUsageError, _("""
1108 Mail message was rejected by a detector.
1109 %(error)s
1110 """) % locals()
1111 # allowed to attach the message to the existing node?
1112 if self.nodeid and not self.db.security.hasPermission('Edit',
1113 self.author, self.classname, 'messages'):
1114 raise Unauthorized, _(
1115 'You are not permitted to add messages to %(classname)s.'
1116 ) % self.__dict__
1118 if self.nodeid:
1119 # add the message to the node's list
1120 messages = self.cl.get(self.nodeid, 'messages')
1121 messages.append(message_id)
1122 self.props['messages'] = messages
1123 else:
1124 # pre-load the messages list
1125 self.props['messages'] = [message_id]
1127 def create_node(self):
1128 ''' Create/update a node using self.props
1129 '''
1130 classname = self.classname
1131 try:
1132 if self.nodeid:
1133 # Check permissions for each property
1134 for prop in self.props.keys():
1135 if not self.db.security.hasPermission('Edit', self.author,
1136 classname, prop):
1137 raise Unauthorized, _('You are not permitted to edit '
1138 'property %(prop)s of class %(classname)s.'
1139 ) % locals()
1140 self.cl.set(self.nodeid, **self.props)
1141 else:
1142 # Check permissions for each property
1143 for prop in self.props.keys():
1144 if not self.db.security.hasPermission('Create', self.author,
1145 classname, prop):
1146 raise Unauthorized, _('You are not permitted to set '
1147 'property %(prop)s of class %(classname)s.'
1148 ) % locals()
1149 self.nodeid = self.cl.create(**self.props)
1150 except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1151 raise MailUsageError, _("""
1152 There was a problem with the message you sent:
1153 %(message)s
1154 """) % locals()
1156 return self.nodeid
1160 class MailGW:
1162 # To override the message parsing, derive your own class from
1163 # parsedMessage and assign to parsed_message_class in a derived
1164 # class of MailGW
1165 parsed_message_class = parsedMessage
1167 def __init__(self, instance, arguments=()):
1168 self.instance = instance
1169 self.arguments = arguments
1170 self.default_class = None
1171 for option, value in self.arguments:
1172 if option == '-c':
1173 self.default_class = value.strip()
1175 self.mailer = Mailer(instance.config)
1176 self.logger = logging.getLogger('roundup.mailgw')
1178 # should we trap exceptions (normal usage) or pass them through
1179 # (for testing)
1180 self.trapExceptions = 1
1182 def do_pipe(self):
1183 """ Read a message from standard input and pass it to the mail handler.
1185 Read into an internal structure that we can seek on (in case
1186 there's an error).
1188 XXX: we may want to read this into a temporary file instead...
1189 """
1190 s = cStringIO.StringIO()
1191 s.write(sys.stdin.read())
1192 s.seek(0)
1193 self.main(s)
1194 return 0
1196 def do_mailbox(self, filename):
1197 """ Read a series of messages from the specified unix mailbox file and
1198 pass each to the mail handler.
1199 """
1200 # open the spool file and lock it
1201 import fcntl
1202 # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
1203 if hasattr(fcntl, 'LOCK_EX'):
1204 FCNTL = fcntl
1205 else:
1206 import FCNTL
1207 f = open(filename, 'r+')
1208 fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
1210 # handle and clear the mailbox
1211 try:
1212 from mailbox import UnixMailbox
1213 mailbox = UnixMailbox(f, factory=Message)
1214 # grab one message
1215 message = mailbox.next()
1216 while message:
1217 # handle this message
1218 self.handle_Message(message)
1219 message = mailbox.next()
1220 # nuke the file contents
1221 os.ftruncate(f.fileno(), 0)
1222 except:
1223 import traceback
1224 traceback.print_exc()
1225 return 1
1226 fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
1227 return 0
1229 def do_imap(self, server, user='', password='', mailbox='', ssl=0,
1230 cram=0):
1231 ''' Do an IMAP connection
1232 '''
1233 import getpass, imaplib, socket
1234 try:
1235 if not user:
1236 user = raw_input('User: ')
1237 if not password:
1238 password = getpass.getpass()
1239 except (KeyboardInterrupt, EOFError):
1240 # Ctrl C or D maybe also Ctrl Z under Windows.
1241 print "\nAborted by user."
1242 return 1
1243 # open a connection to the server and retrieve all messages
1244 try:
1245 if ssl:
1246 self.logger.debug('Trying server %r with ssl'%server)
1247 server = imaplib.IMAP4_SSL(server)
1248 else:
1249 self.logger.debug('Trying server %r without ssl'%server)
1250 server = imaplib.IMAP4(server)
1251 except (imaplib.IMAP4.error, socket.error, socket.sslerror):
1252 self.logger.exception('IMAP server error')
1253 return 1
1255 try:
1256 if cram:
1257 server.login_cram_md5(user, password)
1258 else:
1259 server.login(user, password)
1260 except imaplib.IMAP4.error, e:
1261 self.logger.exception('IMAP login failure')
1262 return 1
1264 try:
1265 if not mailbox:
1266 (typ, data) = server.select()
1267 else:
1268 (typ, data) = server.select(mailbox=mailbox)
1269 if typ != 'OK':
1270 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
1271 data))
1272 return 1
1273 try:
1274 numMessages = int(data[0])
1275 except ValueError, value:
1276 self.logger.error('Invalid message count from mailbox %r'%
1277 data[0])
1278 return 1
1279 for i in range(1, numMessages+1):
1280 (typ, data) = server.fetch(str(i), '(RFC822)')
1282 # mark the message as deleted.
1283 server.store(str(i), '+FLAGS', r'(\Deleted)')
1285 # process the message
1286 s = cStringIO.StringIO(data[0][1])
1287 s.seek(0)
1288 self.handle_Message(Message(s))
1289 server.close()
1290 finally:
1291 try:
1292 server.expunge()
1293 except:
1294 pass
1295 server.logout()
1297 return 0
1300 def do_apop(self, server, user='', password='', ssl=False):
1301 ''' Do authentication POP
1302 '''
1303 self._do_pop(server, user, password, True, ssl)
1305 def do_pop(self, server, user='', password='', ssl=False):
1306 ''' Do plain POP
1307 '''
1308 self._do_pop(server, user, password, False, ssl)
1310 def _do_pop(self, server, user, password, apop, ssl):
1311 '''Read a series of messages from the specified POP server.
1312 '''
1313 import getpass, poplib, socket
1314 try:
1315 if not user:
1316 user = raw_input('User: ')
1317 if not password:
1318 password = getpass.getpass()
1319 except (KeyboardInterrupt, EOFError):
1320 # Ctrl C or D maybe also Ctrl Z under Windows.
1321 print "\nAborted by user."
1322 return 1
1324 # open a connection to the server and retrieve all messages
1325 try:
1326 if ssl:
1327 klass = poplib.POP3_SSL
1328 else:
1329 klass = poplib.POP3
1330 server = klass(server)
1331 except socket.error:
1332 self.logger.exception('POP server error')
1333 return 1
1334 if apop:
1335 server.apop(user, password)
1336 else:
1337 server.user(user)
1338 server.pass_(password)
1339 numMessages = len(server.list()[1])
1340 for i in range(1, numMessages+1):
1341 # retr: returns
1342 # [ pop response e.g. '+OK 459 octets',
1343 # [ array of message lines ],
1344 # number of octets ]
1345 lines = server.retr(i)[1]
1346 s = cStringIO.StringIO('\n'.join(lines))
1347 s.seek(0)
1348 self.handle_Message(Message(s))
1349 # delete the message
1350 server.dele(i)
1352 # quit the server to commit changes.
1353 server.quit()
1354 return 0
1356 def main(self, fp):
1357 ''' fp - the file from which to read the Message.
1358 '''
1359 return self.handle_Message(Message(fp))
1361 def handle_Message(self, message):
1362 """Handle an RFC822 Message
1364 Handle the Message object by calling handle_message() and then cope
1365 with any errors raised by handle_message.
1366 This method's job is to make that call and handle any
1367 errors in a sane manner. It should be replaced if you wish to
1368 handle errors in a different manner.
1369 """
1370 # in some rare cases, a particularly stuffed-up e-mail will make
1371 # its way into here... try to handle it gracefully
1373 sendto = message.getaddrlist('resent-from')
1374 if not sendto:
1375 sendto = message.getaddrlist('from')
1376 if not sendto:
1377 # very bad-looking message - we don't even know who sent it
1378 msg = ['Badly formed message from mail gateway. Headers:']
1379 msg.extend(message.headers)
1380 msg = '\n'.join(map(str, msg))
1381 self.logger.error(msg)
1382 return
1384 msg = 'Handling message'
1385 if message.getheader('message-id'):
1386 msg += ' (Message-id=%r)'%message.getheader('message-id')
1387 self.logger.info(msg)
1389 # try normal message-handling
1390 if not self.trapExceptions:
1391 return self.handle_message(message)
1393 # no, we want to trap exceptions
1394 try:
1395 return self.handle_message(message)
1396 except MailUsageHelp:
1397 # bounce the message back to the sender with the usage message
1398 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1399 m = ['']
1400 m.append('\n\nMail Gateway Help\n=================')
1401 m.append(fulldoc)
1402 self.mailer.bounce_message(message, [sendto[0][1]], m,
1403 subject="Mail Gateway Help")
1404 except MailUsageError, value:
1405 # bounce the message back to the sender with the usage message
1406 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1407 m = ['']
1408 m.append(str(value))
1409 m.append('\n\nMail Gateway Help\n=================')
1410 m.append(fulldoc)
1411 self.mailer.bounce_message(message, [sendto[0][1]], m)
1412 except Unauthorized, value:
1413 # just inform the user that he is not authorized
1414 m = ['']
1415 m.append(str(value))
1416 self.mailer.bounce_message(message, [sendto[0][1]], m)
1417 except IgnoreMessage:
1418 # do not take any action
1419 # this exception is thrown when email should be ignored
1420 msg = 'IgnoreMessage raised'
1421 if message.getheader('message-id'):
1422 msg += ' (Message-id=%r)'%message.getheader('message-id')
1423 self.logger.info(msg)
1424 return
1425 except:
1426 msg = 'Exception handling message'
1427 if message.getheader('message-id'):
1428 msg += ' (Message-id=%r)'%message.getheader('message-id')
1429 self.logger.exception(msg)
1431 # bounce the message back to the sender with the error message
1432 # let the admin know that something very bad is happening
1433 m = ['']
1434 m.append('An unexpected error occurred during the processing')
1435 m.append('of your message. The tracker administrator is being')
1436 m.append('notified.\n')
1437 self.mailer.bounce_message(message, [sendto[0][1]], m)
1439 m.append('----------------')
1440 m.append(traceback.format_exc())
1441 self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
1443 def handle_message(self, message):
1444 ''' message - a Message instance
1446 Parse the message as per the module docstring.
1447 '''
1448 # get database handle for handling one email
1449 self.db = self.instance.open ('admin')
1450 try:
1451 return self._handle_message(message)
1452 finally:
1453 self.db.close()
1455 def _handle_message(self, message):
1456 ''' message - a Message instance
1458 Parse the message as per the module docstring.
1459 The following code expects an opened database and a try/finally
1460 that closes the database.
1461 '''
1462 parsed_message = self.parsed_message_class(self, message)
1464 # Filter out messages to ignore
1465 parsed_message.handle_ignore()
1467 # Check for usage/help requests
1468 parsed_message.handle_help()
1470 # Check if the subject line is valid
1471 parsed_message.check_subject()
1473 # XXX Don't enable. This doesn't work yet.
1474 # XXX once this works it should be moved to parsedMessage class
1475 # "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
1476 # handle delivery to addresses like:tracker+issue25@some.dom.ain
1477 # use the embedded issue number as our issue
1478 # issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
1479 # if issue_re:
1480 # for header in ['to', 'cc', 'bcc']:
1481 # addresses = message.getheader(header, '')
1482 # if addresses:
1483 # # FIXME, this only finds the first match in the addresses.
1484 # issue = re.search(issue_re, addresses, 'i')
1485 # if issue:
1486 # classname = issue.group('classname')
1487 # nodeid = issue.group('nodeid')
1488 # break
1490 # Parse the subject line to get the importants parts
1491 parsed_message.parse_subject()
1493 # check for registration OTK
1494 if parsed_message.rego_confirm():
1495 return
1497 # get the classname
1498 parsed_message.get_classname()
1500 # get the optional nodeid
1501 parsed_message.get_nodeid()
1503 # Determine who the author is
1504 parsed_message.get_author_id()
1506 # make sure they're allowed to edit or create this class
1507 parsed_message.check_node_permissions()
1509 # author may have been created:
1510 # commit author to database and re-open as author
1511 parsed_message.commit_and_reopen_as_author()
1513 # Get the recipients list
1514 parsed_message.get_recipients()
1516 # get the new/updated node props
1517 parsed_message.get_props()
1519 # Handle PGP signed or encrypted messages
1520 parsed_message.get_pgp_message()
1522 # extract content and attachments from message body
1523 parsed_message.get_content_and_attachments()
1525 # put attachments into files linked to the issue
1526 parsed_message.create_files()
1528 # create the message if there's a message body (content)
1529 parsed_message.create_msg()
1531 # perform the node change / create
1532 nodeid = parsed_message.create_node()
1534 # commit the changes to the DB
1535 self.db.commit()
1537 return nodeid
1539 def get_class_arguments(self, class_type, classname=None):
1540 ''' class_type - a valid node class type:
1541 - 'user' refers to the author of a message
1542 - 'issue' refers to an issue-type class (to which the
1543 message is appended) specified in parameter classname
1544 Note that this need not be the real classname, we get
1545 the real classname used as a parameter (from previous
1546 message-parsing steps)
1547 - 'file' specifies a file-type class
1548 - 'msg' is the message-class
1549 classname - the name of the current issue-type class
1551 Parse the commandline arguments and retrieve the properties that
1552 are relevant to the class_type. We now allow multiple -S options
1553 per class_type (-C option).
1554 '''
1555 allprops = {}
1557 classname = classname or class_type
1558 cls_lookup = { 'issue' : classname }
1560 # Allow other issue-type classes -- take the real classname from
1561 # previous parsing-steps of the message:
1562 clsname = cls_lookup.get (class_type, class_type)
1564 # check if the clsname is valid
1565 try:
1566 self.db.getclass(clsname)
1567 except KeyError:
1568 mailadmin = self.instance.config['ADMIN_EMAIL']
1569 raise MailUsageError, _("""
1570 The mail gateway is not properly set up. Please contact
1571 %(mailadmin)s and have them fix the incorrect class specified as:
1572 %(clsname)s
1573 """) % locals()
1575 if self.arguments:
1576 # The default type on the commandline is msg
1577 if class_type == 'msg':
1578 current_type = class_type
1579 else:
1580 current_type = None
1582 # Handle the arguments specified by the email gateway command line.
1583 # We do this by looping over the list of self.arguments looking for
1584 # a -C to match the class we want, then use the -S setting string.
1585 for option, propstring in self.arguments:
1586 if option in ( '-C', '--class'):
1587 current_type = propstring.strip()
1589 if current_type != class_type:
1590 current_type = None
1592 elif current_type and option in ('-S', '--set'):
1593 cls = cls_lookup.get (current_type, current_type)
1594 temp_cl = self.db.getclass(cls)
1595 errors, props = setPropArrayFromString(self,
1596 temp_cl, propstring.strip())
1598 if errors:
1599 mailadmin = self.instance.config['ADMIN_EMAIL']
1600 raise MailUsageError, _("""
1601 The mail gateway is not properly set up. Please contact
1602 %(mailadmin)s and have them fix the incorrect properties:
1603 %(errors)s
1604 """) % locals()
1605 allprops.update(props)
1607 return allprops
1610 def setPropArrayFromString(self, cl, propString, nodeid=None):
1611 ''' takes string of form prop=value,value;prop2=value
1612 and returns (error, prop[..])
1613 '''
1614 props = {}
1615 errors = []
1616 for prop in string.split(propString, ';'):
1617 # extract the property name and value
1618 try:
1619 propname, value = prop.split('=')
1620 except ValueError, message:
1621 errors.append(_('not of form [arg=value,value,...;'
1622 'arg=value,value,...]'))
1623 return (errors, props)
1624 # convert the value to a hyperdb-usable value
1625 propname = propname.strip()
1626 try:
1627 props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1628 propname, value)
1629 except hyperdb.HyperdbValueError, message:
1630 errors.append(str(message))
1631 return errors, props
1634 def extractUserFromList(userClass, users):
1635 '''Given a list of users, try to extract the first non-anonymous user
1636 and return that user, otherwise return None
1637 '''
1638 if len(users) > 1:
1639 for user in users:
1640 # make sure we don't match the anonymous or admin user
1641 if userClass.get(user, 'username') in ('admin', 'anonymous'):
1642 continue
1643 # first valid match will do
1644 return user
1645 # well, I guess we have no choice
1646 return user[0]
1647 elif users:
1648 return users[0]
1649 return None
1652 def uidFromAddress(db, address, create=1, **user_props):
1653 ''' address is from the rfc822 module, and therefore is (name, addr)
1655 user is created if they don't exist in the db already
1656 user_props may supply additional user information
1657 '''
1658 (realname, address) = address
1660 # try a straight match of the address
1661 user = extractUserFromList(db.user, db.user.stringFind(address=address))
1662 if user is not None:
1663 return user
1665 # try the user alternate addresses if possible
1666 props = db.user.getprops()
1667 if props.has_key('alternate_addresses'):
1668 users = db.user.filter(None, {'alternate_addresses': address})
1669 # We want an exact match of the email, not just a substring
1670 # match. Otherwise e.g. support@example.com would match
1671 # discuss-support@example.com which is not what we want.
1672 found_users = []
1673 for u in users:
1674 alt = db.user.get(u, 'alternate_addresses').split('\n')
1675 for a in alt:
1676 if a.strip().lower() == address.lower():
1677 found_users.append(u)
1678 break
1679 user = extractUserFromList(db.user, found_users)
1680 if user is not None:
1681 return user
1683 # try to match the username to the address (for local
1684 # submissions where the address is empty)
1685 user = extractUserFromList(db.user, db.user.stringFind(username=address))
1687 # couldn't match address or username, so create a new user
1688 if create:
1689 # generate a username
1690 if '@' in address:
1691 username = address.split('@')[0]
1692 else:
1693 username = address
1694 trying = username
1695 n = 0
1696 while 1:
1697 try:
1698 # does this username exist already?
1699 db.user.lookup(trying)
1700 except KeyError:
1701 break
1702 n += 1
1703 trying = username + str(n)
1705 # create!
1706 try:
1707 return db.user.create(username=trying, address=address,
1708 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1709 password=password.Password(password.generatePassword(), config=db.config),
1710 **user_props)
1711 except exceptions.Reject:
1712 return 0
1713 else:
1714 return 0
1716 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1717 """Parse mail message; return message summary and stripped content
1719 The message body is divided into sections by blank lines.
1720 Sections where the second and all subsequent lines begin with a ">"
1721 or "|" character are considered "quoting sections". The first line of
1722 the first non-quoting section becomes the summary of the message.
1724 Arguments:
1726 keep_citations: declared for backward compatibility.
1727 If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1729 keep_body: declared for backward compatibility.
1730 If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1732 config: tracker configuration object.
1733 If omitted or None, use default configuration.
1735 """
1736 if config is None:
1737 config = configuration.CoreConfig()
1738 if keep_citations is None:
1739 keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1740 if keep_body is None:
1741 keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1742 eol = config["MAILGW_EOL_RE"]
1743 signature = config["MAILGW_SIGN_RE"]
1744 original_msg = config["MAILGW_ORIGMSG_RE"]
1746 # strip off leading carriage-returns / newlines
1747 i = 0
1748 for i in range(len(content)):
1749 if content[i] not in '\r\n':
1750 break
1751 if i > 0:
1752 sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1753 else:
1754 sections = config["MAILGW_BLANKLINE_RE"].split(content)
1756 # extract out the summary from the message
1757 summary = ''
1758 l = []
1759 for section in sections:
1760 #section = section.strip()
1761 if not section:
1762 continue
1763 lines = eol.split(section)
1764 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1765 lines[1] and lines[1][0] in '>|'):
1766 # see if there's a response somewhere inside this section (ie.
1767 # no blank line between quoted message and response)
1768 for line in lines[1:]:
1769 if line and line[0] not in '>|':
1770 break
1771 else:
1772 # we keep quoted bits if specified in the config
1773 if keep_citations:
1774 l.append(section)
1775 continue
1776 # keep this section - it has reponse stuff in it
1777 lines = lines[lines.index(line):]
1778 section = '\n'.join(lines)
1779 # and while we're at it, use the first non-quoted bit as
1780 # our summary
1781 summary = section
1783 if not summary:
1784 # if we don't have our summary yet use the first line of this
1785 # section
1786 summary = section
1787 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1788 # lose any signature
1789 break
1790 elif original_msg.match(lines[0]):
1791 # ditch the stupid Outlook quoting of the entire original message
1792 break
1794 # and add the section to the output
1795 l.append(section)
1797 # figure the summary - find the first sentence-ending punctuation or the
1798 # first whole line, whichever is longest
1799 sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1800 if sentence:
1801 sentence = sentence.group(1)
1802 else:
1803 sentence = ''
1804 first = eol.split(summary)[0]
1805 summary = max(sentence, first)
1807 # Now reconstitute the message content minus the bits we don't care
1808 # about.
1809 if not keep_body:
1810 content = '\n\n'.join(l)
1812 return summary, content
1814 # vim: set filetype=python sts=4 sw=4 et si :