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_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
1158 # XXX Don't enable. This doesn't work yet.
1159 # "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
1160 # handle delivery to addresses like:tracker+issue25@some.dom.ain
1161 # use the embedded issue number as our issue
1162 # issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
1163 # if issue_re:
1164 # for header in ['to', 'cc', 'bcc']:
1165 # addresses = message.getheader(header, '')
1166 # if addresses:
1167 # # FIXME, this only finds the first match in the addresses.
1168 # issue = re.search(issue_re, addresses, 'i')
1169 # if issue:
1170 # classname = issue.group('classname')
1171 # nodeid = issue.group('nodeid')
1172 # break
1174 # Default sequence of methods to be called on message. Use this for
1175 # easier override of the default message processing
1176 # list consists of tuples (method, return_if_true), the parsing
1177 # returns if the return_if_true flag is set for a method *and* the
1178 # method returns something that evaluates to True.
1179 method_list = [
1180 # Filter out messages to ignore
1181 (handle_ignore, False),
1182 # Check for usage/help requests
1183 (handle_help, False),
1184 # Check if the subject line is valid
1185 (check_subject, False),
1186 # get importants parts from subject
1187 (parse_subject, False),
1188 # check for registration OTK
1189 (rego_confirm, True),
1190 # get the classname
1191 (get_classname, False),
1192 # get the optional nodeid:
1193 (get_nodeid, False),
1194 # Determine who the author is:
1195 (get_author_id, False),
1196 # allowed to edit or create this class?
1197 (check_permissions, False),
1198 # author may have been created:
1199 # commit author to database and re-open as author
1200 (commit_and_reopen_as_author, False),
1201 # Get the recipients list
1202 (get_recipients, False),
1203 # get the new/updated node props
1204 (get_props, False),
1205 # Handle PGP signed or encrypted messages
1206 (get_pgp_message, False),
1207 # extract content and attachments from message body:
1208 (get_content_and_attachments, False),
1209 # put attachments into files linked to the issue:
1210 (create_files, False),
1211 # create the message if there's a message body (content):
1212 (create_msg, False),
1213 ]
1216 def parse (self):
1217 for method, flag in self.method_list:
1218 ret = method(self)
1219 if flag and ret:
1220 return
1221 # perform the node change / create:
1222 return self.create_node()
1225 class MailGW:
1227 # To override the message parsing, derive your own class from
1228 # parsedMessage and assign to parsed_message_class in a derived
1229 # class of MailGW
1230 parsed_message_class = parsedMessage
1232 def __init__(self, instance, arguments=()):
1233 self.instance = instance
1234 self.arguments = arguments
1235 self.default_class = None
1236 for option, value in self.arguments:
1237 if option == '-c':
1238 self.default_class = value.strip()
1240 self.mailer = Mailer(instance.config)
1241 self.logger = logging.getLogger('roundup.mailgw')
1243 # should we trap exceptions (normal usage) or pass them through
1244 # (for testing)
1245 self.trapExceptions = 1
1247 def do_pipe(self):
1248 """ Read a message from standard input and pass it to the mail handler.
1250 Read into an internal structure that we can seek on (in case
1251 there's an error).
1253 XXX: we may want to read this into a temporary file instead...
1254 """
1255 s = cStringIO.StringIO()
1256 s.write(sys.stdin.read())
1257 s.seek(0)
1258 self.main(s)
1259 return 0
1261 def do_mailbox(self, filename):
1262 """ Read a series of messages from the specified unix mailbox file and
1263 pass each to the mail handler.
1264 """
1265 # open the spool file and lock it
1266 import fcntl
1267 # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
1268 if hasattr(fcntl, 'LOCK_EX'):
1269 FCNTL = fcntl
1270 else:
1271 import FCNTL
1272 f = open(filename, 'r+')
1273 fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
1275 # handle and clear the mailbox
1276 try:
1277 from mailbox import UnixMailbox
1278 mailbox = UnixMailbox(f, factory=Message)
1279 # grab one message
1280 message = mailbox.next()
1281 while message:
1282 # handle this message
1283 self.handle_Message(message)
1284 message = mailbox.next()
1285 # nuke the file contents
1286 os.ftruncate(f.fileno(), 0)
1287 except:
1288 import traceback
1289 traceback.print_exc()
1290 return 1
1291 fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
1292 return 0
1294 def do_imap(self, server, user='', password='', mailbox='', ssl=0,
1295 cram=0):
1296 ''' Do an IMAP connection
1297 '''
1298 import getpass, imaplib, socket
1299 try:
1300 if not user:
1301 user = raw_input('User: ')
1302 if not password:
1303 password = getpass.getpass()
1304 except (KeyboardInterrupt, EOFError):
1305 # Ctrl C or D maybe also Ctrl Z under Windows.
1306 print "\nAborted by user."
1307 return 1
1308 # open a connection to the server and retrieve all messages
1309 try:
1310 if ssl:
1311 self.logger.debug('Trying server %r with ssl'%server)
1312 server = imaplib.IMAP4_SSL(server)
1313 else:
1314 self.logger.debug('Trying server %r without ssl'%server)
1315 server = imaplib.IMAP4(server)
1316 except (imaplib.IMAP4.error, socket.error, socket.sslerror):
1317 self.logger.exception('IMAP server error')
1318 return 1
1320 try:
1321 if cram:
1322 server.login_cram_md5(user, password)
1323 else:
1324 server.login(user, password)
1325 except imaplib.IMAP4.error, e:
1326 self.logger.exception('IMAP login failure')
1327 return 1
1329 try:
1330 if not mailbox:
1331 (typ, data) = server.select()
1332 else:
1333 (typ, data) = server.select(mailbox=mailbox)
1334 if typ != 'OK':
1335 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
1336 data))
1337 return 1
1338 try:
1339 numMessages = int(data[0])
1340 except ValueError, value:
1341 self.logger.error('Invalid message count from mailbox %r'%
1342 data[0])
1343 return 1
1344 for i in range(1, numMessages+1):
1345 (typ, data) = server.fetch(str(i), '(RFC822)')
1347 # mark the message as deleted.
1348 server.store(str(i), '+FLAGS', r'(\Deleted)')
1350 # process the message
1351 s = cStringIO.StringIO(data[0][1])
1352 s.seek(0)
1353 self.handle_Message(Message(s))
1354 server.close()
1355 finally:
1356 try:
1357 server.expunge()
1358 except:
1359 pass
1360 server.logout()
1362 return 0
1365 def do_apop(self, server, user='', password='', ssl=False):
1366 ''' Do authentication POP
1367 '''
1368 self._do_pop(server, user, password, True, ssl)
1370 def do_pop(self, server, user='', password='', ssl=False):
1371 ''' Do plain POP
1372 '''
1373 self._do_pop(server, user, password, False, ssl)
1375 def _do_pop(self, server, user, password, apop, ssl):
1376 '''Read a series of messages from the specified POP server.
1377 '''
1378 import getpass, poplib, socket
1379 try:
1380 if not user:
1381 user = raw_input('User: ')
1382 if not password:
1383 password = getpass.getpass()
1384 except (KeyboardInterrupt, EOFError):
1385 # Ctrl C or D maybe also Ctrl Z under Windows.
1386 print "\nAborted by user."
1387 return 1
1389 # open a connection to the server and retrieve all messages
1390 try:
1391 if ssl:
1392 klass = poplib.POP3_SSL
1393 else:
1394 klass = poplib.POP3
1395 server = klass(server)
1396 except socket.error:
1397 self.logger.exception('POP server error')
1398 return 1
1399 if apop:
1400 server.apop(user, password)
1401 else:
1402 server.user(user)
1403 server.pass_(password)
1404 numMessages = len(server.list()[1])
1405 for i in range(1, numMessages+1):
1406 # retr: returns
1407 # [ pop response e.g. '+OK 459 octets',
1408 # [ array of message lines ],
1409 # number of octets ]
1410 lines = server.retr(i)[1]
1411 s = cStringIO.StringIO('\n'.join(lines))
1412 s.seek(0)
1413 self.handle_Message(Message(s))
1414 # delete the message
1415 server.dele(i)
1417 # quit the server to commit changes.
1418 server.quit()
1419 return 0
1421 def main(self, fp):
1422 ''' fp - the file from which to read the Message.
1423 '''
1424 return self.handle_Message(Message(fp))
1426 def handle_Message(self, message):
1427 """Handle an RFC822 Message
1429 Handle the Message object by calling handle_message() and then cope
1430 with any errors raised by handle_message.
1431 This method's job is to make that call and handle any
1432 errors in a sane manner. It should be replaced if you wish to
1433 handle errors in a different manner.
1434 """
1435 # in some rare cases, a particularly stuffed-up e-mail will make
1436 # its way into here... try to handle it gracefully
1438 self.parsed_message = None
1439 sendto = message.getaddrlist('resent-from')
1440 if not sendto:
1441 sendto = message.getaddrlist('from')
1442 if not sendto:
1443 # very bad-looking message - we don't even know who sent it
1444 msg = ['Badly formed message from mail gateway. Headers:']
1445 msg.extend(message.headers)
1446 msg = '\n'.join(map(str, msg))
1447 self.logger.error(msg)
1448 return
1450 msg = 'Handling message'
1451 if message.getheader('message-id'):
1452 msg += ' (Message-id=%r)'%message.getheader('message-id')
1453 self.logger.info(msg)
1455 # try normal message-handling
1456 if not self.trapExceptions:
1457 return self.handle_message(message)
1459 # no, we want to trap exceptions
1460 try:
1461 return self.handle_message(message)
1462 except MailUsageHelp:
1463 # bounce the message back to the sender with the usage message
1464 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1465 m = ['']
1466 m.append('\n\nMail Gateway Help\n=================')
1467 m.append(fulldoc)
1468 self.mailer.bounce_message(message, [sendto[0][1]], m,
1469 subject="Mail Gateway Help")
1470 except MailUsageError, value:
1471 # bounce the message back to the sender with the usage message
1472 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1473 m = ['']
1474 m.append(str(value))
1475 m.append('\n\nMail Gateway Help\n=================')
1476 m.append(fulldoc)
1477 self.mailer.bounce_message(message, [sendto[0][1]], m)
1478 except Unauthorized, value:
1479 # just inform the user that he is not authorized
1480 m = ['']
1481 m.append(str(value))
1482 self.mailer.bounce_message(message, [sendto[0][1]], m)
1483 except IgnoreMessage:
1484 # do not take any action
1485 # this exception is thrown when email should be ignored
1486 msg = 'IgnoreMessage raised'
1487 if message.getheader('message-id'):
1488 msg += ' (Message-id=%r)'%message.getheader('message-id')
1489 self.logger.info(msg)
1490 return
1491 except:
1492 msg = 'Exception handling message'
1493 if message.getheader('message-id'):
1494 msg += ' (Message-id=%r)'%message.getheader('message-id')
1495 self.logger.exception(msg)
1497 # bounce the message back to the sender with the error message
1498 # let the admin know that something very bad is happening
1499 m = ['']
1500 m.append('An unexpected error occurred during the processing')
1501 m.append('of your message. The tracker administrator is being')
1502 m.append('notified.\n')
1503 self.mailer.bounce_message(message, [sendto[0][1]], m)
1505 m.append('----------------')
1506 m.append(traceback.format_exc())
1507 self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
1509 def handle_message(self, message):
1510 ''' message - a Message instance
1512 Parse the message as per the module docstring.
1513 '''
1514 # get database handle for handling one email
1515 self.db = self.instance.open ('admin')
1516 try:
1517 return self._handle_message(message)
1518 finally:
1519 self.db.close()
1521 def _handle_message(self, message):
1522 ''' message - a Message instance
1524 Parse the message as per the module docstring.
1525 The following code expects an opened database and a try/finally
1526 that closes the database.
1527 '''
1528 self.parsed_message = self.parsed_message_class(self, message)
1529 nodeid = self.parsed_message.parse ()
1531 # commit the changes to the DB
1532 self.db.commit()
1534 return nodeid
1536 def get_class_arguments(self, class_type, classname=None):
1537 ''' class_type - a valid node class type:
1538 - 'user' refers to the author of a message
1539 - 'issue' refers to an issue-type class (to which the
1540 message is appended) specified in parameter classname
1541 Note that this need not be the real classname, we get
1542 the real classname used as a parameter (from previous
1543 message-parsing steps)
1544 - 'file' specifies a file-type class
1545 - 'msg' is the message-class
1546 classname - the name of the current issue-type class
1548 Parse the commandline arguments and retrieve the properties that
1549 are relevant to the class_type. We now allow multiple -S options
1550 per class_type (-C option).
1551 '''
1552 allprops = {}
1554 classname = classname or class_type
1555 cls_lookup = { 'issue' : classname }
1557 # Allow other issue-type classes -- take the real classname from
1558 # previous parsing-steps of the message:
1559 clsname = cls_lookup.get (class_type, class_type)
1561 # check if the clsname is valid
1562 try:
1563 self.db.getclass(clsname)
1564 except KeyError:
1565 mailadmin = self.instance.config['ADMIN_EMAIL']
1566 raise MailUsageError, _("""
1567 The mail gateway is not properly set up. Please contact
1568 %(mailadmin)s and have them fix the incorrect class specified as:
1569 %(clsname)s
1570 """) % locals()
1572 if self.arguments:
1573 # The default type on the commandline is msg
1574 if class_type == 'msg':
1575 current_type = class_type
1576 else:
1577 current_type = None
1579 # Handle the arguments specified by the email gateway command line.
1580 # We do this by looping over the list of self.arguments looking for
1581 # a -C to match the class we want, then use the -S setting string.
1582 for option, propstring in self.arguments:
1583 if option in ( '-C', '--class'):
1584 current_type = propstring.strip()
1586 if current_type != class_type:
1587 current_type = None
1589 elif current_type and option in ('-S', '--set'):
1590 cls = cls_lookup.get (current_type, current_type)
1591 temp_cl = self.db.getclass(cls)
1592 errors, props = setPropArrayFromString(self,
1593 temp_cl, propstring.strip())
1595 if errors:
1596 mailadmin = self.instance.config['ADMIN_EMAIL']
1597 raise MailUsageError, _("""
1598 The mail gateway is not properly set up. Please contact
1599 %(mailadmin)s and have them fix the incorrect properties:
1600 %(errors)s
1601 """) % locals()
1602 allprops.update(props)
1604 return allprops
1607 def setPropArrayFromString(self, cl, propString, nodeid=None):
1608 ''' takes string of form prop=value,value;prop2=value
1609 and returns (error, prop[..])
1610 '''
1611 props = {}
1612 errors = []
1613 for prop in string.split(propString, ';'):
1614 # extract the property name and value
1615 try:
1616 propname, value = prop.split('=')
1617 except ValueError, message:
1618 errors.append(_('not of form [arg=value,value,...;'
1619 'arg=value,value,...]'))
1620 return (errors, props)
1621 # convert the value to a hyperdb-usable value
1622 propname = propname.strip()
1623 try:
1624 props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1625 propname, value)
1626 except hyperdb.HyperdbValueError, message:
1627 errors.append(str(message))
1628 return errors, props
1631 def extractUserFromList(userClass, users):
1632 '''Given a list of users, try to extract the first non-anonymous user
1633 and return that user, otherwise return None
1634 '''
1635 if len(users) > 1:
1636 for user in users:
1637 # make sure we don't match the anonymous or admin user
1638 if userClass.get(user, 'username') in ('admin', 'anonymous'):
1639 continue
1640 # first valid match will do
1641 return user
1642 # well, I guess we have no choice
1643 return user[0]
1644 elif users:
1645 return users[0]
1646 return None
1649 def uidFromAddress(db, address, create=1, **user_props):
1650 ''' address is from the rfc822 module, and therefore is (name, addr)
1652 user is created if they don't exist in the db already
1653 user_props may supply additional user information
1654 '''
1655 (realname, address) = address
1657 # try a straight match of the address
1658 user = extractUserFromList(db.user, db.user.stringFind(address=address))
1659 if user is not None:
1660 return user
1662 # try the user alternate addresses if possible
1663 props = db.user.getprops()
1664 if props.has_key('alternate_addresses'):
1665 users = db.user.filter(None, {'alternate_addresses': address})
1666 # We want an exact match of the email, not just a substring
1667 # match. Otherwise e.g. support@example.com would match
1668 # discuss-support@example.com which is not what we want.
1669 found_users = []
1670 for u in users:
1671 alt = db.user.get(u, 'alternate_addresses').split('\n')
1672 for a in alt:
1673 if a.strip().lower() == address.lower():
1674 found_users.append(u)
1675 break
1676 user = extractUserFromList(db.user, found_users)
1677 if user is not None:
1678 return user
1680 # try to match the username to the address (for local
1681 # submissions where the address is empty)
1682 user = extractUserFromList(db.user, db.user.stringFind(username=address))
1684 # couldn't match address or username, so create a new user
1685 if create:
1686 # generate a username
1687 if '@' in address:
1688 username = address.split('@')[0]
1689 else:
1690 username = address
1691 trying = username
1692 n = 0
1693 while 1:
1694 try:
1695 # does this username exist already?
1696 db.user.lookup(trying)
1697 except KeyError:
1698 break
1699 n += 1
1700 trying = username + str(n)
1702 # create!
1703 try:
1704 return db.user.create(username=trying, address=address,
1705 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1706 password=password.Password(password.generatePassword(), config=db.config),
1707 **user_props)
1708 except exceptions.Reject:
1709 return 0
1710 else:
1711 return 0
1713 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1714 """Parse mail message; return message summary and stripped content
1716 The message body is divided into sections by blank lines.
1717 Sections where the second and all subsequent lines begin with a ">"
1718 or "|" character are considered "quoting sections". The first line of
1719 the first non-quoting section becomes the summary of the message.
1721 Arguments:
1723 keep_citations: declared for backward compatibility.
1724 If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1726 keep_body: declared for backward compatibility.
1727 If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1729 config: tracker configuration object.
1730 If omitted or None, use default configuration.
1732 """
1733 if config is None:
1734 config = configuration.CoreConfig()
1735 if keep_citations is None:
1736 keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1737 if keep_body is None:
1738 keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1739 eol = config["MAILGW_EOL_RE"]
1740 signature = config["MAILGW_SIGN_RE"]
1741 original_msg = config["MAILGW_ORIGMSG_RE"]
1743 # strip off leading carriage-returns / newlines
1744 i = 0
1745 for i in range(len(content)):
1746 if content[i] not in '\r\n':
1747 break
1748 if i > 0:
1749 sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1750 else:
1751 sections = config["MAILGW_BLANKLINE_RE"].split(content)
1753 # extract out the summary from the message
1754 summary = ''
1755 l = []
1756 for section in sections:
1757 #section = section.strip()
1758 if not section:
1759 continue
1760 lines = eol.split(section)
1761 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1762 lines[1] and lines[1][0] in '>|'):
1763 # see if there's a response somewhere inside this section (ie.
1764 # no blank line between quoted message and response)
1765 for line in lines[1:]:
1766 if line and line[0] not in '>|':
1767 break
1768 else:
1769 # we keep quoted bits if specified in the config
1770 if keep_citations:
1771 l.append(section)
1772 continue
1773 # keep this section - it has reponse stuff in it
1774 lines = lines[lines.index(line):]
1775 section = '\n'.join(lines)
1776 # and while we're at it, use the first non-quoted bit as
1777 # our summary
1778 summary = section
1780 if not summary:
1781 # if we don't have our summary yet use the first line of this
1782 # section
1783 summary = section
1784 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1785 # lose any signature
1786 break
1787 elif original_msg.match(lines[0]):
1788 # ditch the stupid Outlook quoting of the entire original message
1789 break
1791 # and add the section to the output
1792 l.append(section)
1794 # figure the summary - find the first sentence-ending punctuation or the
1795 # first whole line, whichever is longest
1796 sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1797 if sentence:
1798 sentence = sentence.group(1)
1799 else:
1800 sentence = ''
1801 first = eol.split(summary)[0]
1802 summary = max(sentence, first)
1804 # Now reconstitute the message content minus the bits we don't care
1805 # about.
1806 if not keep_body:
1807 content = '\n\n'.join(l)
1809 return summary, content
1811 # vim: set filetype=python sts=4 sw=4 et si :