Code

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