Code

Yet another fix to the mail gateway, messages got *all* files of
[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.msg_props = {}
553         self.props = None
554         self.content = None
555         self.attachments = None
557     def handle_ignore(self):
558         ''' Check to see if message can be safely ignored:
559             detect loops and
560             Precedence: Bulk, or Microsoft Outlook autoreplies
561         '''
562         if self.message.getheader('x-roundup-loop', ''):
563             raise IgnoreLoop
564         if (self.message.getheader('precedence', '') == 'bulk'
565                 or self.subject.lower().find("autoreply") > 0):
566             raise IgnoreBulk
568     def handle_help(self):
569         ''' Check to see if the message contains a usage/help request
570         '''
571         if self.subject.strip().lower() == 'help':
572             raise MailUsageHelp
574     def check_subject(self):
575         ''' Check to see if the message contains a valid subject line
576         '''
577         if not self.subject:
578             raise MailUsageError, _("""
579 Emails to Roundup trackers must include a Subject: line!
580 """)
582     def parse_subject(self):
583         ''' Matches subjects like:
584         Re: "[issue1234] title of issue [status=resolved]"
585         
586         Each part of the subject is matched, stored, then removed from the
587         start of the subject string as needed. The stored values are then
588         returned
589         '''
591         tmpsubject = self.subject
593         sd_open, sd_close = self.config['MAILGW_SUBJECT_SUFFIX_DELIMITERS']
594         delim_open = re.escape(sd_open)
595         if delim_open in '[(': delim_open = '\\' + delim_open
596         delim_close = re.escape(sd_close)
597         if delim_close in '[(': delim_close = '\\' + delim_close
599         # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH
600         re_re = r"(?P<refwd>%s)\s*" % self.config["MAILGW_REFWD_RE"].pattern
601         m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE)
602         if m:
603             m = m.groupdict()
604             if m['refwd']:
605                 self.matches.update(m)
606                 tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re:
608         # Look for Leading "
609         m = re.match(r'(?P<quote>\s*")', tmpsubject,
610                      re.IGNORECASE)
611         if m:
612             self.matches.update(m.groupdict())
613             tmpsubject = tmpsubject[len(self.matches['quote']):] # Consume quote
615         # Check if the subject includes a prefix
616         self.has_prefix = re.search(r'^%s(\w+)%s'%(delim_open,
617             delim_close), tmpsubject.strip())
619         # Match the classname if specified
620         class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open,
621             "|".join(self.db.getclasses()), delim_close)
622         # Note: re.search, not re.match as there might be garbage
623         # (mailing list prefix, etc.) before the class identifier
624         m = re.search(class_re, tmpsubject, re.IGNORECASE)
625         if m:
626             self.matches.update(m.groupdict())
627             # Skip to the end of the class identifier, including any
628             # garbage before it.
630             tmpsubject = tmpsubject[m.end():]
632         # Match the title of the subject
633         # if we've not found a valid classname prefix then force the
634         # scanning to handle there being a leading delimiter
635         title_re = r'(?P<title>%s[^%s]*)'%(
636             not self.matches['classname'] and '.' or '', delim_open)
637         m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE)
638         if m:
639             self.matches.update(m.groupdict())
640             tmpsubject = tmpsubject[len(self.matches['title']):] # Consume title
642         if self.matches['title']:
643             self.matches['title'] = self.matches['title'].strip()
644         else:
645             self.matches['title'] = ''
647         # strip off the quotes that dumb emailers put around the subject, like
648         #      Re: "[issue1] bla blah"
649         if self.matches['quote'] and self.matches['title'].endswith('"'):
650             self.matches['title'] = self.matches['title'][:-1]
651         
652         # Match any arguments specified
653         args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open,
654             delim_close)
655         m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE)
656         if m:
657             self.matches.update(m.groupdict())
659     def rego_confirm(self):
660         ''' Check for registration OTK and confirm the registration if found
661         '''
662         
663         if self.config['EMAIL_REGISTRATION_CONFIRMATION']:
664             otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})')
665             otk = otk_re.search(self.matches['title'] or '')
666             if otk:
667                 self.db.confirm_registration(otk.group('otk'))
668                 subject = 'Your registration to %s is complete' % \
669                           self.config['TRACKER_NAME']
670                 sendto = [self.from_list[0][1]]
671                 self.mailgw.mailer.standard_message(sendto, subject, '')
672                 return 1
673         return 0
675     def get_classname(self):
676         ''' Determine the classname of the node being created/edited
677         '''
678         subject = self.subject
680         # get the classname
681         if self.pfxmode == 'none':
682             classname = None
683         else:
684             classname = self.matches['classname']
686         if not classname and self.has_prefix and self.pfxmode == 'strict':
687             raise MailUsageError, _("""
688 The message you sent to roundup did not contain a properly formed subject
689 line. The subject must contain a class name or designator to indicate the
690 'topic' of the message. For example:
691     Subject: [issue] This is a new issue
692       - this will create a new issue in the tracker with the title 'This is
693         a new issue'.
694     Subject: [issue1234] This is a followup to issue 1234
695       - this will append the message's contents to the existing issue 1234
696         in the tracker.
698 Subject was: '%(subject)s'
699 """) % locals()
701         # try to get the class specified - if "loose" or "none" then fall
702         # back on the default
703         attempts = []
704         if classname:
705             attempts.append(classname)
707         if self.mailgw.default_class:
708             attempts.append(self.mailgw.default_class)
709         else:
710             attempts.append(self.config['MAILGW_DEFAULT_CLASS'])
712         # first valid class name wins
713         self.cl = None
714         for trycl in attempts:
715             try:
716                 self.cl = self.db.getclass(trycl)
717                 classname = self.classname = trycl
718                 break
719             except KeyError:
720                 pass
722         if not self.cl:
723             validname = ', '.join(self.db.getclasses())
724             if classname:
725                 raise MailUsageError, _("""
726 The class name you identified in the subject line ("%(classname)s") does
727 not exist in the database.
729 Valid class names are: %(validname)s
730 Subject was: "%(subject)s"
731 """) % locals()
732             else:
733                 raise MailUsageError, _("""
734 You did not identify a class name in the subject line and there is no
735 default set for this tracker. The subject must contain a class name or
736 designator to indicate the 'topic' of the message. For example:
737     Subject: [issue] This is a new issue
738       - this will create a new issue in the tracker with the title 'This is
739         a new issue'.
740     Subject: [issue1234] This is a followup to issue 1234
741       - this will append the message's contents to the existing issue 1234
742         in the tracker.
744 Subject was: '%(subject)s'
745 """) % locals()
746         # get the class properties
747         self.properties = self.cl.getprops()
748         
750     def get_nodeid(self):
751         ''' Determine the nodeid from the message and return it if found
752         '''
753         title = self.matches['title']
754         subject = self.subject
755         
756         if self.pfxmode == 'none':
757             nodeid = None
758         else:
759             nodeid = self.matches['nodeid']
761         # try in-reply-to to match the message if there's no nodeid
762         inreplyto = self.message.getheader('in-reply-to') or ''
763         if nodeid is None and inreplyto:
764             l = self.db.getclass('msg').stringFind(messageid=inreplyto)
765             if l:
766                 nodeid = self.cl.filter(None, {'messages':l})[0]
769         # but we do need either a title or a nodeid...
770         if nodeid is None and not title:
771             raise MailUsageError, _("""
772 I cannot match your message to a node in the database - you need to either
773 supply a full designator (with number, eg "[issue123]") or keep the
774 previous subject title intact so I can match that.
776 Subject was: "%(subject)s"
777 """) % locals()
779         # If there's no nodeid, check to see if this is a followup and
780         # maybe someone's responded to the initial mail that created an
781         # entry. Try to find the matching nodes with the same title, and
782         # use the _last_ one matched (since that'll _usually_ be the most
783         # recent...). The subject_content_match config may specify an
784         # additional restriction based on the matched node's creation or
785         # activity.
786         tmatch_mode = self.config['MAILGW_SUBJECT_CONTENT_MATCH']
787         if tmatch_mode != 'never' and nodeid is None and self.matches['refwd']:
788             l = self.cl.stringFind(title=title)
789             limit = None
790             if (tmatch_mode.startswith('creation') or
791                     tmatch_mode.startswith('activity')):
792                 limit, interval = tmatch_mode.split(' ', 1)
793                 threshold = date.Date('.') - date.Interval(interval)
794             for id in l:
795                 if limit:
796                     if threshold < self.cl.get(id, limit):
797                         nodeid = id
798                 else:
799                     nodeid = id
801         # if a nodeid was specified, make sure it's valid
802         if nodeid is not None and not self.cl.hasnode(nodeid):
803             if self.pfxmode == 'strict':
804                 raise MailUsageError, _("""
805 The node specified by the designator in the subject of your message
806 ("%(nodeid)s") does not exist.
808 Subject was: "%(subject)s"
809 """) % locals()
810             else:
811                 nodeid = None
812         self.nodeid = nodeid
814     def get_author_id(self):
815         ''' Attempt to get the author id from the existing registered users,
816             otherwise attempt to register a new user and return their id
817         '''
818         # Don't create users if anonymous isn't allowed to register
819         create = 1
820         anonid = self.db.user.lookup('anonymous')
821         if not (self.db.security.hasPermission('Register', anonid, 'user')
822                 and self.db.security.hasPermission('Email Access', anonid)):
823             create = 0
825         # ok, now figure out who the author is - create a new user if the
826         # "create" flag is true
827         author = uidFromAddress(self.db, self.from_list[0], create=create)
829         # if we're not recognised, and we don't get added as a user, then we
830         # must be anonymous
831         if not author:
832             author = anonid
834         # make sure the author has permission to use the email interface
835         if not self.db.security.hasPermission('Email Access', author):
836             if author == anonid:
837                 # we're anonymous and we need to be a registered user
838                 from_address = self.from_list[0][1]
839                 registration_info = ""
840                 if self.db.security.hasPermission('Web Access', author) and \
841                    self.db.security.hasPermission('Register', anonid, 'user'):
842                     tracker_web = self.config.TRACKER_WEB
843                     registration_info = """ Please register at:
845 %(tracker_web)suser?template=register
847 ...before sending mail to the tracker.""" % locals()
849                 raise Unauthorized, _("""
850 You are not a registered user.%(registration_info)s
852 Unknown address: %(from_address)s
853 """) % locals()
854             else:
855                 # we're registered and we're _still_ not allowed access
856                 raise Unauthorized, _(
857                     'You are not permitted to access this tracker.')
858         self.author = author
860     def check_node_permissions(self):
861         ''' Check if the author has permission to edit or create this
862             class of node
863         '''
864         if self.nodeid:
865             if not self.db.security.hasPermission('Edit', self.author,
866                     self.classname, itemid=self.nodeid):
867                 raise Unauthorized, _(
868                     'You are not permitted to edit %(classname)s.'
869                     ) % self.__dict__
870         else:
871             if not self.db.security.hasPermission('Create', self.author,
872                     self.classname):
873                 raise Unauthorized, _(
874                     'You are not permitted to create %(classname)s.'
875                     ) % self.__dict__
877     def commit_and_reopen_as_author(self):
878         ''' the author may have been created - make sure the change is
879             committed before we reopen the database
880             then re-open the database as the author
881         '''
882         self.db.commit()
884         # set the database user as the author
885         username = self.db.user.get(self.author, 'username')
886         self.db.setCurrentUser(username)
888         # re-get the class with the new database connection
889         self.cl = self.db.getclass(self.classname)
891     def get_recipients(self):
892         ''' Get the list of recipients who were included in message and
893             register them as users if possible
894         '''
895         # Don't create users if anonymous isn't allowed to register
896         create = 1
897         anonid = self.db.user.lookup('anonymous')
898         if not (self.db.security.hasPermission('Register', anonid, 'user')
899                 and self.db.security.hasPermission('Email Access', anonid)):
900             create = 0
902         # get the user class arguments from the commandline
903         user_props = self.mailgw.get_class_arguments('user')
905         # now update the recipients list
906         recipients = []
907         tracker_email = self.config['TRACKER_EMAIL'].lower()
908         msg_to = self.message.getaddrlist('to')
909         msg_cc = self.message.getaddrlist('cc')
910         for recipient in msg_to + msg_cc:
911             r = recipient[1].strip().lower()
912             if r == tracker_email or not r:
913                 continue
915             # look up the recipient - create if necessary (and we're
916             # allowed to)
917             recipient = uidFromAddress(self.db, recipient, create, **user_props)
919             # if all's well, add the recipient to the list
920             if recipient:
921                 recipients.append(recipient)
922         self.recipients = recipients
924     def get_props(self):
925         ''' Generate all the props for the new/updated node and return them
926         '''
927         subject = self.subject
928         
929         # get the commandline arguments for issues
930         issue_props = self.mailgw.get_class_arguments('issue', self.classname)
931         
932         #
933         # handle the subject argument list
934         #
935         # figure what the properties of this Class are
936         props = {}
937         args = self.matches['args']
938         argswhole = self.matches['argswhole']
939         title = self.matches['title']
940         
941         # Reform the title 
942         if self.matches['nodeid'] and self.nodeid is None:
943             title = subject
944         
945         if args:
946             if self.sfxmode == 'none':
947                 title += ' ' + argswhole
948             else:
949                 errors, props = setPropArrayFromString(self, self.cl, args,
950                     self.nodeid)
951                 # handle any errors parsing the argument list
952                 if errors:
953                     if self.sfxmode == 'strict':
954                         errors = '\n- '.join(map(str, errors))
955                         raise MailUsageError, _("""
956 There were problems handling your subject line argument list:
957 - %(errors)s
959 Subject was: "%(subject)s"
960 """) % locals()
961                     else:
962                         title += ' ' + argswhole
965         # set the issue title to the subject
966         title = title.strip()
967         if (title and self.properties.has_key('title') and not
968                 issue_props.has_key('title')):
969             issue_props['title'] = title
970         if (self.nodeid and self.properties.has_key('title') and not
971                 self.config['MAILGW_SUBJECT_UPDATES_TITLE']):
972             issue_props['title'] = self.cl.get(self.nodeid,'title')
974         # merge the command line props defined in issue_props into
975         # the props dictionary because function(**props, **issue_props)
976         # is a syntax error.
977         for prop in issue_props.keys() :
978             if not props.has_key(prop) :
979                 props[prop] = issue_props[prop]
981         self.props = props
983     def get_pgp_message(self):
984         ''' If they've enabled PGP processing then verify the signature
985             or decrypt the message
986         '''
987         def pgp_role():
988             """ if PGP_ROLES is specified the user must have a Role in the list
989                 or we will skip PGP processing
990             """
991             if self.config.PGP_ROLES:
992                 return self.db.user.has_role(self.author,
993                     iter_roles(self.config.PGP_ROLES))
994             else:
995                 return True
997         if self.config.PGP_ENABLE and pgp_role():
998             assert pyme, 'pyme is not installed'
999             # signed/encrypted mail must come from the primary address
1000             author_address = self.db.user.get(self.author, 'address')
1001             if self.config.PGP_HOMEDIR:
1002                 os.environ['GNUPGHOME'] = self.config.PGP_HOMEDIR
1003             if self.message.pgp_signed():
1004                 self.message.verify_signature(author_address)
1005             elif self.message.pgp_encrypted():
1006                 # replace message with the contents of the decrypted
1007                 # message for content extraction
1008                 # TODO: encrypted message handling is far from perfect
1009                 # bounces probably include the decrypted message, for
1010                 # instance :(
1011                 self.message = self.message.decrypt(author_address)
1012             else:
1013                 raise MailUsageError, _("""
1014 This tracker has been configured to require all email be PGP signed or
1015 encrypted.""")
1017     def get_content_and_attachments(self):
1018         ''' get the attachments and first text part from the message
1019         '''
1020         ig = self.config.MAILGW_IGNORE_ALTERNATIVES
1021         self.content, self.attachments = self.message.extract_content(
1022             ignore_alternatives=ig,
1023             unpack_rfc822=self.config.MAILGW_UNPACK_RFC822)
1024         
1026     def create_files(self):
1027         ''' Create a file for each attachment in the message
1028         '''
1029         if not self.properties.has_key('files'):
1030             return
1031         files = []
1032         file_props = self.mailgw.get_class_arguments('file')
1033         
1034         if self.attachments:
1035             for (name, mime_type, data) in self.attachments:
1036                 if not self.db.security.hasPermission('Create', self.author,
1037                     'file'):
1038                     raise Unauthorized, _(
1039                         'You are not permitted to create files.')
1040                 if not name:
1041                     name = "unnamed"
1042                 try:
1043                     fileid = self.db.file.create(type=mime_type, name=name,
1044                          content=data, **file_props)
1045                 except exceptions.Reject:
1046                     pass
1047                 else:
1048                     files.append(fileid)
1049             # allowed to attach the files to an existing node?
1050             if self.nodeid and not self.db.security.hasPermission('Edit',
1051                     self.author, self.classname, 'files'):
1052                 raise Unauthorized, _(
1053                     'You are not permitted to add files to %(classname)s.'
1054                     ) % self.__dict__
1056             self.msg_props['files'] = files
1057             if self.nodeid:
1058                 # extend the existing files list
1059                 fileprop = self.cl.get(self.nodeid, 'files')
1060                 fileprop.extend(files)
1061                 files = fileprop
1063             self.props['files'] = files
1065     def create_msg(self):
1066         ''' Create msg containing all the relevant information from the message
1067         '''
1068         if not self.properties.has_key('messages'):
1069             return
1070         msg_props = self.mailgw.get_class_arguments('msg')
1071         self.msg_props.update (msg_props)
1072         
1073         # Get the message ids
1074         inreplyto = self.message.getheader('in-reply-to') or ''
1075         messageid = self.message.getheader('message-id')
1076         # generate a messageid if there isn't one
1077         if not messageid:
1078             messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
1079                 self.classname, self.nodeid, self.config['MAIL_DOMAIN'])
1080         
1081         if self.content is None:
1082             raise MailUsageError, _("""
1083 Roundup requires the submission to be plain text. The message parser could
1084 not find a text/plain part to use.
1085 """)
1087         # parse the body of the message, stripping out bits as appropriate
1088         summary, content = parseContent(self.content, config=self.config)
1089         content = content.strip()
1091         if content:
1092             if not self.db.security.hasPermission('Create', self.author, 'msg'):
1093                 raise Unauthorized, _(
1094                     'You are not permitted to create messages.')
1096             try:
1097                 message_id = self.db.msg.create(author=self.author,
1098                     recipients=self.recipients, date=date.Date('.'),
1099                     summary=summary, content=content,
1100                     messageid=messageid, inreplyto=inreplyto, **self.msg_props)
1101             except exceptions.Reject, error:
1102                 raise MailUsageError, _("""
1103 Mail message was rejected by a detector.
1104 %(error)s
1105 """) % locals()
1106             # allowed to attach the message to the existing node?
1107             if self.nodeid and not self.db.security.hasPermission('Edit',
1108                     self.author, self.classname, 'messages'):
1109                 raise Unauthorized, _(
1110                     'You are not permitted to add messages to %(classname)s.'
1111                     ) % self.__dict__
1113             if self.nodeid:
1114                 # add the message to the node's list
1115                 messages = self.cl.get(self.nodeid, 'messages')
1116                 messages.append(message_id)
1117                 self.props['messages'] = messages
1118             else:
1119                 # pre-load the messages list
1120                 self.props['messages'] = [message_id]
1122     def create_node(self):
1123         ''' Create/update a node using self.props 
1124         '''
1125         classname = self.classname
1126         try:
1127             if self.nodeid:
1128                 # Check permissions for each property
1129                 for prop in self.props.keys():
1130                     if not self.db.security.hasPermission('Edit', self.author,
1131                             classname, prop):
1132                         raise Unauthorized, _('You are not permitted to edit '
1133                             'property %(prop)s of class %(classname)s.'
1134                             ) % locals()
1135                 self.cl.set(self.nodeid, **self.props)
1136             else:
1137                 # Check permissions for each property
1138                 for prop in self.props.keys():
1139                     if not self.db.security.hasPermission('Create', self.author,
1140                             classname, prop):
1141                         raise Unauthorized, _('You are not permitted to set '
1142                             'property %(prop)s of class %(classname)s.'
1143                             ) % locals()
1144                 self.nodeid = self.cl.create(**self.props)
1145         except (TypeError, IndexError, ValueError, exceptions.Reject), message:
1146             raise MailUsageError, _("""
1147 There was a problem with the message you sent:
1148    %(message)s
1149 """) % locals()
1151         return self.nodeid
1155 class MailGW:
1157     # To override the message parsing, derive your own class from
1158     # parsedMessage and assign to parsed_message_class in a derived
1159     # class of MailGW
1160     parsed_message_class = parsedMessage
1162     def __init__(self, instance, arguments=()):
1163         self.instance = instance
1164         self.arguments = arguments
1165         self.default_class = None
1166         for option, value in self.arguments:
1167             if option == '-c':
1168                 self.default_class = value.strip()
1170         self.mailer = Mailer(instance.config)
1171         self.logger = logging.getLogger('roundup.mailgw')
1173         # should we trap exceptions (normal usage) or pass them through
1174         # (for testing)
1175         self.trapExceptions = 1
1177     def do_pipe(self):
1178         """ Read a message from standard input and pass it to the mail handler.
1180             Read into an internal structure that we can seek on (in case
1181             there's an error).
1183             XXX: we may want to read this into a temporary file instead...
1184         """
1185         s = cStringIO.StringIO()
1186         s.write(sys.stdin.read())
1187         s.seek(0)
1188         self.main(s)
1189         return 0
1191     def do_mailbox(self, filename):
1192         """ Read a series of messages from the specified unix mailbox file and
1193             pass each to the mail handler.
1194         """
1195         # open the spool file and lock it
1196         import fcntl
1197         # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols
1198         if hasattr(fcntl, 'LOCK_EX'):
1199             FCNTL = fcntl
1200         else:
1201             import FCNTL
1202         f = open(filename, 'r+')
1203         fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
1205         # handle and clear the mailbox
1206         try:
1207             from mailbox import UnixMailbox
1208             mailbox = UnixMailbox(f, factory=Message)
1209             # grab one message
1210             message = mailbox.next()
1211             while message:
1212                 # handle this message
1213                 self.handle_Message(message)
1214                 message = mailbox.next()
1215             # nuke the file contents
1216             os.ftruncate(f.fileno(), 0)
1217         except:
1218             import traceback
1219             traceback.print_exc()
1220             return 1
1221         fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
1222         return 0
1224     def do_imap(self, server, user='', password='', mailbox='', ssl=0,
1225             cram=0):
1226         ''' Do an IMAP connection
1227         '''
1228         import getpass, imaplib, socket
1229         try:
1230             if not user:
1231                 user = raw_input('User: ')
1232             if not password:
1233                 password = getpass.getpass()
1234         except (KeyboardInterrupt, EOFError):
1235             # Ctrl C or D maybe also Ctrl Z under Windows.
1236             print "\nAborted by user."
1237             return 1
1238         # open a connection to the server and retrieve all messages
1239         try:
1240             if ssl:
1241                 self.logger.debug('Trying server %r with ssl'%server)
1242                 server = imaplib.IMAP4_SSL(server)
1243             else:
1244                 self.logger.debug('Trying server %r without ssl'%server)
1245                 server = imaplib.IMAP4(server)
1246         except (imaplib.IMAP4.error, socket.error, socket.sslerror):
1247             self.logger.exception('IMAP server error')
1248             return 1
1250         try:
1251             if cram:
1252                 server.login_cram_md5(user, password)
1253             else:
1254                 server.login(user, password)
1255         except imaplib.IMAP4.error, e:
1256             self.logger.exception('IMAP login failure')
1257             return 1
1259         try:
1260             if not mailbox:
1261                 (typ, data) = server.select()
1262             else:
1263                 (typ, data) = server.select(mailbox=mailbox)
1264             if typ != 'OK':
1265                 self.logger.error('Failed to get mailbox %r: %s'%(mailbox,
1266                     data))
1267                 return 1
1268             try:
1269                 numMessages = int(data[0])
1270             except ValueError, value:
1271                 self.logger.error('Invalid message count from mailbox %r'%
1272                     data[0])
1273                 return 1
1274             for i in range(1, numMessages+1):
1275                 (typ, data) = server.fetch(str(i), '(RFC822)')
1277                 # mark the message as deleted.
1278                 server.store(str(i), '+FLAGS', r'(\Deleted)')
1280                 # process the message
1281                 s = cStringIO.StringIO(data[0][1])
1282                 s.seek(0)
1283                 self.handle_Message(Message(s))
1284             server.close()
1285         finally:
1286             try:
1287                 server.expunge()
1288             except:
1289                 pass
1290             server.logout()
1292         return 0
1295     def do_apop(self, server, user='', password='', ssl=False):
1296         ''' Do authentication POP
1297         '''
1298         self._do_pop(server, user, password, True, ssl)
1300     def do_pop(self, server, user='', password='', ssl=False):
1301         ''' Do plain POP
1302         '''
1303         self._do_pop(server, user, password, False, ssl)
1305     def _do_pop(self, server, user, password, apop, ssl):
1306         '''Read a series of messages from the specified POP server.
1307         '''
1308         import getpass, poplib, socket
1309         try:
1310             if not user:
1311                 user = raw_input('User: ')
1312             if not password:
1313                 password = getpass.getpass()
1314         except (KeyboardInterrupt, EOFError):
1315             # Ctrl C or D maybe also Ctrl Z under Windows.
1316             print "\nAborted by user."
1317             return 1
1319         # open a connection to the server and retrieve all messages
1320         try:
1321             if ssl:
1322                 klass = poplib.POP3_SSL
1323             else:
1324                 klass = poplib.POP3
1325             server = klass(server)
1326         except socket.error:
1327             self.logger.exception('POP server error')
1328             return 1
1329         if apop:
1330             server.apop(user, password)
1331         else:
1332             server.user(user)
1333             server.pass_(password)
1334         numMessages = len(server.list()[1])
1335         for i in range(1, numMessages+1):
1336             # retr: returns
1337             # [ pop response e.g. '+OK 459 octets',
1338             #   [ array of message lines ],
1339             #   number of octets ]
1340             lines = server.retr(i)[1]
1341             s = cStringIO.StringIO('\n'.join(lines))
1342             s.seek(0)
1343             self.handle_Message(Message(s))
1344             # delete the message
1345             server.dele(i)
1347         # quit the server to commit changes.
1348         server.quit()
1349         return 0
1351     def main(self, fp):
1352         ''' fp - the file from which to read the Message.
1353         '''
1354         return self.handle_Message(Message(fp))
1356     def handle_Message(self, message):
1357         """Handle an RFC822 Message
1359         Handle the Message object by calling handle_message() and then cope
1360         with any errors raised by handle_message.
1361         This method's job is to make that call and handle any
1362         errors in a sane manner. It should be replaced if you wish to
1363         handle errors in a different manner.
1364         """
1365         # in some rare cases, a particularly stuffed-up e-mail will make
1366         # its way into here... try to handle it gracefully
1368         sendto = message.getaddrlist('resent-from')
1369         if not sendto:
1370             sendto = message.getaddrlist('from')
1371         if not sendto:
1372             # very bad-looking message - we don't even know who sent it
1373             msg = ['Badly formed message from mail gateway. Headers:']
1374             msg.extend(message.headers)
1375             msg = '\n'.join(map(str, msg))
1376             self.logger.error(msg)
1377             return
1379         msg = 'Handling message'
1380         if message.getheader('message-id'):
1381             msg += ' (Message-id=%r)'%message.getheader('message-id')
1382         self.logger.info(msg)
1384         # try normal message-handling
1385         if not self.trapExceptions:
1386             return self.handle_message(message)
1388         # no, we want to trap exceptions
1389         try:
1390             return self.handle_message(message)
1391         except MailUsageHelp:
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('\n\nMail Gateway Help\n=================')
1396             m.append(fulldoc)
1397             self.mailer.bounce_message(message, [sendto[0][1]], m,
1398                 subject="Mail Gateway Help")
1399         except MailUsageError, value:
1400             # bounce the message back to the sender with the usage message
1401             fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
1402             m = ['']
1403             m.append(str(value))
1404             m.append('\n\nMail Gateway Help\n=================')
1405             m.append(fulldoc)
1406             self.mailer.bounce_message(message, [sendto[0][1]], m)
1407         except Unauthorized, value:
1408             # just inform the user that he is not authorized
1409             m = ['']
1410             m.append(str(value))
1411             self.mailer.bounce_message(message, [sendto[0][1]], m)
1412         except IgnoreMessage:
1413             # do not take any action
1414             # this exception is thrown when email should be ignored
1415             msg = 'IgnoreMessage raised'
1416             if message.getheader('message-id'):
1417                 msg += ' (Message-id=%r)'%message.getheader('message-id')
1418             self.logger.info(msg)
1419             return
1420         except:
1421             msg = 'Exception handling message'
1422             if message.getheader('message-id'):
1423                 msg += ' (Message-id=%r)'%message.getheader('message-id')
1424             self.logger.exception(msg)
1426             # bounce the message back to the sender with the error message
1427             # let the admin know that something very bad is happening
1428             m = ['']
1429             m.append('An unexpected error occurred during the processing')
1430             m.append('of your message. The tracker administrator is being')
1431             m.append('notified.\n')
1432             self.mailer.bounce_message(message, [sendto[0][1]], m)
1434             m.append('----------------')
1435             m.append(traceback.format_exc())
1436             self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m)
1438     def handle_message(self, message):
1439         ''' message - a Message instance
1441         Parse the message as per the module docstring.
1442         '''
1443         # get database handle for handling one email
1444         self.db = self.instance.open ('admin')
1445         try:
1446             return self._handle_message(message)
1447         finally:
1448             self.db.close()
1450     def _handle_message(self, message):
1451         ''' message - a Message instance
1453         Parse the message as per the module docstring.
1454         The following code expects an opened database and a try/finally
1455         that closes the database.
1456         '''
1457         parsed_message = self.parsed_message_class(self, message)
1459         # Filter out messages to ignore
1460         parsed_message.handle_ignore()
1461         
1462         # Check for usage/help requests
1463         parsed_message.handle_help()
1464         
1465         # Check if the subject line is valid
1466         parsed_message.check_subject()
1468         # XXX Don't enable. This doesn't work yet.
1469         # XXX once this works it should be moved to parsedMessage class
1470 #  "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]"
1471         # handle delivery to addresses like:tracker+issue25@some.dom.ain
1472         # use the embedded issue number as our issue
1473 #            issue_re = config['MAILGW_ISSUE_ADDRESS_RE']
1474 #            if issue_re:
1475 #                for header in ['to', 'cc', 'bcc']:
1476 #                    addresses = message.getheader(header, '')
1477 #                if addresses:
1478 #                  # FIXME, this only finds the first match in the addresses.
1479 #                    issue = re.search(issue_re, addresses, 'i')
1480 #                    if issue:
1481 #                        classname = issue.group('classname')
1482 #                        nodeid = issue.group('nodeid')
1483 #                        break
1485         # Parse the subject line to get the importants parts
1486         parsed_message.parse_subject()
1488         # check for registration OTK
1489         if parsed_message.rego_confirm():
1490             return
1492         # get the classname
1493         parsed_message.get_classname()
1495         # get the optional nodeid
1496         parsed_message.get_nodeid()
1498         # Determine who the author is
1499         parsed_message.get_author_id()
1500         
1501         # make sure they're allowed to edit or create this class
1502         parsed_message.check_node_permissions()
1504         # author may have been created:
1505         # commit author to database and re-open as author
1506         parsed_message.commit_and_reopen_as_author()
1508         # Get the recipients list
1509         parsed_message.get_recipients()
1511         # get the new/updated node props
1512         parsed_message.get_props()
1514         # Handle PGP signed or encrypted messages
1515         parsed_message.get_pgp_message()
1517         # extract content and attachments from message body
1518         parsed_message.get_content_and_attachments()
1520         # put attachments into files linked to the issue
1521         parsed_message.create_files()
1522         
1523         # create the message if there's a message body (content)
1524         parsed_message.create_msg()
1525             
1526         # perform the node change / create
1527         nodeid = parsed_message.create_node()
1529         # commit the changes to the DB
1530         self.db.commit()
1532         return nodeid
1534     def get_class_arguments(self, class_type, classname=None):
1535         ''' class_type - a valid node class type:
1536                 - 'user' refers to the author of a message
1537                 - 'issue' refers to an issue-type class (to which the
1538                   message is appended) specified in parameter classname
1539                   Note that this need not be the real classname, we get
1540                   the real classname used as a parameter (from previous
1541                   message-parsing steps)
1542                 - 'file' specifies a file-type class
1543                 - 'msg' is the message-class
1544             classname - the name of the current issue-type class
1546         Parse the commandline arguments and retrieve the properties that
1547         are relevant to the class_type. We now allow multiple -S options
1548         per class_type (-C option).
1549         '''
1550         allprops = {}
1552         classname = classname or class_type
1553         cls_lookup = { 'issue' : classname }
1554         
1555         # Allow other issue-type classes -- take the real classname from
1556         # previous parsing-steps of the message:
1557         clsname = cls_lookup.get (class_type, class_type)
1559         # check if the clsname is valid
1560         try:
1561             self.db.getclass(clsname)
1562         except KeyError:
1563             mailadmin = self.instance.config['ADMIN_EMAIL']
1564             raise MailUsageError, _("""
1565 The mail gateway is not properly set up. Please contact
1566 %(mailadmin)s and have them fix the incorrect class specified as:
1567   %(clsname)s
1568 """) % locals()
1569         
1570         if self.arguments:
1571             # The default type on the commandline is msg
1572             if class_type == 'msg':
1573                 current_type = class_type
1574             else:
1575                 current_type = None
1576             
1577             # Handle the arguments specified by the email gateway command line.
1578             # We do this by looping over the list of self.arguments looking for
1579             # a -C to match the class we want, then use the -S setting string.
1580             for option, propstring in self.arguments:
1581                 if option in ( '-C', '--class'):
1582                     current_type = propstring.strip()
1583                     
1584                     if current_type != class_type:
1585                         current_type = None
1587                 elif current_type and option in ('-S', '--set'):
1588                     cls = cls_lookup.get (current_type, current_type)
1589                     temp_cl = self.db.getclass(cls)
1590                     errors, props = setPropArrayFromString(self,
1591                         temp_cl, propstring.strip())
1593                     if errors:
1594                         mailadmin = self.instance.config['ADMIN_EMAIL']
1595                         raise MailUsageError, _("""
1596 The mail gateway is not properly set up. Please contact
1597 %(mailadmin)s and have them fix the incorrect properties:
1598   %(errors)s
1599 """) % locals()
1600                     allprops.update(props)
1602         return allprops
1605 def setPropArrayFromString(self, cl, propString, nodeid=None):
1606     ''' takes string of form prop=value,value;prop2=value
1607         and returns (error, prop[..])
1608     '''
1609     props = {}
1610     errors = []
1611     for prop in string.split(propString, ';'):
1612         # extract the property name and value
1613         try:
1614             propname, value = prop.split('=')
1615         except ValueError, message:
1616             errors.append(_('not of form [arg=value,value,...;'
1617                 'arg=value,value,...]'))
1618             return (errors, props)
1619         # convert the value to a hyperdb-usable value
1620         propname = propname.strip()
1621         try:
1622             props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid,
1623                 propname, value)
1624         except hyperdb.HyperdbValueError, message:
1625             errors.append(str(message))
1626     return errors, props
1629 def extractUserFromList(userClass, users):
1630     '''Given a list of users, try to extract the first non-anonymous user
1631        and return that user, otherwise return None
1632     '''
1633     if len(users) > 1:
1634         for user in users:
1635             # make sure we don't match the anonymous or admin user
1636             if userClass.get(user, 'username') in ('admin', 'anonymous'):
1637                 continue
1638             # first valid match will do
1639             return user
1640         # well, I guess we have no choice
1641         return user[0]
1642     elif users:
1643         return users[0]
1644     return None
1647 def uidFromAddress(db, address, create=1, **user_props):
1648     ''' address is from the rfc822 module, and therefore is (name, addr)
1650         user is created if they don't exist in the db already
1651         user_props may supply additional user information
1652     '''
1653     (realname, address) = address
1655     # try a straight match of the address
1656     user = extractUserFromList(db.user, db.user.stringFind(address=address))
1657     if user is not None:
1658         return user
1660     # try the user alternate addresses if possible
1661     props = db.user.getprops()
1662     if props.has_key('alternate_addresses'):
1663         users = db.user.filter(None, {'alternate_addresses': address})
1664         user = extractUserFromList(db.user, users)
1665         if user is not None:
1666             return user
1668     # try to match the username to the address (for local
1669     # submissions where the address is empty)
1670     user = extractUserFromList(db.user, db.user.stringFind(username=address))
1672     # couldn't match address or username, so create a new user
1673     if create:
1674         # generate a username
1675         if '@' in address:
1676             username = address.split('@')[0]
1677         else:
1678             username = address
1679         trying = username
1680         n = 0
1681         while 1:
1682             try:
1683                 # does this username exist already?
1684                 db.user.lookup(trying)
1685             except KeyError:
1686                 break
1687             n += 1
1688             trying = username + str(n)
1690         # create!
1691         try:
1692             return db.user.create(username=trying, address=address,
1693                 realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES,
1694                 password=password.Password(password.generatePassword(), config=db.config),
1695                 **user_props)
1696         except exceptions.Reject:
1697             return 0
1698     else:
1699         return 0
1701 def parseContent(content, keep_citations=None, keep_body=None, config=None):
1702     """Parse mail message; return message summary and stripped content
1704     The message body is divided into sections by blank lines.
1705     Sections where the second and all subsequent lines begin with a ">"
1706     or "|" character are considered "quoting sections". The first line of
1707     the first non-quoting section becomes the summary of the message.
1709     Arguments:
1711         keep_citations: declared for backward compatibility.
1712             If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"]
1714         keep_body: declared for backward compatibility.
1715             If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"]
1717         config: tracker configuration object.
1718             If omitted or None, use default configuration.
1720     """
1721     if config is None:
1722         config = configuration.CoreConfig()
1723     if keep_citations is None:
1724         keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"]
1725     if keep_body is None:
1726         keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"]
1727     eol = config["MAILGW_EOL_RE"]
1728     signature = config["MAILGW_SIGN_RE"]
1729     original_msg = config["MAILGW_ORIGMSG_RE"]
1731     # strip off leading carriage-returns / newlines
1732     i = 0
1733     for i in range(len(content)):
1734         if content[i] not in '\r\n':
1735             break
1736     if i > 0:
1737         sections = config["MAILGW_BLANKLINE_RE"].split(content[i:])
1738     else:
1739         sections = config["MAILGW_BLANKLINE_RE"].split(content)
1741     # extract out the summary from the message
1742     summary = ''
1743     l = []
1744     for section in sections:
1745         #section = section.strip()
1746         if not section:
1747             continue
1748         lines = eol.split(section)
1749         if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and
1750                 lines[1] and lines[1][0] in '>|'):
1751             # see if there's a response somewhere inside this section (ie.
1752             # no blank line between quoted message and response)
1753             for line in lines[1:]:
1754                 if line and line[0] not in '>|':
1755                     break
1756             else:
1757                 # we keep quoted bits if specified in the config
1758                 if keep_citations:
1759                     l.append(section)
1760                 continue
1761             # keep this section - it has reponse stuff in it
1762             lines = lines[lines.index(line):]
1763             section = '\n'.join(lines)
1764             # and while we're at it, use the first non-quoted bit as
1765             # our summary
1766             summary = section
1768         if not summary:
1769             # if we don't have our summary yet use the first line of this
1770             # section
1771             summary = section
1772         elif signature.match(lines[0]) and 2 <= len(lines) <= 10:
1773             # lose any signature
1774             break
1775         elif original_msg.match(lines[0]):
1776             # ditch the stupid Outlook quoting of the entire original message
1777             break
1779         # and add the section to the output
1780         l.append(section)
1782     # figure the summary - find the first sentence-ending punctuation or the
1783     # first whole line, whichever is longest
1784     sentence = re.search(r'^([^!?\.]+[!?\.])', summary)
1785     if sentence:
1786         sentence = sentence.group(1)
1787     else:
1788         sentence = ''
1789     first = eol.split(summary)[0]
1790     summary = max(sentence, first)
1792     # Now reconstitute the message content minus the bits we don't care
1793     # about.
1794     if not keep_body:
1795         content = '\n\n'.join(l)
1797     return summary, content
1799 # vim: set filetype=python sts=4 sw=4 et si :