cd068899b2c622f35e8e2ab0f144c20b602a65ae
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 getheader(self, name, default=None):
251 hdr = mimetools.Message.getheader(self, name, default)
252 # TODO are there any other False values possible?
253 # TODO if not hdr: return hdr
254 if hdr is None:
255 return None
256 if not hdr:
257 return ''
258 if hdr:
259 hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders
260 # historically this method has returned utf-8 encoded string
261 l = []
262 for part, encoding in decode_header(hdr):
263 if encoding:
264 part = part.decode(encoding)
265 l.append(part)
266 return ''.join([s.encode('utf-8') for s in l])
268 def getaddrlist(self, name):
269 # overload to decode the name part of the address
270 l = []
271 for (name, addr) in mimetools.Message.getaddrlist(self, name):
272 p = []
273 for part, encoding in decode_header(name):
274 if encoding:
275 part = part.decode(encoding)
276 p.append(part)
277 name = ''.join([s.encode('utf-8') for s in p])
278 l.append((name, addr))
279 return l
281 def getname(self):
282 """Find an appropriate name for this message."""
283 name = None
284 if self.gettype() == 'message/rfc822':
285 # handle message/rfc822 specially - the name should be
286 # the subject of the actual e-mail embedded here
287 # we add a '.eml' extension like other email software does it
288 self.fp.seek(0)
289 s = cStringIO.StringIO(self.getbody())
290 name = Message(s).getheader('subject')
291 if name:
292 name = name + '.eml'
293 if not name:
294 # try name on Content-Type
295 name = self.getparam('name')
296 if not name:
297 disp = self.getheader('content-disposition', None)
298 if disp:
299 name = getparam(disp, 'filename')
301 if name:
302 return name.strip()
304 def getbody(self):
305 """Get the decoded message body."""
306 self.rewindbody()
307 encoding = self.getencoding()
308 data = None
309 if encoding == 'base64':
310 # BUG: is base64 really used for text encoding or
311 # are we inserting zip files here.
312 data = binascii.a2b_base64(self.fp.read())
313 elif encoding == 'quoted-printable':
314 # the quopri module wants to work with files
315 decoded = cStringIO.StringIO()
316 quopri.decode(self.fp, decoded)
317 data = decoded.getvalue()
318 elif encoding == 'uuencoded':
319 data = binascii.a2b_uu(self.fp.read())
320 else:
321 # take it as text
322 data = self.fp.read()
324 # Encode message to unicode
325 charset = rfc2822.unaliasCharset(self.getparam("charset"))
326 if charset:
327 # Do conversion only if charset specified - handle
328 # badly-specified charsets
329 edata = unicode(data, charset, 'replace').encode('utf-8')
330 # Convert from dos eol to unix
331 edata = edata.replace('\r\n', '\n')
332 else:
333 # Leave message content as is
334 edata = data
336 return edata
338 # General multipart handling:
339 # Take the first text/plain part, anything else is considered an
340 # attachment.
341 # multipart/mixed:
342 # Multiple "unrelated" parts.
343 # multipart/Alternative (rfc 1521):
344 # Like multipart/mixed, except that we'd only want one of the
345 # alternatives. Generally a top-level part from MUAs sending HTML
346 # mail - there will be a text/plain version.
347 # multipart/signed (rfc 1847):
348 # The control information is carried in the second of the two
349 # required body parts.
350 # ACTION: Default, so if content is text/plain we get it.
351 # multipart/encrypted (rfc 1847):
352 # The control information is carried in the first of the two
353 # required body parts.
354 # ACTION: Not handleable as the content is encrypted.
355 # multipart/related (rfc 1872, 2112, 2387):
356 # The Multipart/Related content-type addresses the MIME
357 # representation of compound objects, usually HTML mail with embedded
358 # images. Usually appears as an alternative.
359 # ACTION: Default, if we must.
360 # multipart/report (rfc 1892):
361 # e.g. mail system delivery status reports.
362 # ACTION: Default. Could be ignored or used for Delivery Notification
363 # flagging.
364 # multipart/form-data:
365 # For web forms only.
366 # message/rfc822:
367 # Only if configured in [mailgw] unpack_rfc822
369 def extract_content(self, parent_type=None, ignore_alternatives=False,
370 unpack_rfc822=False):
371 """Extract the body and the attachments recursively.
373 If the content is hidden inside a multipart/alternative part,
374 we use the *last* text/plain part of the *first*
375 multipart/alternative in the whole message.
376 """
377 content_type = self.gettype()
378 content = None
379 attachments = []
381 if content_type == 'text/plain':
382 content = self.getbody()
383 elif content_type[:10] == 'multipart/':
384 content_found = bool (content)
385 ig = ignore_alternatives and not content_found
386 for part in self.getparts():
387 new_content, new_attach = part.extract_content(content_type,
388 not content and ig, unpack_rfc822)
390 # If we haven't found a text/plain part yet, take this one,
391 # otherwise make it an attachment.
392 if not content:
393 content = new_content
394 cpart = part
395 elif new_content:
396 if content_found or content_type != 'multipart/alternative':
397 attachments.append(part.text_as_attachment())
398 else:
399 # if we have found a text/plain in the current
400 # multipart/alternative and find another one, we
401 # use the first as an attachment (if configured)
402 # and use the second one because rfc 2046, sec.
403 # 5.1.4. specifies that later parts are better
404 # (thanks to Philipp Gortan for pointing this
405 # out)
406 attachments.append(cpart.text_as_attachment())
407 content = new_content
408 cpart = part
410 attachments.extend(new_attach)
411 if ig and content_type == 'multipart/alternative' and content:
412 attachments = []
413 elif unpack_rfc822 and content_type == 'message/rfc822':
414 s = cStringIO.StringIO(self.getbody())
415 m = Message(s)
416 ig = ignore_alternatives and not content
417 new_content, attachments = m.extract_content(m.gettype(), ig,
418 unpack_rfc822)
419 attachments.insert(0, m.text_as_attachment())
420 elif (parent_type == 'multipart/signed' and
421 content_type == 'application/pgp-signature'):
422 # ignore it so it won't be saved as an attachment
423 pass
424 else:
425 attachments.append(self.as_attachment())
426 return content, attachments
428 def text_as_attachment(self):
429 """Return first text/plain part as Message"""
430 if not self.gettype().startswith ('multipart/'):
431 return self.as_attachment()
432 for part in self.getparts():
433 content_type = part.gettype()
434 if content_type == 'text/plain':
435 return part.as_attachment()
436 elif content_type.startswith ('multipart/'):
437 p = part.text_as_attachment()
438 if p:
439 return p
440 return None
442 def as_attachment(self):
443 """Return this message as an attachment."""
444 return (self.getname(), self.gettype(), self.getbody())
446 def pgp_signed(self):
447 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
448 '''
449 return self.gettype() == 'multipart/signed' \
450 and self.typeheader.find('protocol="application/pgp-signature"') != -1
452 def pgp_encrypted(self):
453 ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter
454 '''
455 return self.gettype() == 'multipart/encrypted' \
456 and self.typeheader.find('protocol="application/pgp-encrypted"') != -1
458 def decrypt(self, author):
459 ''' decrypt an OpenPGP MIME message
460 This message must be signed as well as encrypted using the "combined"
461 method. The decrypted contents are returned as a new message.
462 '''
463 (hdr, msg) = self.getparts()
464 # According to the RFC 3156 encrypted mail must have exactly two parts.
465 # The first part contains the control information. Let's verify that
466 # the message meets the RFC before we try to decrypt it.
467 if hdr.getbody() != 'Version: 1' or hdr.gettype() != 'application/pgp-encrypted':
468 raise MailUsageError, \
469 _("Unknown multipart/encrypted version.")
471 context = pyme.core.Context()
472 ciphertext = pyme.core.Data(msg.getbody())
473 plaintext = pyme.core.Data()
475 result = context.op_decrypt_verify(ciphertext, plaintext)
477 if result:
478 raise MailUsageError, _("Unable to decrypt your message.")
480 # we've decrypted it but that just means they used our public
481 # key to send it to us. now check the signatures to see if it
482 # was signed by someone we trust
483 result = context.op_verify_result()
484 check_pgp_sigs(result.signatures, context, author)
486 plaintext.seek(0,0)
487 # pyme.core.Data implements a seek method with a different signature
488 # than roundup can handle. So we'll put the data in a container that
489 # the Message class can work with.
490 c = cStringIO.StringIO()
491 c.write(plaintext.read())
492 c.seek(0)
493 return Message(c)
495 def verify_signature(self, author):
496 ''' verify the signature of an OpenPGP MIME message
497 This only handles detached signatures. Old style
498 PGP mail (i.e. '-----BEGIN PGP SIGNED MESSAGE----')
499 is archaic and not supported :)
500 '''
501 # we don't check the micalg parameter...gpgme seems to
502 # figure things out on its own
503 (msg, sig) = self.getparts()
505 if sig.gettype() != 'application/pgp-signature':
506 raise MailUsageError, \
507 _("No PGP signature found in message.")
509 context = pyme.core.Context()
510 # msg.getbody() is skipping over some headers that are
511 # required to be present for verification to succeed so
512 # we'll do this by hand
513 msg.fp.seek(0)
514 # according to rfc 3156 the data "MUST first be converted
515 # to its content-type specific canonical form. For
516 # text/plain this means conversion to an appropriate
517 # character set and conversion of line endings to the
518 # canonical <CR><LF> sequence."
519 # TODO: what about character set conversion?
520 canonical_msg = re.sub('(?<!\r)\n', '\r\n', msg.fp.read())
521 msg_data = pyme.core.Data(canonical_msg)
522 sig_data = pyme.core.Data(sig.getbody())
524 context.op_verify(sig_data, msg_data, None)
526 # check all signatures for validity
527 result = context.op_verify_result()
528 check_pgp_sigs(result.signatures, context, author)
530 class parsedMessage:
532 def __init__(self, mailgw, message):
533 self.mailgw = mailgw
534 self.config = mailgw.instance.config
535 self.db = mailgw.db
536 self.message = message
537 self.subject = message.getheader('subject', '')
538 self.has_prefix = False
539 self.matches = dict.fromkeys(['refwd', 'quote', 'classname',
540 'nodeid', 'title', 'args', 'argswhole'])
541 self.from_list = message.getaddrlist('resent-from') \
542 or message.getaddrlist('from')
543 self.pfxmode = self.config['MAILGW_SUBJECT_PREFIX_PARSING']
544 self.sfxmode = self.config['MAILGW_SUBJECT_SUFFIX_PARSING']
545 # these are filled in by subsequent parsing steps
546 self.classname = None
547 self.properties = None
548 self.cl = None
549 self.nodeid = None
550 self.author = None
551 self.recipients = None
552 self.props = None
553 self.content = None
554 self.attachments = None
556 def handle_ignore(self):
557 ''' Check to see if message can be safely ignored:
558 detect loops and
559 Precedence: Bulk, or Microsoft Outlook autoreplies
560 '''
561 if self.message.getheader('x-roundup-loop', ''):
562 raise IgnoreLoop
563 if (self.message.getheader('precedence', '') == 'bulk'
564 or self.subject.lower().find("autoreply") > 0):
565 raise IgnoreBulk
567 def handle_help(self):
568 ''' Check to see if the message contains a usage/help request
569 '''
570 if self.subject.strip().lower() == 'help':
571 raise MailUsageHelp
573 def check_subject(self):
574 ''' Check to see if the message contains a valid subject line
575 '''
576 if not self.subject:
577 raise MailUsageError, _("""
578 Emails to Roundup trackers must include a Subject: line!
579 """)
581 def parse_subject(self):
582 ''' Matches subjects like:
583 Re: "[issue1234] title of issue [status=resolved]"
585 Each part of the subject is matched, stored, then removed from the
586 start of the subject string as needed. The stored values are then
587 returned
588 '''
590 tmpsubject = self.subject
592 sd_open, sd_close = self.config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
593 delim_open = re.escape(sd_open)
594 if delim_open in '[(': delim_open = '\\' + delim_open
595 delim_close = re.escape(sd_close)
596 if delim_close in '[(': delim_close = '\\' + delim_close
598 # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
599 re_re = r"(?P<refwd>%s)\s*" % self.config["MAILGW_REFWD_RE"].pattern
600 m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
601 if m:
602 m = m.groupdict()
603 if m['refwd']:
604 self.matches.update(m)
605 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
607 # Look for Leading "
608 m = re.match(r'(?P<quote>\s*")', tmpsubject,
609 re.IGNORECASE)
610 if m:
611 self.matches.update(m.groupdict())
612 tmpsubject = tmpsubject[len(self.matches['quote']):] # Consume quote
614 # Check if the subject includes a prefix
615 self.has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
616 delim_close), tmpsubject.strip())
618 # Match the classname if specified
619 class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
620 "|".join(self.db.getclasses()), delim_close)
621 # Note: re.search, not re.match as there might be garbage
622 # (mailing list prefix, etc.) before the class identifier
623 m = re.search(class_re, tmpsubject, re.IGNORECASE)
624 if m:
625 self.matches.update(m.groupdict())
626 # Skip to the end of the class identifier, including any
627 # garbage before it.
629 tmpsubject = tmpsubject[m.end():]
631 # Match the title of the subject
632 # if we've not found a valid classname prefix then force the
633 # scanning to handle there being a leading delimiter
634 title_re = r'(?P<title>%s[^%s]*)'%(
635 not self.matches['classname'] and '.' or '', delim_open)
636 m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
637 if m:
638 self.matches.update(m.groupdict())
639 tmpsubject = tmpsubject[len(self.matches['title']):] # Consume title
641 if self.matches['title']:
642 self.matches['title'] = self.matches['title'].strip()
643 else:
644 self.matches['title'] = ''
646 # strip off the quotes that dumb emailers put around the subject, like
647 # Re: "[issue1] bla blah"
648 if self.matches['quote'] and self.matches['title'].endswith('"'):
649 self.matches['title'] = self.matches['title'][:-1]
651 # Match any arguments specified
652 args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
653 delim_close)
654 m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
655 if m:
656 self.matches.update(m.groupdict())
658 def rego_confirm(self):
659 ''' Check for registration OTK and confirm the registration if found
660 '''
662 if self.config['EMAIL_REGISTRATION_CONFIRMATION']:
663 otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
664 otk = otk_re.search(self.matches['title'] or '')
665 if otk:
666 self.db.confirm_registration(otk.group('otk'))
667 subject = 'Your registration to %s is complete' % \
668 self.config['TRACKER_NAME']
669 sendto = [self.from_list[0][1]]
670 self.mailgw.mailer.standard_message(sendto, subject, '')
671 return 1
672 return 0
674 def get_classname(self):
675 ''' Determine the classname of the node being created/edited
676 '''
677 subject = self.subject
679 # get the classname
680 if self.pfxmode == 'none':
681 classname = None
682 else:
683 classname = self.matches['classname']
685 if not classname and self.has_prefix and self.pfxmode == 'strict':
686 raise MailUsageError, _("""
687 The message you sent to roundup did not contain a properly formed subject
688 line. The subject must contain a class name or designator to indicate the
689 'topic' of the message. For example:
690 Subject: [issue] This is a new issue
691 - this will create a new issue in the tracker with the title 'This is
692 a new issue'.
693 Subject: [issue1234] This is a followup to issue 1234
694 - this will append the message's contents to the existing issue 1234
695 in the tracker.
697 Subject was: '%(subject)s'
698 """) % locals()
700 # try to get the class specified - if "loose" or "none" then fall
701 # back on the default
702 attempts = []
703 if classname:
704 attempts.append(classname)
706 if self.mailgw.default_class:
707 attempts.append(self.default_class)
708 else:
709 attempts.append(self.config['MAILGW_DEFAULT_CLASS'])
711 # first valid class name wins
712 self.cl = None
713 for trycl in attempts:
714 try:
715 self.cl = self.db.getclass(trycl)
716 classname = self.classname = trycl
717 break
718 except KeyError:
719 pass
721 if not self.cl:
722 validname = ', '.join(self.db.getclasses())
723 if classname:
724 raise MailUsageError, _("""
725 The class name you identified in the subject line ("%(classname)s") does
726 not exist in the database.
728 Valid class names are: %(validname)s
729 Subject was: "%(subject)s"
730 """) % locals()
731 else:
732 raise MailUsageError, _("""
733 You did not identify a class name in the subject line and there is no
734 default set for this tracker. The subject must contain a class name or
735 designator to indicate the 'topic' of the message. For example:
736 Subject: [issue] This is a new issue
737 - this will create a new issue in the tracker with the title 'This is
738 a new issue'.
739 Subject: [issue1234] This is a followup to issue 1234
740 - this will append the message's contents to the existing issue 1234
741 in the tracker.
743 Subject was: '%(subject)s'
744 """) % locals()
745 # get the class properties
746 self.properties = self.cl.getprops()
749 def get_nodeid(self):
750 ''' Determine the nodeid from the message and return it if found
751 '''
752 title = self.matches['title']
753 subject = self.subject
755 if self.pfxmode == 'none':
756 nodeid = None
757 else:
758 nodeid = self.matches['nodeid']
760 # try in-reply-to to match the message if there's no nodeid
761 inreplyto = self.message.getheader('in-reply-to') or ''
762 if nodeid is None and inreplyto:
763 l = self.db.getclass('msg').stringFind(messageid=inreplyto)
764 if l:
765 nodeid = self.cl.filter(None, {'messages':l})[0]
768 # but we do need either a title or a nodeid...
769 if nodeid is None and not title:
770 raise MailUsageError, _("""
771 I cannot match your message to a node in the database - you need to either
772 supply a full designator (with number, eg "[issue123]") or keep the
773 previous subject title intact so I can match that.
775 Subject was: "%(subject)s"
776 """) % locals()
778 # If there's no nodeid, check to see if this is a followup and
779 # maybe someone's responded to the initial mail that created an
780 # entry. Try to find the matching nodes with the same title, and
781 # use the _last_ one matched (since that'll _usually_ be the most
782 # recent...). The subject_content_match config may specify an
783 # additional restriction based on the matched node's creation or
784 # activity.
785 tmatch_mode = self.config['MAILGW_SUBJECT_CONTENT_MATCH']
786 if tmatch_mode != 'never' and nodeid is None and self.matches['refwd']:
787 l = self.cl.stringFind(title=title)
788 limit = None
789 if (tmatch_mode.startswith('creation') or
790 tmatch_mode.startswith('activity')):
791 limit, interval = tmatch_mode.split(' ', 1)
792 threshold = date.Date('.') - date.Interval(interval)
793 for id in l:
794 if limit:
795 if threshold < self.cl.get(id, limit):
796 nodeid = id
797 else:
798 nodeid = id
800 # if a nodeid was specified, make sure it's valid
801 if nodeid is not None and not self.cl.hasnode(nodeid):
802 if self.pfxmode == 'strict':
803 raise MailUsageError, _("""
804 The node specified by the designator in the subject of your message
805 ("%(nodeid)s") does not exist.
807 Subject was: "%(subject)s"
808 """) % locals()
809 else:
810 nodeid = None
811 self.nodeid = nodeid
813 def get_author_id(self):
814 ''' Attempt to get the author id from the existing registered users,
815 otherwise attempt to register a new user and return their id
816 '''
817 # Don't create users if anonymous isn't allowed to register
818 create = 1
819 anonid = self.db.user.lookup('anonymous')
820 if not (self.db.security.hasPermission('Register', anonid, 'user')
821 and self.db.security.hasPermission('Email Access', anonid)):
822 create = 0
824 # ok, now figure out who the author is - create a new user if the
825 # "create" flag is true
826 author = uidFromAddress(self.db, self.from_list[0], create=create)
828 # if we're not recognised, and we don't get added as a user, then we
829 # must be anonymous
830 if not author:
831 author = anonid
833 # make sure the author has permission to use the email interface
834 if not self.db.security.hasPermission('Email Access', author):
835 if author == anonid:
836 # we're anonymous and we need to be a registered user
837 from_address = self.from_list[0][1]
838 registration_info = ""
839 if self.db.security.hasPermission('Web Access', author) and \
840 self.db.security.hasPermission('Register', anonid, 'user'):
841 tracker_web = self.config.TRACKER_WEB
842 registration_info = """ Please register at:
844 %(tracker_web)suser?template=register
846 ...before sending mail to the tracker.""" % locals()
848 raise Unauthorized, _("""
849 You are not a registered user.%(registration_info)s
851 Unknown address: %(from_address)s
852 """) % locals()
853 else:
854 # we're registered and we're _still_ not allowed access
855 raise Unauthorized, _(
856 'You are not permitted to access this tracker.')
857 self.author = author
859 def check_node_permissions(self):
860 ''' Check if the author has permission to edit or create this
861 class of node
862 '''
863 if self.nodeid:
864 if not self.db.security.hasPermission('Edit', self.author,
865 self.classname, itemid=self.nodeid):
866 raise Unauthorized, _(
867 'You are not permitted to edit %(classname)s.'
868 ) % self.__dict__
869 else:
870 if not self.db.security.hasPermission('Create', self.author,
871 self.classname):
872 raise Unauthorized, _(
873 'You are not permitted to create %(classname)s.'
874 ) % self.__dict__
876 def commit_and_reopen_as_author(self):
877 ''' the author may have been created - make sure the change is
878 committed before we reopen the database
879 then re-open the database as the author
880 '''
881 self.db.commit()
883 # set the database user as the author
884 username = self.db.user.get(self.author, 'username')
885 self.db.setCurrentUser(username)
887 # re-get the class with the new database connection
888 self.cl = self.db.getclass(self.classname)
890 def get_recipients(self):
891 ''' Get the list of recipients who were included in message and
892 register them as users if possible
893 '''
894 # Don't create users if anonymous isn't allowed to register
895 create = 1
896 anonid = self.db.user.lookup('anonymous')
897 if not (self.db.security.hasPermission('Register', anonid, 'user')
898 and self.db.security.hasPermission('Email Access', anonid)):
899 create = 0
901 # get the user class arguments from the commandline
902 user_props = self.mailgw.get_class_arguments('user')
904 # now update the recipients list
905 recipients = []
906 tracker_email = self.config['TRACKER_EMAIL'].lower()
907 msg_to = self.message.getaddrlist('to')
908 msg_cc = self.message.getaddrlist('cc')
909 for recipient in msg_to + msg_cc:
910 r = recipient[1].strip().lower()
911 if r == tracker_email or not r:
912 continue
914 # look up the recipient - create if necessary (and we're
915 # allowed to)
916 recipient = uidFromAddress(self.db, recipient, create, **user_props)
918 # if all's well, add the recipient to the list
919 if recipient:
920 recipients.append(recipient)
921 self.recipients = recipients
923 def get_props(self):
924 ''' Generate all the props for the new/updated node and return them
925 '''
926 subject = self.subject
928 # get the commandline arguments for issues
929 issue_props = self.mailgw.get_class_arguments('issue', self.classname)
931 #
932 # handle the subject argument list
933 #
934 # figure what the properties of this Class are
935 props = {}
936 args = self.matches['args']
937 argswhole = self.matches['argswhole']
938 title = self.matches['title']
940 # Reform the title
941 if self.matches['nodeid'] and self.nodeid is None:
942 title = subject
944 if args:
945 if self.sfxmode == 'none':
946 title += ' ' + argswhole
947 else:
948 errors, props = setPropArrayFromString(self, self.cl, args,
949 self.nodeid)
950 # handle any errors parsing the argument list
951 if errors:
952 if self.sfxmode == 'strict':
953 errors = '\n- '.join(map(str, errors))
954 raise MailUsageError, _("""
955 There were problems handling your subject line argument list:
956 - %(errors)s
958 Subject was: "%(subject)s"
959 """) % locals()
960 else:
961 title += ' ' + argswhole
964 # set the issue title to the subject
965 title = title.strip()
966 if (title and self.properties.has_key('title') and not
967 issue_props.has_key('title')):
968 issue_props['title'] = title
969 if (self.nodeid and self.properties.has_key('title') and not
970 self.config['MAILGW_SUBJECT_UPDATES_TITLE']):
971 issue_props['title'] = self.cl.get(self.nodeid,'title')
973 # merge the command line props defined in issue_props into
974 # the props dictionary because function(**props, **issue_props)
975 # is a syntax error.
976 for prop in issue_props.keys() :
977 if not props.has_key(prop) :
978 props[prop] = issue_props[prop]
980 self.props = props
982 def get_pgp_message(self):
983 ''' If they've enabled PGP processing then verify the signature
984 or decrypt the message
985 '''
986 def pgp_role():
987 """ if PGP_ROLES is specified the user must have a Role in the list
988 or we will skip PGP processing
989 """
990 if self.config.PGP_ROLES:
991 return self.db.user.has_role(self.author,
992 iter_roles(self.config.PGP_ROLES))
993 else:
994 return True
996 if self.config.PGP_ENABLE and pgp_role():
997 assert pyme, 'pyme is not installed'
998 # signed/encrypted mail must come from the primary address
999 author_address = self.db.user.get(self.author, 'address')
1000 if self.config.PGP_HOMEDIR:
1001 os.environ['GNUPGHOME'] = self.config.PGP_HOMEDIR
1002 if self.message.pgp_signed():
1003 self.message.verify_signature(author_address)
1004 elif self.message.pgp_encrypted():
1005 # replace message with the contents of the decrypted
1006 # message for content extraction
1007 # TODO: encrypted message handling is far from perfect
1008 # bounces probably include the decrypted message, for
1009 # instance :(
1010 self.message = self.message.decrypt(author_address)
1011 else:
1012 raise MailUsageError, _("""
1013 This tracker has been configured to require all email be PGP signed or
1014 encrypted.""")
1016 def get_content_and_attachments(self):
1017 ''' get the attachments and first text part from the message
1018 '''
1019 ig = self.config.MAILGW_IGNORE_ALTERNATIVES
1020 self.content, self.attachments = self.message.extract_content(
1021 ignore_alternatives=ig,
1022 unpack_rfc822=self.config.MAILGW_UNPACK_RFC822)
1025 def create_files(self):
1026 ''' Create a file for each attachment in the message
1027 '''
1028 if not self.properties.has_key('files'):
1029 return
1030 files = []
1031 file_props = self.mailgw.get_class_arguments('file')
1033 if self.attachments:
1034 for (name, mime_type, data) in self.attachments:
1035 if not self.db.security.hasPermission('Create', self.author,
1036 'file'):
1037 raise Unauthorized, _(
1038 'You are not permitted to create files.')
1039 if not name:
1040 name = "unnamed"
1041 try:
1042 fileid = self.db.file.create(type=mime_type, name=name,
1043 content=data, **file_props)
1044 except exceptions.Reject:
1045 pass
1046 else:
1047 files.append(fileid)
1048 # allowed to attach the files to an existing node?
1049 if self.nodeid and not self.db.security.hasPermission('Edit',
1050 self.author, self.classname, 'files'):
1051 raise Unauthorized, _(
1052 'You are not permitted to add files to %(classname)s.'
1053 ) % self.__dict__
1055 if self.nodeid:
1056 # extend the existing files list
1057 fileprop = self.cl.get(self.nodeid, 'files')
1058 fileprop.extend(files)
1059 files = fileprop
1061 self.props['files'] = files
1063 def create_msg(self):
1064 ''' Create msg containing all the relevant information from the message
1065 '''
1066 if not self.properties.has_key('messages'):
1067 return
1068 msg_props = self.mailgw.get_class_arguments('msg')
1070 # Get the message ids
1071 inreplyto = self.message.getheader('in-reply-to') or ''
1072 messageid = self.message.getheader('message-id')
1073 # generate a messageid if there isn't one
1074 if not messageid:
1075 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1076 self.classname, self.nodeid, self.config['MAIL_DOMAIN'])
1078 if self.content is None:
1079 raise MailUsageError, _("""
1080 Roundup requires the submission to be plain text. The message parser could
1081 not find a text/plain part to use.
1082 """)
1084 # parse the body of the message, stripping out bits as appropriate
1085 summary, content = parseContent(self.content, config=self.config)
1086 content = content.strip()
1088 if content:
1089 if not self.db.security.hasPermission('Create', self.author, 'msg'):
1090 raise Unauthorized, _(
1091 'You are not permitted to create messages.')
1093 try:
1094 message_id = self.db.msg.create(author=self.author,
1095 recipients=self.recipients, date=date.Date('.'),
1096 summary=summary, content=content, files=self.props['files'],
1097 messageid=messageid, inreplyto=inreplyto, **msg_props)
1098 except exceptions.Reject, error:
1099 raise MailUsageError, _("""
1100 Mail message was rejected by a detector.
1101 %(error)s
1102 """) % locals()
1103 # allowed to attach the message to the existing node?
1104 if self.nodeid and not self.db.security.hasPermission('Edit',
1105 self.author, self.classname, 'messages'):
1106 raise Unauthorized, _(
1107 'You are not permitted to add messages to %(classname)s.'
1108 ) % self.__dict__
1110 if self.nodeid:
1111 # add the message to the node's list
1112 messages = self.cl.get(self.nodeid, 'messages')
1113 messages.append(message_id)
1114 self.props['messages'] = messages
1115 else:
1116 # pre-load the messages list
1117 self.props['messages'] = [message_id]
1119 def create_node(self):
1120 ''' Create/update a node using self.props
1121 '''
1122 classname = self.classname
1123 try:
1124 if self.nodeid:
1125 # Check permissions for each property
1126 for prop in self.props.keys():
1127 if not self.db.security.hasPermission('Edit', self.author,
1128 classname, prop):
1129 raise Unauthorized, _('You are not permitted to edit '
1130 'property %(prop)s of class %(classname)s.'
1131 ) % locals()
1132 self.cl.set(self.nodeid, **self.props)
1133 else:
1134 # Check permissions for each property
1135 for prop in self.props.keys():
1136 if not self.db.security.hasPermission('Create', self.author,
1137 classname, prop):
1138 raise Unauthorized, _('You are not permitted to set '
1139 'property %(prop)s of class %(classname)s.'
1140 ) % locals()
1141 self.nodeid = self.cl.create(**self.props)
1142 except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1143 raise MailUsageError, _("""
1144 There was a problem with the message you sent:
1145 %(message)s
1146 """) % locals()
1148 return self.nodeid
1152 class MailGW:
1154 # To override the message parsing, derive your own class from
1155 # parsedMessage and assign to parsed_message_class in a derived
1156 # class of MailGW
1157 parsed_message_class = parsedMessage
1159 def __init__(self, instance, arguments=()):
1160 self.instance = instance
1161 self.arguments = arguments
1162 self.default_class = None
1163 for option, value in self.arguments:
1164 if option == '-c':
1165 self.default_class = value.strip()
1167 self.mailer = Mailer(instance.config)
1168 self.logger = logging.getLogger('roundup.mailgw')
1170 # should we trap exceptions (normal usage) or pass them through
1171 # (for testing)
1172 self.trapExceptions = 1
1174 def do_pipe(self):
1175 """ Read a message from standard input and pass it to the mail handler.
1177 Read into an internal structure that we can seek on (in case
1178 there's an error).
1180 XXX: we may want to read this into a temporary file instead...
1181 """
1182 s = cStringIO.StringIO()
1183 s.write(sys.stdin.read())
1184 s.seek(0)
1185 self.main(s)
1186 return 0
1188 def do_mailbox(self, filename):
1189 """ Read a series of messages from the specified unix mailbox file and
1190 pass each to the mail handler.
1191 """
1192 # open the spool file and lock it
1193 import fcntl
1194 # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
1195 if hasattr(fcntl, 'LOCK_EX'):
1196 FCNTL = fcntl
1197 else:
1198 import FCNTL
1199 f = open(filename, 'r+')
1200 fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
1202 # handle and clear the mailbox
1203 try:
1204 from mailbox import UnixMailbox
1205 mailbox = UnixMailbox(f, factory=Message)
1206 # grab one message
1207 message = mailbox.next()
1208 while message:
1209 # handle this message
1210 self.handle_Message(message)
1211 message = mailbox.next()
1212 # nuke the file contents
1213 os.ftruncate(f.fileno(), 0)
1214 except:
1215 import traceback
1216 traceback.print_exc()
1217 return 1
1218 fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
1219 return 0
1221 def do_imap(self, server, user='', password='', mailbox='', ssl=0,
1222 cram=0):
1223 ''' Do an IMAP connection
1224 '''
1225 import getpass, imaplib, socket
1226 try:
1227 if not user:
1228 user = raw_input('User: ')
1229 if not password:
1230 password = getpass.getpass()
1231 except (KeyboardInterrupt, EOFError):
1232 # Ctrl C or D maybe also Ctrl Z under Windows.
1233 print "\nAborted by user."
1234 return 1
1235 # open a connection to the server and retrieve all messages
1236 try:
1237 if ssl:
1238 self.logger.debug('Trying server %r with ssl'%server)
1239 server = imaplib.IMAP4_SSL(server)
1240 else:
1241 self.logger.debug('Trying server %r without ssl'%server)
1242 server = imaplib.IMAP4(server)
1243 except (imaplib.IMAP4.error, socket.error, socket.sslerror):
1244 self.logger.exception('IMAP server error')
1245 return 1
1247 try:
1248 if cram:
1249 server.login_cram_md5(user, password)
1250 else:
1251 server.login(user, password)
1252 except imaplib.IMAP4.error, e:
1253 self.logger.exception('IMAP login failure')
1254 return 1
1256 try:
1257 if not mailbox:
1258 (typ, data) = server.select()
1259 else:
1260 (typ, data) = server.select(mailbox=mailbox)
1261 if typ != 'OK':
1262 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
1263 data))
1264 return 1
1265 try:
1266 numMessages = int(data[0])
1267 except ValueError, value:
1268 self.logger.error('Invalid message count from mailbox %r'%
1269 data[0])
1270 return 1
1271 for i in range(1, numMessages+1):
1272 (typ, data) = server.fetch(str(i), '(RFC822)')
1274 # mark the message as deleted.
1275 server.store(str(i), '+FLAGS', r'(\Deleted)')
1277 # process the message
1278 s = cStringIO.StringIO(data[0][1])
1279 s.seek(0)
1280 self.handle_Message(Message(s))
1281 server.close()
1282 finally:
1283 try:
1284 server.expunge()
1285 except:
1286 pass
1287 server.logout()
1289 return 0
1292 def do_apop(self, server, user='', password='', ssl=False):
1293 ''' Do authentication POP
1294 '''
1295 self._do_pop(server, user, password, True, ssl)
1297 def do_pop(self, server, user='', password='', ssl=False):
1298 ''' Do plain POP
1299 '''
1300 self._do_pop(server, user, password, False, ssl)
1302 def _do_pop(self, server, user, password, apop, ssl):
1303 '''Read a series of messages from the specified POP server.
1304 '''
1305 import getpass, poplib, socket
1306 try:
1307 if not user:
1308 user = raw_input('User: ')
1309 if not password:
1310 password = getpass.getpass()
1311 except (KeyboardInterrupt, EOFError):
1312 # Ctrl C or D maybe also Ctrl Z under Windows.
1313 print "\nAborted by user."
1314 return 1
1316 # open a connection to the server and retrieve all messages
1317 try:
1318 if ssl:
1319 klass = poplib.POP3_SSL
1320 else:
1321 klass = poplib.POP3
1322 server = klass(server)
1323 except socket.error:
1324 self.logger.exception('POP server error')
1325 return 1
1326 if apop:
1327 server.apop(user, password)
1328 else:
1329 server.user(user)
1330 server.pass_(password)
1331 numMessages = len(server.list()[1])
1332 for i in range(1, numMessages+1):
1333 # retr: returns
1334 # [ pop response e.g. '+OK 459 octets',
1335 # [ array of message lines ],
1336 # number of octets ]
1337 lines = server.retr(i)[1]
1338 s = cStringIO.StringIO('\n'.join(lines))
1339 s.seek(0)
1340 self.handle_Message(Message(s))
1341 # delete the message
1342 server.dele(i)
1344 # quit the server to commit changes.
1345 server.quit()
1346 return 0
1348 def main(self, fp):
1349 ''' fp - the file from which to read the Message.
1350 '''
1351 return self.handle_Message(Message(fp))
1353 def handle_Message(self, message):
1354 """Handle an RFC822 Message
1356 Handle the Message object by calling handle_message() and then cope
1357 with any errors raised by handle_message.
1358 This method's job is to make that call and handle any
1359 errors in a sane manner. It should be replaced if you wish to
1360 handle errors in a different manner.
1361 """
1362 # in some rare cases, a particularly stuffed-up e-mail will make
1363 # its way into here... try to handle it gracefully
1365 sendto = message.getaddrlist('resent-from')
1366 if not sendto:
1367 sendto = message.getaddrlist('from')
1368 if not sendto:
1369 # very bad-looking message - we don't even know who sent it
1370 msg = ['Badly formed message from mail gateway. Headers:']
1371 msg.extend(message.headers)
1372 msg = '\n'.join(map(str, msg))
1373 self.logger.error(msg)
1374 return
1376 msg = 'Handling message'
1377 if message.getheader('message-id'):
1378 msg += ' (Message-id=%r)'%message.getheader('message-id')
1379 self.logger.info(msg)
1381 # try normal message-handling
1382 if not self.trapExceptions:
1383 return self.handle_message(message)
1385 # no, we want to trap exceptions
1386 try:
1387 return self.handle_message(message)
1388 except MailUsageHelp:
1389 # bounce the message back to the sender with the usage message
1390 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1391 m = ['']
1392 m.append('\n\nMail Gateway Help\n=================')
1393 m.append(fulldoc)
1394 self.mailer.bounce_message(message, [sendto[0][1]], m,
1395 subject="Mail Gateway Help")
1396 except MailUsageError, value:
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(str(value))
1401 m.append('\n\nMail Gateway Help\n=================')
1402 m.append(fulldoc)
1403 self.mailer.bounce_message(message, [sendto[0][1]], m)
1404 except Unauthorized, value:
1405 # just inform the user that he is not authorized
1406 m = ['']
1407 m.append(str(value))
1408 self.mailer.bounce_message(message, [sendto[0][1]], m)
1409 except IgnoreMessage:
1410 # do not take any action
1411 # this exception is thrown when email should be ignored
1412 msg = 'IgnoreMessage raised'
1413 if message.getheader('message-id'):
1414 msg += ' (Message-id=%r)'%message.getheader('message-id')
1415 self.logger.info(msg)
1416 return
1417 except:
1418 msg = 'Exception handling message'
1419 if message.getheader('message-id'):
1420 msg += ' (Message-id=%r)'%message.getheader('message-id')
1421 self.logger.exception(msg)
1423 # bounce the message back to the sender with the error message
1424 # let the admin know that something very bad is happening
1425 m = ['']
1426 m.append('An unexpected error occurred during the processing')
1427 m.append('of your message. The tracker administrator is being')
1428 m.append('notified.\n')
1429 self.mailer.bounce_message(message, [sendto[0][1]], m)
1431 m.append('----------------')
1432 m.append(traceback.format_exc())
1433 self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
1435 def handle_message(self, message):
1436 ''' message - a Message instance
1438 Parse the message as per the module docstring.
1439 '''
1440 # get database handle for handling one email
1441 self.db = self.instance.open ('admin')
1442 try:
1443 return self._handle_message(message)
1444 finally:
1445 self.db.close()
1447 def _handle_message(self, message):
1448 ''' message - a Message instance
1450 Parse the message as per the module docstring.
1451 The following code expects an opened database and a try/finally
1452 that closes the database.
1453 '''
1454 parsed_message = self.parsed_message_class(self, message)
1456 # Filter out messages to ignore
1457 parsed_message.handle_ignore()
1459 # Check for usage/help requests
1460 parsed_message.handle_help()
1462 # Check if the subject line is valid
1463 parsed_message.check_subject()
1465 # XXX Don't enable. This doesn't work yet.
1466 # XXX once this works it should be moved to parsedMessage class
1467 # "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
1468 # handle delivery to addresses like:tracker+issue25@some.dom.ain
1469 # use the embedded issue number as our issue
1470 # issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
1471 # if issue_re:
1472 # for header in ['to', 'cc', 'bcc']:
1473 # addresses = message.getheader(header, '')
1474 # if addresses:
1475 # # FIXME, this only finds the first match in the addresses.
1476 # issue = re.search(issue_re, addresses, 'i')
1477 # if issue:
1478 # classname = issue.group('classname')
1479 # nodeid = issue.group('nodeid')
1480 # break
1482 # Parse the subject line to get the importants parts
1483 parsed_message.parse_subject()
1485 # check for registration OTK
1486 if parsed_message.rego_confirm():
1487 return
1489 # get the classname
1490 parsed_message.get_classname()
1492 # get the optional nodeid
1493 parsed_message.get_nodeid()
1495 # Determine who the author is
1496 parsed_message.get_author_id()
1498 # make sure they're allowed to edit or create this class
1499 parsed_message.check_node_permissions()
1501 # author may have been created:
1502 # commit author to database and re-open as author
1503 parsed_message.commit_and_reopen_as_author()
1505 # Get the recipients list
1506 parsed_message.get_recipients()
1508 # get the new/updated node props
1509 parsed_message.get_props()
1511 # Handle PGP signed or encrypted messages
1512 parsed_message.get_pgp_message()
1514 # extract content and attachments from message body
1515 parsed_message.get_content_and_attachments()
1517 # put attachments into files linked to the issue
1518 parsed_message.create_files()
1520 # create the message if there's a message body (content)
1521 parsed_message.create_msg()
1523 # perform the node change / create
1524 nodeid = parsed_message.create_node()
1526 # commit the changes to the DB
1527 self.db.commit()
1529 return nodeid
1531 def get_class_arguments(self, class_type, classname=None):
1532 ''' class_type - a valid node class type:
1533 - 'user' refers to the author of a message
1534 - 'issue' refers to an issue-type class (to which the
1535 message is appended) specified in parameter classname
1536 Note that this need not be the real classname, we get
1537 the real classname used as a parameter (from previous
1538 message-parsing steps)
1539 - 'file' specifies a file-type class
1540 - 'msg' is the message-class
1541 classname - the name of the current issue-type class
1543 Parse the commandline arguments and retrieve the properties that
1544 are relevant to the class_type. We now allow multiple -S options
1545 per class_type (-C option).
1546 '''
1547 allprops = {}
1549 classname = classname or class_type
1550 cls_lookup = { 'issue' : classname }
1552 # Allow other issue-type classes -- take the real classname from
1553 # previous parsing-steps of the message:
1554 clsname = cls_lookup.get (class_type, class_type)
1556 # check if the clsname is valid
1557 try:
1558 self.db.getclass(clsname)
1559 except KeyError:
1560 mailadmin = self.instance.config['ADMIN_EMAIL']
1561 raise MailUsageError, _("""
1562 The mail gateway is not properly set up. Please contact
1563 %(mailadmin)s and have them fix the incorrect class specified as:
1564 %(clsname)s
1565 """) % locals()
1567 if self.arguments:
1568 # The default type on the commandline is msg
1569 if class_type == 'msg':
1570 current_type = class_type
1571 else:
1572 current_type = None
1574 # Handle the arguments specified by the email gateway command line.
1575 # We do this by looping over the list of self.arguments looking for
1576 # a -C to match the class we want, then use the -S setting string.
1577 for option, propstring in self.arguments:
1578 if option in ( '-C', '--class'):
1579 current_type = propstring.strip()
1581 if current_type != class_type:
1582 current_type = None
1584 elif current_type and option in ('-S', '--set'):
1585 cls = cls_lookup.get (current_type, current_type)
1586 temp_cl = self.db.getclass(cls)
1587 errors, props = setPropArrayFromString(self,
1588 temp_cl, propstring.strip())
1590 if errors:
1591 mailadmin = self.instance.config['ADMIN_EMAIL']
1592 raise MailUsageError, _("""
1593 The mail gateway is not properly set up. Please contact
1594 %(mailadmin)s and have them fix the incorrect properties:
1595 %(errors)s
1596 """) % locals()
1597 allprops.update(props)
1599 return allprops
1602 def setPropArrayFromString(self, cl, propString, nodeid=None):
1603 ''' takes string of form prop=value,value;prop2=value
1604 and returns (error, prop[..])
1605 '''
1606 props = {}
1607 errors = []
1608 for prop in string.split(propString, ';'):
1609 # extract the property name and value
1610 try:
1611 propname, value = prop.split('=')
1612 except ValueError, message:
1613 errors.append(_('not of form [arg=value,value,...;'
1614 'arg=value,value,...]'))
1615 return (errors, props)
1616 # convert the value to a hyperdb-usable value
1617 propname = propname.strip()
1618 try:
1619 props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1620 propname, value)
1621 except hyperdb.HyperdbValueError, message:
1622 errors.append(str(message))
1623 return errors, props
1626 def extractUserFromList(userClass, users):
1627 '''Given a list of users, try to extract the first non-anonymous user
1628 and return that user, otherwise return None
1629 '''
1630 if len(users) > 1:
1631 for user in users:
1632 # make sure we don't match the anonymous or admin user
1633 if userClass.get(user, 'username') in ('admin', 'anonymous'):
1634 continue
1635 # first valid match will do
1636 return user
1637 # well, I guess we have no choice
1638 return user[0]
1639 elif users:
1640 return users[0]
1641 return None
1644 def uidFromAddress(db, address, create=1, **user_props):
1645 ''' address is from the rfc822 module, and therefore is (name, addr)
1647 user is created if they don't exist in the db already
1648 user_props may supply additional user information
1649 '''
1650 (realname, address) = address
1652 # try a straight match of the address
1653 user = extractUserFromList(db.user, db.user.stringFind(address=address))
1654 if user is not None:
1655 return user
1657 # try the user alternate addresses if possible
1658 props = db.user.getprops()
1659 if props.has_key('alternate_addresses'):
1660 users = db.user.filter(None, {'alternate_addresses': address})
1661 user = extractUserFromList(db.user, users)
1662 if user is not None:
1663 return user
1665 # try to match the username to the address (for local
1666 # submissions where the address is empty)
1667 user = extractUserFromList(db.user, db.user.stringFind(username=address))
1669 # couldn't match address or username, so create a new user
1670 if create:
1671 # generate a username
1672 if '@' in address:
1673 username = address.split('@')[0]
1674 else:
1675 username = address
1676 trying = username
1677 n = 0
1678 while 1:
1679 try:
1680 # does this username exist already?
1681 db.user.lookup(trying)
1682 except KeyError:
1683 break
1684 n += 1
1685 trying = username + str(n)
1687 # create!
1688 try:
1689 return db.user.create(username=trying, address=address,
1690 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1691 password=password.Password(password.generatePassword()),
1692 **user_props)
1693 except exceptions.Reject:
1694 return 0
1695 else:
1696 return 0
1698 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1699 """Parse mail message; return message summary and stripped content
1701 The message body is divided into sections by blank lines.
1702 Sections where the second and all subsequent lines begin with a ">"
1703 or "|" character are considered "quoting sections". The first line of
1704 the first non-quoting section becomes the summary of the message.
1706 Arguments:
1708 keep_citations: declared for backward compatibility.
1709 If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1711 keep_body: declared for backward compatibility.
1712 If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1714 config: tracker configuration object.
1715 If omitted or None, use default configuration.
1717 """
1718 if config is None:
1719 config = configuration.CoreConfig()
1720 if keep_citations is None:
1721 keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1722 if keep_body is None:
1723 keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1724 eol = config["MAILGW_EOL_RE"]
1725 signature = config["MAILGW_SIGN_RE"]
1726 original_msg = config["MAILGW_ORIGMSG_RE"]
1728 # strip off leading carriage-returns / newlines
1729 i = 0
1730 for i in range(len(content)):
1731 if content[i] not in '\r\n':
1732 break
1733 if i > 0:
1734 sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1735 else:
1736 sections = config["MAILGW_BLANKLINE_RE"].split(content)
1738 # extract out the summary from the message
1739 summary = ''
1740 l = []
1741 for section in sections:
1742 #section = section.strip()
1743 if not section:
1744 continue
1745 lines = eol.split(section)
1746 if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1747 lines[1] and lines[1][0] in '>|'):
1748 # see if there's a response somewhere inside this section (ie.
1749 # no blank line between quoted message and response)
1750 for line in lines[1:]:
1751 if line and line[0] not in '>|':
1752 break
1753 else:
1754 # we keep quoted bits if specified in the config
1755 if keep_citations:
1756 l.append(section)
1757 continue
1758 # keep this section - it has reponse stuff in it
1759 lines = lines[lines.index(line):]
1760 section = '\n'.join(lines)
1761 # and while we're at it, use the first non-quoted bit as
1762 # our summary
1763 summary = section
1765 if not summary:
1766 # if we don't have our summary yet use the first line of this
1767 # section
1768 summary = section
1769 elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1770 # lose any signature
1771 break
1772 elif original_msg.match(lines[0]):
1773 # ditch the stupid Outlook quoting of the entire original message
1774 break
1776 # and add the section to the output
1777 l.append(section)
1779 # figure the summary - find the first sentence-ending punctuation or the
1780 # first whole line, whichever is longest
1781 sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1782 if sentence:
1783 sentence = sentence.group(1)
1784 else:
1785 sentence = ''
1786 first = eol.split(summary)[0]
1787 summary = max(sentence, first)
1789 # Now reconstitute the message content minus the bits we don't care
1790 # about.
1791 if not keep_body:
1792 content = '\n\n'.join(l)
1794 return summary, content
1796 # vim: set filetype=python sts=4 sw=4 et si :