Code

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