6274173e836511b409bb31f111892c3badbfad26
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
19 __doc__ = '''
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.
31 Summary
32 -------
33 The "summary" property on message nodes is taken from the first non-quoting
34 section in the message body. The message body is divided into sections by
35 blank lines. Sections where the second and all subsequent lines begin with
36 a ">" or "|" character are considered "quoting sections". The first line of
37 the first non-quoting section becomes the summary of the message.
39 Addresses
40 ---------
41 All of the addresses in the To: and Cc: headers of the incoming message are
42 looked up among the user nodes, and the corresponding users are placed in
43 the "recipients" property on the new "msg" node. The address in the From:
44 header similarly determines the "author" property of the new "msg"
45 node. The default handling for addresses that don't have corresponding
46 users is to create new users with no passwords and a username equal to the
47 address. (The web interface does not permit logins for users with no
48 passwords.) If we prefer to reject mail from outside sources, we can simply
49 register an auditor on the "user" class that prevents the creation of user
50 nodes with no passwords.
52 Actions
53 -------
54 The subject line of the incoming message is examined to determine whether
55 the message is an attempt to create a new item or to discuss an existing
56 item. A designator enclosed in square brackets is sought as the first thing
57 on the subject line (after skipping any "Fwd:" or "Re:" prefixes).
59 If an item designator (class name and id number) is found there, the newly
60 created "msg" node is added to the "messages" property for that item, and
61 any new "file" nodes are added to the "files" property for the item.
63 If just an item class name is found there, we attempt to create a new item
64 of that class with its "messages" property initialized to contain the new
65 "msg" node and its "files" property initialized to contain any new "file"
66 nodes.
68 Triggers
69 --------
70 Both cases may trigger detectors (in the first case we are calling the
71 set() method to add the message to the item's spool; in the second case we
72 are calling the create() method to create a new node). If an auditor raises
73 an exception, the original message is bounced back to the sender with the
74 explanatory message given in the exception.
76 $Id: mailgw.py,v 1.35 2001-11-22 15:46:42 jhermann Exp $
77 '''
80 import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri
81 import traceback
82 import hyperdb, date, password
84 class MailGWError(ValueError):
85 pass
87 class MailUsageError(ValueError):
88 pass
90 class Message(mimetools.Message):
91 ''' subclass mimetools.Message so we can retrieve the parts of the
92 message...
93 '''
94 def getPart(self):
95 ''' Get a single part of a multipart message and return it as a new
96 Message instance.
97 '''
98 boundary = self.getparam('boundary')
99 mid, end = '--'+boundary, '--'+boundary+'--'
100 s = cStringIO.StringIO()
101 while 1:
102 line = self.fp.readline()
103 if not line:
104 break
105 if line.strip() in (mid, end):
106 break
107 s.write(line)
108 if not s.getvalue().strip():
109 return None
110 s.seek(0)
111 return Message(s)
113 subject_re = re.compile(r'(?P<refwd>\s*\W?\s*(fwd|re)\s*\W?\s*)*'
114 r'\s*(\[(?P<classname>[^\d]+)(?P<nodeid>\d+)?\])'
115 r'\s*(?P<title>[^\[]+)(\[(?P<args>.+?)\])?', re.I)
117 class MailGW:
118 def __init__(self, instance, db):
119 self.instance = instance
120 self.db = db
122 def main(self, fp):
123 ''' fp - the file from which to read the Message.
124 '''
125 self.handle_Message(Message(fp))
127 def handle_Message(self, message):
128 '''Handle an RFC822 Message
130 Handle the Message object by calling handle_message() and then cope
131 with any errors raised by handle_message.
132 This method's job is to make that call and handle any
133 errors in a sane manner. It should be replaced if you wish to
134 handle errors in a different manner.
135 '''
136 m = []
137 # in some rare cases, a particularly stuffed-up e-mail will make
138 # its way into here... try to handle it gracefully
139 sendto = message.getaddrlist('from')
140 if sendto:
141 try:
142 self.handle_message(message)
143 return
144 except MailUsageError, value:
145 # bounce the message back to the sender with the usage message
146 fulldoc = '\n'.join(string.split(__doc__, '\n')[2:])
147 sendto = [sendto[0][1]]
148 m = ['Subject: Failed issue tracker submission', '']
149 m.append(str(value))
150 m.append('\n\nMail Gateway Help\n=================')
151 m.append(fulldoc)
152 except:
153 # bounce the message back to the sender with the error message
154 sendto = [sendto[0][1]]
155 m = ['Subject: failed issue tracker submission', '']
156 # TODO as attachments?
157 m.append('---- traceback of failure ----')
158 s = cStringIO.StringIO()
159 import traceback
160 traceback.print_exc(None, s)
161 m.append(s.getvalue())
162 m.append('---- failed message follows ----')
163 try:
164 message.fp.seek(0)
165 except:
166 pass
167 m.append(message.fp.read())
168 else:
169 # very bad-looking message - we don't even know who sent it
170 sendto = [self.ADMIN_EMAIL]
171 m = ['Subject: badly formed message from mail gateway']
172 m.append('')
173 m.append('The mail gateway retrieved a message which has no From:')
174 m.append('line, indicating that it is corrupt. Please check your')
175 m.append('mail gateway source.')
176 m.append('')
177 m.append('---- failed message follows ----')
178 try:
179 message.fp.seek(0)
180 except:
181 pass
182 m.append(message.fp.read())
184 # now send the message
185 try:
186 smtp = smtplib.SMTP(self.MAILHOST)
187 smtp.sendmail(self.ADMIN_EMAIL, sendto, '\n'.join(m))
188 except socket.error, value:
189 raise MailGWError, "Couldn't send confirmation email: "\
190 "mailhost %s"%value
191 except smtplib.SMTPException, value:
192 raise MailGWError, "Couldn't send confirmation email: %s"%value
194 def handle_message(self, message):
195 ''' message - a Message instance
197 Parse the message as per the module docstring.
198 '''
199 # handle the subject line
200 subject = message.getheader('subject', '')
201 m = subject_re.match(subject)
202 if not m:
203 raise MailUsageError, '''
204 The message you sent to roundup did not contain a properly formed subject
205 line. The subject must contain a class name or designator to indicate the
206 "topic" of the message. For example:
207 Subject: [issue] This is a new issue
208 - this will create a new issue in the tracker with the title "This is
209 a new issue".
210 Subject: [issue1234] This is a followup to issue 1234
211 - this will append the message's contents to the existing issue 1234
212 in the tracker.
214 Subject was: "%s"
215 '''%subject
216 classname = m.group('classname')
217 nodeid = m.group('nodeid')
218 title = m.group('title').strip()
219 subject_args = m.group('args')
220 try:
221 cl = self.db.getclass(classname)
222 except KeyError:
223 raise MailUsageError, '''
224 The class name you identified in the subject line ("%s") does not exist in the
225 database.
227 Valid class names are: %s
228 Subject was: "%s"
229 '''%(classname, ', '.join(self.db.getclasses()), subject)
231 # If there's no nodeid, check to see if this is a followup and
232 # maybe someone's responded to the initial mail that created an
233 # entry. Try to find the matching nodes with the same title, and
234 # use the _last_ one matched (since that'll _usually_ be the most
235 # recent...)
236 if not nodeid and m.group('refwd'):
237 l = cl.stringFind(title=title)
238 if l:
239 nodeid = l[-1]
241 # start of the props
242 properties = cl.getprops()
243 props = {}
245 # handle the args
246 args = m.group('args')
247 if args:
248 for prop in string.split(args, ';'):
249 try:
250 key, value = prop.split('=')
251 except ValueError, message:
252 raise MailUsageError, '''
253 Subject argument list not of form [arg=value,value,...;arg=value,value...]
254 (specific exception message was "%s")
256 Subject was: "%s"
257 '''%(message, subject)
258 try:
259 type = properties[key]
260 except KeyError:
261 raise MailUsageError, '''
262 Subject argument list refers to an invalid property: "%s"
264 Subject was: "%s"
265 '''%(key, subject)
266 if isinstance(type, hyperdb.String):
267 props[key] = value
268 if isinstance(type, hyperdb.Password):
269 props[key] = password.Password(value)
270 elif isinstance(type, hyperdb.Date):
271 try:
272 props[key] = date.Date(value)
273 except ValueError, message:
274 raise UsageError, '''
275 Subject argument list contains an invalid date for %s.
277 Error was: %s
278 Subject was: "%s"
279 '''%(key, message, subject)
280 elif isinstance(type, hyperdb.Interval):
281 try:
282 props[key] = date.Interval(value)
283 except ValueError, message:
284 raise UsageError, '''
285 Subject argument list contains an invalid date interval for %s.
287 Error was: %s
288 Subject was: "%s"
289 '''%(key, message, subject)
290 elif isinstance(type, hyperdb.Link):
291 props[key] = value
292 elif isinstance(type, hyperdb.Multilink):
293 props[key] = value.split(',')
295 #
296 # handle the users
297 #
298 author = self.db.uidFromAddress(message.getaddrlist('from')[0])
299 # reopen the database as the author
300 username = self.db.user.get(author, 'username')
301 self.db.close()
302 self.db = self.instance.open(username)
303 # now update the recipients list
304 recipients = []
305 tracker_email = self.ISSUE_TRACKER_EMAIL.lower()
306 for recipient in message.getaddrlist('to') + message.getaddrlist('cc'):
307 if recipient[1].strip().lower() == tracker_email:
308 continue
309 recipients.append(self.db.uidFromAddress(recipient))
311 # now handle the body - find the message
312 content_type = message.gettype()
313 attachments = []
314 if content_type == 'multipart/mixed':
315 # skip over the intro to the first boundary
316 part = message.getPart()
317 content = None
318 while 1:
319 # get the next part
320 part = message.getPart()
321 if part is None:
322 break
323 # parse it
324 subtype = part.gettype()
325 if subtype == 'text/plain' and not content:
326 # add all text/plain parts to the message content
327 if content is None:
328 content = part.fp.read()
329 else:
330 content = content + part.fp.read()
332 elif subtype == 'message/rfc822':
333 # handle message/rfc822 specially - the name should be
334 # the subject of the actual e-mail embedded here
335 i = part.fp.tell()
336 mailmess = Message(part.fp)
337 name = mailmess.getheader('subject')
338 part.fp.seek(i)
339 attachments.append((name, 'message/rfc822', part.fp.read()))
341 else:
342 # try name on Content-Type
343 name = part.getparam('name')
344 # this is just an attachment
345 encoding = part.getencoding()
346 if encoding == 'base64':
347 data = binascii.a2b_base64(part.fp.read())
348 elif encoding == 'quoted-printable':
349 # the quopri module wants to work with files
350 decoded = cStringIO.StringIO()
351 quopri.decode(part.fp, decoded)
352 data = decoded.getvalue()
353 elif encoding == 'uuencoded':
354 data = binascii.a2b_uu(part.fp.read())
355 attachments.append((name, part.gettype(), data))
357 if content is None:
358 raise MailUsageError, '''
359 Roundup requires the submission to be plain text. The message parser could
360 not find a text/plain part to use.
361 '''
363 elif content_type[:10] == 'multipart/':
364 # skip over the intro to the first boundary
365 message.getPart()
366 content = None
367 while 1:
368 # get the next part
369 part = message.getPart()
370 if part is None:
371 break
372 # parse it
373 if part.gettype() == 'text/plain' and not content:
374 # this one's our content
375 content = part.fp.read()
376 if content is None:
377 raise MailUsageError, '''
378 Roundup requires the submission to be plain text. The message parser could
379 not find a text/plain part to use.
380 '''
382 elif content_type != 'text/plain':
383 raise MailUsageError, '''
384 Roundup requires the submission to be plain text. The message parser could
385 not find a text/plain part to use.
386 '''
388 else:
389 content = message.fp.read()
391 summary, content = parseContent(content)
393 # handle the files
394 files = []
395 for (name, type, data) in attachments:
396 files.append(self.db.file.create(type=type, name=name,
397 content=data))
399 # now handle the db stuff
400 if nodeid:
401 # If an item designator (class name and id number) is found there,
402 # the newly created "msg" node is added to the "messages" property
403 # for that item, and any new "file" nodes are added to the "files"
404 # property for the item.
405 message_id = self.db.msg.create(author=author,
406 recipients=recipients, date=date.Date('.'), summary=summary,
407 content=content, files=files)
408 try:
409 messages = cl.get(nodeid, 'messages')
410 except IndexError:
411 raise MailUsageError, '''
412 The node specified by the designator in the subject of your message ("%s")
413 does not exist.
415 Subject was: "%s"
416 '''%(nodeid, subject)
417 messages.append(message_id)
418 props['messages'] = messages
420 # if the message is currently 'unread' or 'resolved', then set
421 # it to 'chatting'
422 if properties.has_key('status'):
423 try:
424 # determine the id of 'unread', 'resolved' and 'chatting'
425 unread_id = self.db.status.lookup('unread')
426 resolved_id = self.db.status.lookup('resolved')
427 chatting_id = self.db.status.lookup('chatting')
428 except KeyError:
429 pass
430 else:
431 if (not props.has_key('status') or
432 props['status'] == unread_id or
433 props['status'] == resolved_id):
434 props['status'] = chatting_id
436 try:
437 cl.set(nodeid, **props)
438 except (TypeError, IndexError, ValueError), message:
439 raise MailUsageError, '''
440 There was a problem with the message you sent:
441 %s
442 '''%message
443 else:
444 # If just an item class name is found there, we attempt to create a
445 # new item of that class with its "messages" property initialized to
446 # contain the new "msg" node and its "files" property initialized to
447 # contain any new "file" nodes.
448 message_id = self.db.msg.create(author=author,
449 recipients=recipients, date=date.Date('.'), summary=summary,
450 content=content, files=files)
451 # fill out the properties with defaults where required
452 if properties.has_key('assignedto') and \
453 not props.has_key('assignedto'):
454 props['assignedto'] = '1' # "admin"
456 # pre-set the issue to unread
457 if properties.has_key('status') and not props.has_key('status'):
458 try:
459 # determine the id of 'unread'
460 unread_id = self.db.status.lookup('unread')
461 except KeyError:
462 pass
463 else:
464 props['status'] = '1'
466 # set the title to the subject
467 if properties.has_key('title') and not props.has_key('title'):
468 props['title'] = title
470 # pre-load the messages list and nosy list
471 props['messages'] = [message_id]
472 props['nosy'] = props.get('nosy', []) + recipients
473 props['nosy'].append(author)
474 props['nosy'].sort()
476 # and attempt to create the new node
477 try:
478 nodeid = cl.create(**props)
479 except (TypeError, IndexError, ValueError), message:
480 raise MailUsageError, '''
481 There was a problem with the message you sent:
482 %s
483 '''%message
485 def parseContent(content, blank_line=re.compile(r'[\r\n]+\s*[\r\n]+'),
486 eol=re.compile(r'[\r\n]+'), signature=re.compile(r'^[>|\s]*[-_]+\s*$')):
487 ''' The message body is divided into sections by blank lines.
488 Sections where the second and all subsequent lines begin with a ">" or "|"
489 character are considered "quoting sections". The first line of the first
490 non-quoting section becomes the summary of the message.
491 '''
492 # strip off leading carriage-returns / newlines
493 i = 0
494 for i in range(len(content)):
495 if content[i] not in '\r\n':
496 break
497 if i > 0:
498 sections = blank_line.split(content[i:])
499 else:
500 sections = blank_line.split(content)
502 # extract out the summary from the message
503 summary = ''
504 l = []
505 for section in sections:
506 #section = section.strip()
507 if not section:
508 continue
509 lines = eol.split(section)
510 if lines[0] and lines[0][0] in '>|':
511 continue
512 if len(lines) > 1 and lines[1] and lines[1][0] in '>|':
513 continue
514 if not summary:
515 summary = lines[0]
516 l.append(section)
517 continue
518 if signature.match(lines[0]):
519 break
520 l.append(section)
521 return summary, '\n\n'.join(l)
523 #
524 # $Log: not supported by cvs2svn $
525 # Revision 1.34 2001/11/15 10:24:27 richard
526 # handle the case where there is no file attached
527 #
528 # Revision 1.33 2001/11/13 21:44:44 richard
529 # . re-open the database as the author in mail handling
530 #
531 # Revision 1.32 2001/11/12 22:04:29 richard
532 # oops, left debug in there
533 #
534 # Revision 1.31 2001/11/12 22:01:06 richard
535 # Fixed issues with nosy reaction and author copies.
536 #
537 # Revision 1.30 2001/11/09 22:33:28 richard
538 # More error handling fixes.
539 #
540 # Revision 1.29 2001/11/07 05:29:26 richard
541 # Modified roundup-mailgw so it can read e-mails from a local mail spool
542 # file. Truncates the spool file after parsing.
543 # Fixed a couple of small bugs introduced in roundup.mailgw when I started
544 # the popgw.
545 #
546 # Revision 1.28 2001/11/01 22:04:37 richard
547 # Started work on supporting a pop3-fetching server
548 # Fixed bugs:
549 # . bug #477104 ] HTML tag error in roundup-server
550 # . bug #477107 ] HTTP header problem
551 #
552 # Revision 1.27 2001/10/30 11:26:10 richard
553 # Case-insensitive match for ISSUE_TRACKER_EMAIL in address in e-mail.
554 #
555 # Revision 1.26 2001/10/30 00:54:45 richard
556 # Features:
557 # . #467129 ] Lossage when username=e-mail-address
558 # . #473123 ] Change message generation for author
559 # . MailGW now moves 'resolved' to 'chatting' on receiving e-mail for an issue.
560 #
561 # Revision 1.25 2001/10/28 23:22:28 richard
562 # fixed bug #474749 ] Indentations lost
563 #
564 # Revision 1.24 2001/10/23 22:57:52 richard
565 # Fix unread->chatting auto transition, thanks Roch'e
566 #
567 # Revision 1.23 2001/10/21 04:00:20 richard
568 # MailGW now moves 'unread' to 'chatting' on receiving e-mail for an issue.
569 #
570 # Revision 1.22 2001/10/21 03:35:13 richard
571 # bug #473125: Paragraph in e-mails
572 #
573 # Revision 1.21 2001/10/21 00:53:42 richard
574 # bug #473130: Nosy list not set correctly
575 #
576 # Revision 1.20 2001/10/17 23:13:19 richard
577 # Did a fair bit of work on the admin tool. Now has an extra command "table"
578 # which displays node information in a tabular format. Also fixed import and
579 # export so they work. Removed freshen.
580 # Fixed quopri usage in mailgw from bug reports.
581 #
582 # Revision 1.19 2001/10/11 23:43:04 richard
583 # Implemented the comma-separated printing option in the admin tool.
584 # Fixed a typo (more of a vim-o actually :) in mailgw.
585 #
586 # Revision 1.18 2001/10/11 06:38:57 richard
587 # Initial cut at trying to handle people responding to CC'ed messages that
588 # create an issue.
589 #
590 # Revision 1.17 2001/10/09 07:25:59 richard
591 # Added the Password property type. See "pydoc roundup.password" for
592 # implementation details. Have updated some of the documentation too.
593 #
594 # Revision 1.16 2001/10/05 02:23:24 richard
595 # . roundup-admin create now prompts for property info if none is supplied
596 # on the command-line.
597 # . hyperdb Class getprops() method may now return only the mutable
598 # properties.
599 # . Login now uses cookies, which makes it a whole lot more flexible. We can
600 # now support anonymous user access (read-only, unless there's an
601 # "anonymous" user, in which case write access is permitted). Login
602 # handling has been moved into cgi_client.Client.main()
603 # . The "extended" schema is now the default in roundup init.
604 # . The schemas have had their page headings modified to cope with the new
605 # login handling. Existing installations should copy the interfaces.py
606 # file from the roundup lib directory to their instance home.
607 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
608 # Ping - has been removed.
609 # . Fixed a whole bunch of places in the CGI interface where we should have
610 # been returning Not Found instead of throwing an exception.
611 # . Fixed a deviation from the spec: trying to modify the 'id' property of
612 # an item now throws an exception.
613 #
614 # Revision 1.15 2001/08/30 06:01:17 richard
615 # Fixed missing import in mailgw :(
616 #
617 # Revision 1.14 2001/08/13 23:02:54 richard
618 # Make the mail parser a little more robust.
619 #
620 # Revision 1.13 2001/08/12 06:32:36 richard
621 # using isinstance(blah, Foo) now instead of isFooType
622 #
623 # Revision 1.12 2001/08/08 01:27:00 richard
624 # Added better error handling to mailgw.
625 #
626 # Revision 1.11 2001/08/08 00:08:03 richard
627 # oops ;)
628 #
629 # Revision 1.10 2001/08/07 00:24:42 richard
630 # stupid typo
631 #
632 # Revision 1.9 2001/08/07 00:15:51 richard
633 # Added the copyright/license notice to (nearly) all files at request of
634 # Bizar Software.
635 #
636 # Revision 1.8 2001/08/05 07:06:07 richard
637 # removed some print statements
638 #
639 # Revision 1.7 2001/08/03 07:18:22 richard
640 # Implemented correct mail splitting (was taking a shortcut). Added unit
641 # tests. Also snips signatures now too.
642 #
643 # Revision 1.6 2001/08/01 04:24:21 richard
644 # mailgw was assuming certain properties existed on the issues being created.
645 #
646 # Revision 1.5 2001/07/29 07:01:39 richard
647 # Added vim command to all source so that we don't get no steenkin' tabs :)
648 #
649 # Revision 1.4 2001/07/28 06:43:02 richard
650 # Multipart message class has the getPart method now. Added some tests for it.
651 #
652 # Revision 1.3 2001/07/28 00:34:34 richard
653 # Fixed some non-string node ids.
654 #
655 # Revision 1.2 2001/07/22 12:09:32 richard
656 # Final commit of Grande Splite
657 #
658 #
659 # vim: set filetype=python ts=4 sw=4 et si