Commit | Line | Data |
---|---|---|
c638d827 CR |
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 | # | |
19 | ||
20 | """An e-mail gateway for Roundup. | |
21 | ||
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 | ||
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. | |
38 | ||
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. | |
51 | ||
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). | |
58 | ||
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. | |
62 | ||
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. | |
67 | ||
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. | |
75 | ||
76 | $Id: mailgw.py,v 1.196 2008-07-23 03:04:44 richard Exp $ | |
77 | """ | |
78 | __docformat__ = 'restructuredtext' | |
79 | ||
80 | import string, re, os, mimetools, cStringIO, smtplib, socket, binascii, quopri | |
81 | import time, random, sys, logging | |
82 | import traceback, rfc822 | |
83 | ||
84 | from email.Header import decode_header | |
85 | ||
86 | from roundup import configuration, hyperdb, date, password, rfc2822, exceptions | |
87 | from roundup.mailer import Mailer, MessageSendError | |
88 | from roundup.i18n import _ | |
89 | from roundup.hyperdb import iter_roles | |
90 | ||
91 | try: | |
92 | import pyme, pyme.core, pyme.gpgme | |
93 | except ImportError: | |
94 | pyme = None | |
95 | ||
96 | SENDMAILDEBUG = os.environ.get('SENDMAILDEBUG', '') | |
97 | ||
98 | class MailGWError(ValueError): | |
99 | pass | |
100 | ||
101 | class MailUsageError(ValueError): | |
102 | pass | |
103 | ||
104 | class MailUsageHelp(Exception): | |
105 | """ We need to send the help message to the user. """ | |
106 | pass | |
107 | ||
108 | class Unauthorized(Exception): | |
109 | """ Access denied """ | |
110 | pass | |
111 | ||
112 | class IgnoreMessage(Exception): | |
113 | """ A general class of message that we should ignore. """ | |
114 | pass | |
115 | class IgnoreBulk(IgnoreMessage): | |
116 | """ This is email from a mailing list or from a vacation program. """ | |
117 | pass | |
118 | class IgnoreLoop(IgnoreMessage): | |
119 | """ We've seen this message before... """ | |
120 | pass | |
121 | ||
122 | def initialiseSecurity(security): | |
123 | ''' Create some Permissions and Roles on the security object | |
124 | ||
125 | This function is directly invoked by security.Security.__init__() | |
126 | as a part of the Security object instantiation. | |
127 | ''' | |
128 | p = security.addPermission(name="Email Access", | |
129 | description="User may use the email interface") | |
130 | security.addPermissionToRole('Admin', p) | |
131 | ||
132 | def getparam(str, param): | |
133 | ''' From the rfc822 "header" string, extract "param" if it appears. | |
134 | ''' | |
135 | if ';' not in str: | |
136 | return None | |
137 | str = str[str.index(';'):] | |
138 | while str[:1] == ';': | |
139 | str = str[1:] | |
140 | if ';' in str: | |
141 | # XXX Should parse quotes! | |
142 | end = str.index(';') | |
143 | else: | |
144 | end = len(str) | |
145 | f = str[:end] | |
146 | if '=' in f: | |
147 | i = f.index('=') | |
148 | if f[:i].strip().lower() == param: | |
149 | return rfc822.unquote(f[i+1:].strip()) | |
150 | return None | |
151 | ||
152 | def gpgh_key_getall(key, attr): | |
153 | ''' return list of given attribute for all uids in | |
154 | a key | |
155 | ''' | |
156 | u = key.uids | |
157 | while u: | |
158 | yield getattr(u, attr) | |
159 | u = u.next | |
160 | ||
161 | def gpgh_sigs(sig): | |
162 | ''' more pythonic iteration over GPG signatures ''' | |
163 | while sig: | |
164 | yield sig | |
165 | sig = sig.next | |
166 | ||
167 | def check_pgp_sigs(sig, gpgctx, author): | |
168 | ''' Theoretically a PGP message can have several signatures. GPGME | |
169 | returns status on all signatures in a linked list. Walk that | |
170 | linked list looking for the author's signature | |
171 | ''' | |
172 | for sig in gpgh_sigs(sig): | |
173 | key = gpgctx.get_key(sig.fpr, False) | |
174 | # we really only care about the signature of the user who | |
175 | # submitted the email | |
176 | if key and (author in gpgh_key_getall(key, 'email')): | |
177 | if sig.summary & pyme.gpgme.GPGME_SIGSUM_VALID: | |
178 | return True | |
179 | else: | |
180 | # try to narrow down the actual problem to give a more useful | |
181 | # message in our bounce | |
182 | if sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_MISSING: | |
183 | raise MailUsageError, \ | |
184 | _("Message signed with unknown key: %s") % sig.fpr | |
185 | elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_EXPIRED: | |
186 | raise MailUsageError, \ | |
187 | _("Message signed with an expired key: %s") % sig.fpr | |
188 | elif sig.summary & pyme.gpgme.GPGME_SIGSUM_KEY_REVOKED: | |
189 | raise MailUsageError, \ | |
190 | _("Message signed with a revoked key: %s") % sig.fpr | |
191 | else: | |
192 | raise MailUsageError, \ | |
193 | _("Invalid PGP signature detected.") | |
194 | ||
195 | # we couldn't find a key belonging to the author of the email | |
196 | raise MailUsageError, _("Message signed with unknown key: %s") % sig.fpr | |
197 | ||
198 | class Message(mimetools.Message): | |
199 | ''' subclass mimetools.Message so we can retrieve the parts of the | |
200 | message... | |
201 | ''' | |
202 | def getpart(self): | |
203 | ''' Get a single part of a multipart message and return it as a new | |
204 | Message instance. | |
205 | ''' | |
206 | boundary = self.getparam('boundary') | |
207 | mid, end = '--'+boundary, '--'+boundary+'--' | |
208 | s = cStringIO.StringIO() | |
209 | while 1: | |
210 | line = self.fp.readline() | |
211 | if not line: | |
212 | break | |
213 | if line.strip() in (mid, end): | |
214 | # according to rfc 1431 the preceding line ending is part of | |
215 | # the boundary so we need to strip that | |
216 | length = s.tell() | |
217 | s.seek(-2, 1) | |
218 | lineending = s.read(2) | |
219 | if lineending == '\r\n': | |
220 | s.truncate(length - 2) | |
221 | elif lineending[1] in ('\r', '\n'): | |
222 | s.truncate(length - 1) | |
223 | else: | |
224 | raise ValueError('Unknown line ending in message.') | |
225 | break | |
226 | s.write(line) | |
227 | if not s.getvalue().strip(): | |
228 | return None | |
229 | s.seek(0) | |
230 | return Message(s) | |
231 | ||
232 | def getparts(self): | |
233 | """Get all parts of this multipart message.""" | |
234 | # skip over the intro to the first boundary | |
235 | self.fp.seek(0) | |
236 | self.getpart() | |
237 | ||
238 | # accumulate the other parts | |
239 | parts = [] | |
240 | while 1: | |
241 | part = self.getpart() | |
242 | if part is None: | |
243 | break | |
244 | parts.append(part) | |
245 | return parts | |
246 | ||
247 | def getheader(self, name, default=None): | |
248 | hdr = mimetools.Message.getheader(self, name, default) | |
249 | # TODO are there any other False values possible? | |
250 | # TODO if not hdr: return hdr | |
251 | if hdr is None: | |
252 | return None | |
253 | if not hdr: | |
254 | return '' | |
255 | if hdr: | |
256 | hdr = hdr.replace('\n','') # Inserted by rfc822.readheaders | |
257 | # historically this method has returned utf-8 encoded string | |
258 | l = [] | |
259 | for part, encoding in decode_header(hdr): | |
260 | if encoding: | |
261 | part = part.decode(encoding) | |
262 | l.append(part) | |
263 | return ''.join([s.encode('utf-8') for s in l]) | |
264 | ||
265 | def getaddrlist(self, name): | |
266 | # overload to decode the name part of the address | |
267 | l = [] | |
268 | for (name, addr) in mimetools.Message.getaddrlist(self, name): | |
269 | p = [] | |
270 | for part, encoding in decode_header(name): | |
271 | if encoding: | |
272 | part = part.decode(encoding) | |
273 | p.append(part) | |
274 | name = ''.join([s.encode('utf-8') for s in p]) | |
275 | l.append((name, addr)) | |
276 | return l | |
277 | ||
278 | def getname(self): | |
279 | """Find an appropriate name for this message.""" | |
280 | if self.gettype() == 'message/rfc822': | |
281 | # handle message/rfc822 specially - the name should be | |
282 | # the subject of the actual e-mail embedded here | |
283 | self.fp.seek(0) | |
284 | name = Message(self.fp).getheader('subject') | |
285 | else: | |
286 | # try name on Content-Type | |
287 | name = self.getparam('name') | |
288 | if not name: | |
289 | disp = self.getheader('content-disposition', None) | |
290 | if disp: | |
291 | name = getparam(disp, 'filename') | |
292 | ||
293 | if name: | |
294 | return name.strip() | |
295 | ||
296 | def getbody(self): | |
297 | """Get the decoded message body.""" | |
298 | self.rewindbody() | |
299 | encoding = self.getencoding() | |
300 | data = None | |
301 | if encoding == 'base64': | |
302 | # BUG: is base64 really used for text encoding or | |
303 | # are we inserting zip files here. | |
304 | data = binascii.a2b_base64(self.fp.read()) | |
305 | elif encoding == 'quoted-printable': | |
306 | # the quopri module wants to work with files | |
307 | decoded = cStringIO.StringIO() | |
308 | quopri.decode(self.fp, decoded) | |
309 | data = decoded.getvalue() | |
310 | elif encoding == 'uuencoded': | |
311 | data = binascii.a2b_uu(self.fp.read()) | |
312 | else: | |
313 | # take it as text | |
314 | data = self.fp.read() | |
315 | ||
316 | # Encode message to unicode | |
317 | charset = rfc2822.unaliasCharset(self.getparam("charset")) | |
318 | if charset: | |
319 | # Do conversion only if charset specified - handle | |
320 | # badly-specified charsets | |
321 | edata = unicode(data, charset, 'replace').encode('utf-8') | |
322 | # Convert from dos eol to unix | |
323 | edata = edata.replace('\r\n', '\n') | |
324 | else: | |
325 | # Leave message content as is | |
326 | edata = data | |
327 | ||
328 | return edata | |
329 | ||
330 | # General multipart handling: | |
331 | # Take the first text/plain part, anything else is considered an | |
332 | # attachment. | |
333 | # multipart/mixed: | |
334 | # Multiple "unrelated" parts. | |
335 | # multipart/Alternative (rfc 1521): | |
336 | # Like multipart/mixed, except that we'd only want one of the | |
337 | # alternatives. Generally a top-level part from MUAs sending HTML | |
338 | # mail - there will be a text/plain version. | |
339 | # multipart/signed (rfc 1847): | |
340 | # The control information is carried in the second of the two | |
341 | # required body parts. | |
342 | # ACTION: Default, so if content is text/plain we get it. | |
343 | # multipart/encrypted (rfc 1847): | |
344 | # The control information is carried in the first of the two | |
345 | # required body parts. | |
346 | # ACTION: Not handleable as the content is encrypted. | |
347 | # multipart/related (rfc 1872, 2112, 2387): | |
348 | # The Multipart/Related content-type addresses the MIME | |
349 | # representation of compound objects, usually HTML mail with embedded | |
350 | # images. Usually appears as an alternative. | |
351 | # ACTION: Default, if we must. | |
352 | # multipart/report (rfc 1892): | |
353 | # e.g. mail system delivery status reports. | |
354 | # ACTION: Default. Could be ignored or used for Delivery Notification | |
355 | # flagging. | |
356 | # multipart/form-data: | |
357 | # For web forms only. | |
358 | ||
359 | def extract_content(self, parent_type=None, ignore_alternatives = False): | |
360 | """Extract the body and the attachments recursively. | |
361 | ||
362 | If the content is hidden inside a multipart/alternative part, | |
363 | we use the *last* text/plain part of the *first* | |
364 | multipart/alternative in the whole message. | |
365 | """ | |
366 | content_type = self.gettype() | |
367 | content = None | |
368 | attachments = [] | |
369 | ||
370 | if content_type == 'text/plain': | |
371 | content = self.getbody() | |
372 | elif content_type[:10] == 'multipart/': | |
373 | content_found = bool (content) | |
374 | ig = ignore_alternatives and not content_found | |
375 | for part in self.getparts(): | |
376 | new_content, new_attach = part.extract_content(content_type, | |
377 | not content and ig) | |
378 | ||
379 | # If we haven't found a text/plain part yet, take this one, | |
380 | # otherwise make it an attachment. | |
381 | if not content: | |
382 | content = new_content | |
383 | cpart = part | |
384 | elif new_content: | |
385 | if content_found or content_type != 'multipart/alternative': | |
386 | attachments.append(part.text_as_attachment()) | |
387 | else: | |
388 | # if we have found a text/plain in the current | |
389 | # multipart/alternative and find another one, we | |
390 | # use the first as an attachment (if configured) | |
391 | # and use the second one because rfc 2046, sec. | |
392 | # 5.1.4. specifies that later parts are better | |
393 | # (thanks to Philipp Gortan for pointing this | |
394 | # out) | |
395 | attachments.append(cpart.text_as_attachment()) | |
396 | content = new_content | |
397 | cpart = part | |
398 | ||
399 | attachments.extend(new_attach) | |
400 | if ig and content_type == 'multipart/alternative' and content: | |
401 | attachments = [] | |
402 | elif (parent_type == 'multipart/signed' and | |
403 | content_type == 'application/pgp-signature'): | |
404 | # ignore it so it won't be saved as an attachment | |
405 | pass | |
406 | else: | |
407 | attachments.append(self.as_attachment()) | |
408 | return content, attachments | |
409 | ||
410 | def text_as_attachment(self): | |
411 | """Return first text/plain part as Message""" | |
412 | if not self.gettype().startswith ('multipart/'): | |
413 | return self.as_attachment() | |
414 | for part in self.getparts(): | |
415 | content_type = part.gettype() | |
416 | if content_type == 'text/plain': | |
417 | return part.as_attachment() | |
418 | elif content_type.startswith ('multipart/'): | |
419 | p = part.text_as_attachment() | |
420 | if p: | |
421 | return p | |
422 | return None | |
423 | ||
424 | def as_attachment(self): | |
425 | """Return this message as an attachment.""" | |
426 | return (self.getname(), self.gettype(), self.getbody()) | |
427 | ||
428 | def pgp_signed(self): | |
429 | ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter | |
430 | ''' | |
431 | return self.gettype() == 'multipart/signed' \ | |
432 | and self.typeheader.find('protocol="application/pgp-signature"') != -1 | |
433 | ||
434 | def pgp_encrypted(self): | |
435 | ''' RFC 3156 requires OpenPGP MIME mail to have the protocol parameter | |
436 | ''' | |
437 | return self.gettype() == 'multipart/encrypted' \ | |
438 | and self.typeheader.find('protocol="application/pgp-encrypted"') != -1 | |
439 | ||
440 | def decrypt(self, author): | |
441 | ''' decrypt an OpenPGP MIME message | |
442 | This message must be signed as well as encrypted using the "combined" | |
443 | method. The decrypted contents are returned as a new message. | |
444 | ''' | |
445 | (hdr, msg) = self.getparts() | |
446 | # According to the RFC 3156 encrypted mail must have exactly two parts. | |
447 | # The first part contains the control information. Let's verify that | |
448 | # the message meets the RFC before we try to decrypt it. | |
449 | if hdr.getbody() != 'Version: 1' or hdr.gettype() != 'application/pgp-encrypted': | |
450 | raise MailUsageError, \ | |
451 | _("Unknown multipart/encrypted version.") | |
452 | ||
453 | context = pyme.core.Context() | |
454 | ciphertext = pyme.core.Data(msg.getbody()) | |
455 | plaintext = pyme.core.Data() | |
456 | ||
457 | result = context.op_decrypt_verify(ciphertext, plaintext) | |
458 | ||
459 | if result: | |
460 | raise MailUsageError, _("Unable to decrypt your message.") | |
461 | ||
462 | # we've decrypted it but that just means they used our public | |
463 | # key to send it to us. now check the signatures to see if it | |
464 | # was signed by someone we trust | |
465 | result = context.op_verify_result() | |
466 | check_pgp_sigs(result.signatures, context, author) | |
467 | ||
468 | plaintext.seek(0,0) | |
469 | # pyme.core.Data implements a seek method with a different signature | |
470 | # than roundup can handle. So we'll put the data in a container that | |
471 | # the Message class can work with. | |
472 | c = cStringIO.StringIO() | |
473 | c.write(plaintext.read()) | |
474 | c.seek(0) | |
475 | return Message(c) | |
476 | ||
477 | def verify_signature(self, author): | |
478 | ''' verify the signature of an OpenPGP MIME message | |
479 | This only handles detached signatures. Old style | |
480 | PGP mail (i.e. '-----BEGIN PGP SIGNED MESSAGE----') | |
481 | is archaic and not supported :) | |
482 | ''' | |
483 | # we don't check the micalg parameter...gpgme seems to | |
484 | # figure things out on its own | |
485 | (msg, sig) = self.getparts() | |
486 | ||
487 | if sig.gettype() != 'application/pgp-signature': | |
488 | raise MailUsageError, \ | |
489 | _("No PGP signature found in message.") | |
490 | ||
491 | context = pyme.core.Context() | |
492 | # msg.getbody() is skipping over some headers that are | |
493 | # required to be present for verification to succeed so | |
494 | # we'll do this by hand | |
495 | msg.fp.seek(0) | |
496 | # according to rfc 3156 the data "MUST first be converted | |
497 | # to its content-type specific canonical form. For | |
498 | # text/plain this means conversion to an appropriate | |
499 | # character set and conversion of line endings to the | |
500 | # canonical <CR><LF> sequence." | |
501 | # TODO: what about character set conversion? | |
502 | canonical_msg = re.sub('(?<!\r)\n', '\r\n', msg.fp.read()) | |
503 | msg_data = pyme.core.Data(canonical_msg) | |
504 | sig_data = pyme.core.Data(sig.getbody()) | |
505 | ||
506 | context.op_verify(sig_data, msg_data, None) | |
507 | ||
508 | # check all signatures for validity | |
509 | result = context.op_verify_result() | |
510 | check_pgp_sigs(result.signatures, context, author) | |
511 | ||
512 | class MailGW: | |
513 | ||
514 | def __init__(self, instance, arguments=()): | |
515 | self.instance = instance | |
516 | self.arguments = arguments | |
517 | self.default_class = None | |
518 | for option, value in self.arguments: | |
519 | if option == '-c': | |
520 | self.default_class = value.strip() | |
521 | ||
522 | self.mailer = Mailer(instance.config) | |
523 | self.logger = logging.getLogger('mailgw') | |
524 | ||
525 | # should we trap exceptions (normal usage) or pass them through | |
526 | # (for testing) | |
527 | self.trapExceptions = 1 | |
528 | ||
529 | def do_pipe(self): | |
530 | """ Read a message from standard input and pass it to the mail handler. | |
531 | ||
532 | Read into an internal structure that we can seek on (in case | |
533 | there's an error). | |
534 | ||
535 | XXX: we may want to read this into a temporary file instead... | |
536 | """ | |
537 | s = cStringIO.StringIO() | |
538 | s.write(sys.stdin.read()) | |
539 | s.seek(0) | |
540 | self.main(s) | |
541 | return 0 | |
542 | ||
543 | def do_mailbox(self, filename): | |
544 | """ Read a series of messages from the specified unix mailbox file and | |
545 | pass each to the mail handler. | |
546 | """ | |
547 | # open the spool file and lock it | |
548 | import fcntl | |
549 | # FCNTL is deprecated in py2.3 and fcntl takes over all the symbols | |
550 | if hasattr(fcntl, 'LOCK_EX'): | |
551 | FCNTL = fcntl | |
552 | else: | |
553 | import FCNTL | |
554 | f = open(filename, 'r+') | |
555 | fcntl.flock(f.fileno(), FCNTL.LOCK_EX) | |
556 | ||
557 | # handle and clear the mailbox | |
558 | try: | |
559 | from mailbox import UnixMailbox | |
560 | mailbox = UnixMailbox(f, factory=Message) | |
561 | # grab one message | |
562 | message = mailbox.next() | |
563 | while message: | |
564 | # handle this message | |
565 | self.handle_Message(message) | |
566 | message = mailbox.next() | |
567 | # nuke the file contents | |
568 | os.ftruncate(f.fileno(), 0) | |
569 | except: | |
570 | import traceback | |
571 | traceback.print_exc() | |
572 | return 1 | |
573 | fcntl.flock(f.fileno(), FCNTL.LOCK_UN) | |
574 | return 0 | |
575 | ||
576 | def do_imap(self, server, user='', password='', mailbox='', ssl=0, | |
577 | cram=0): | |
578 | ''' Do an IMAP connection | |
579 | ''' | |
580 | import getpass, imaplib, socket | |
581 | try: | |
582 | if not user: | |
583 | user = raw_input('User: ') | |
584 | if not password: | |
585 | password = getpass.getpass() | |
586 | except (KeyboardInterrupt, EOFError): | |
587 | # Ctrl C or D maybe also Ctrl Z under Windows. | |
588 | print "\nAborted by user." | |
589 | return 1 | |
590 | # open a connection to the server and retrieve all messages | |
591 | try: | |
592 | if ssl: | |
593 | self.logger.debug('Trying server %r with ssl'%server) | |
594 | server = imaplib.IMAP4_SSL(server) | |
595 | else: | |
596 | self.logger.debug('Trying server %r without ssl'%server) | |
597 | server = imaplib.IMAP4(server) | |
598 | except (imaplib.IMAP4.error, socket.error, socket.sslerror): | |
599 | self.logger.exception('IMAP server error') | |
600 | return 1 | |
601 | ||
602 | try: | |
603 | if cram: | |
604 | server.login_cram_md5(user, password) | |
605 | else: | |
606 | server.login(user, password) | |
607 | except imaplib.IMAP4.error, e: | |
608 | self.logger.exception('IMAP login failure') | |
609 | return 1 | |
610 | ||
611 | try: | |
612 | if not mailbox: | |
613 | (typ, data) = server.select() | |
614 | else: | |
615 | (typ, data) = server.select(mailbox=mailbox) | |
616 | if typ != 'OK': | |
617 | self.logger.error('Failed to get mailbox %r: %s'%(mailbox, | |
618 | data)) | |
619 | return 1 | |
620 | try: | |
621 | numMessages = int(data[0]) | |
622 | except ValueError, value: | |
623 | self.logger.error('Invalid message count from mailbox %r'% | |
624 | data[0]) | |
625 | return 1 | |
626 | for i in range(1, numMessages+1): | |
627 | (typ, data) = server.fetch(str(i), '(RFC822)') | |
628 | ||
629 | # mark the message as deleted. | |
630 | server.store(str(i), '+FLAGS', r'(\Deleted)') | |
631 | ||
632 | # process the message | |
633 | s = cStringIO.StringIO(data[0][1]) | |
634 | s.seek(0) | |
635 | self.handle_Message(Message(s)) | |
636 | server.close() | |
637 | finally: | |
638 | try: | |
639 | server.expunge() | |
640 | except: | |
641 | pass | |
642 | server.logout() | |
643 | ||
644 | return 0 | |
645 | ||
646 | ||
647 | def do_apop(self, server, user='', password='', ssl=False): | |
648 | ''' Do authentication POP | |
649 | ''' | |
650 | self._do_pop(server, user, password, True, ssl) | |
651 | ||
652 | def do_pop(self, server, user='', password='', ssl=False): | |
653 | ''' Do plain POP | |
654 | ''' | |
655 | self._do_pop(server, user, password, False, ssl) | |
656 | ||
657 | def _do_pop(self, server, user, password, apop, ssl): | |
658 | '''Read a series of messages from the specified POP server. | |
659 | ''' | |
660 | import getpass, poplib, socket | |
661 | try: | |
662 | if not user: | |
663 | user = raw_input('User: ') | |
664 | if not password: | |
665 | password = getpass.getpass() | |
666 | except (KeyboardInterrupt, EOFError): | |
667 | # Ctrl C or D maybe also Ctrl Z under Windows. | |
668 | print "\nAborted by user." | |
669 | return 1 | |
670 | ||
671 | # open a connection to the server and retrieve all messages | |
672 | try: | |
673 | if ssl: | |
674 | klass = poplib.POP3_SSL | |
675 | else: | |
676 | klass = poplib.POP3 | |
677 | server = klass(server) | |
678 | except socket.error: | |
679 | self.logger.exception('POP server error') | |
680 | return 1 | |
681 | if apop: | |
682 | server.apop(user, password) | |
683 | else: | |
684 | server.user(user) | |
685 | server.pass_(password) | |
686 | numMessages = len(server.list()[1]) | |
687 | for i in range(1, numMessages+1): | |
688 | # retr: returns | |
689 | # [ pop response e.g. '+OK 459 octets', | |
690 | # [ array of message lines ], | |
691 | # number of octets ] | |
692 | lines = server.retr(i)[1] | |
693 | s = cStringIO.StringIO('\n'.join(lines)) | |
694 | s.seek(0) | |
695 | self.handle_Message(Message(s)) | |
696 | # delete the message | |
697 | server.dele(i) | |
698 | ||
699 | # quit the server to commit changes. | |
700 | server.quit() | |
701 | return 0 | |
702 | ||
703 | def main(self, fp): | |
704 | ''' fp - the file from which to read the Message. | |
705 | ''' | |
706 | return self.handle_Message(Message(fp)) | |
707 | ||
708 | def handle_Message(self, message): | |
709 | """Handle an RFC822 Message | |
710 | ||
711 | Handle the Message object by calling handle_message() and then cope | |
712 | with any errors raised by handle_message. | |
713 | This method's job is to make that call and handle any | |
714 | errors in a sane manner. It should be replaced if you wish to | |
715 | handle errors in a different manner. | |
716 | """ | |
717 | # in some rare cases, a particularly stuffed-up e-mail will make | |
718 | # its way into here... try to handle it gracefully | |
719 | ||
720 | sendto = message.getaddrlist('resent-from') | |
721 | if not sendto: | |
722 | sendto = message.getaddrlist('from') | |
723 | if not sendto: | |
724 | # very bad-looking message - we don't even know who sent it | |
725 | msg = ['Badly formed message from mail gateway. Headers:'] | |
726 | msg.extend(message.headers) | |
727 | msg = '\n'.join(map(str, msg)) | |
728 | self.logger.error(msg) | |
729 | return | |
730 | ||
731 | msg = 'Handling message' | |
732 | if message.getheader('message-id'): | |
733 | msg += ' (Message-id=%r)'%message.getheader('message-id') | |
734 | self.logger.info(msg) | |
735 | ||
736 | # try normal message-handling | |
737 | if not self.trapExceptions: | |
738 | return self.handle_message(message) | |
739 | ||
740 | # no, we want to trap exceptions | |
741 | try: | |
742 | return self.handle_message(message) | |
743 | except MailUsageHelp: | |
744 | # bounce the message back to the sender with the usage message | |
745 | fulldoc = '\n'.join(string.split(__doc__, '\n')[2:]) | |
746 | m = [''] | |
747 | m.append('\n\nMail Gateway Help\n=================') | |
748 | m.append(fulldoc) | |
749 | self.mailer.bounce_message(message, [sendto[0][1]], m, | |
750 | subject="Mail Gateway Help") | |
751 | except MailUsageError, value: | |
752 | # bounce the message back to the sender with the usage message | |
753 | fulldoc = '\n'.join(string.split(__doc__, '\n')[2:]) | |
754 | m = [''] | |
755 | m.append(str(value)) | |
756 | m.append('\n\nMail Gateway Help\n=================') | |
757 | m.append(fulldoc) | |
758 | self.mailer.bounce_message(message, [sendto[0][1]], m) | |
759 | except Unauthorized, value: | |
760 | # just inform the user that he is not authorized | |
761 | m = [''] | |
762 | m.append(str(value)) | |
763 | self.mailer.bounce_message(message, [sendto[0][1]], m) | |
764 | except IgnoreMessage: | |
765 | # do not take any action | |
766 | # this exception is thrown when email should be ignored | |
767 | msg = 'IgnoreMessage raised' | |
768 | if message.getheader('message-id'): | |
769 | msg += ' (Message-id=%r)'%message.getheader('message-id') | |
770 | self.logger.info(msg) | |
771 | return | |
772 | except: | |
773 | msg = 'Exception handling message' | |
774 | if message.getheader('message-id'): | |
775 | msg += ' (Message-id=%r)'%message.getheader('message-id') | |
776 | self.logger.exception(msg) | |
777 | ||
778 | # bounce the message back to the sender with the error message | |
779 | # let the admin know that something very bad is happening | |
780 | m = [''] | |
781 | m.append('An unexpected error occurred during the processing') | |
782 | m.append('of your message. The tracker administrator is being') | |
783 | m.append('notified.\n') | |
784 | self.mailer.bounce_message(message, [sendto[0][1]], m) | |
785 | ||
786 | m.append('----------------') | |
787 | m.append(traceback.format_exc()) | |
788 | self.mailer.bounce_message(message, [self.instance.config.ADMIN_EMAIL], m) | |
789 | ||
790 | def handle_message(self, message): | |
791 | ''' message - a Message instance | |
792 | ||
793 | Parse the message as per the module docstring. | |
794 | ''' | |
795 | # get database handle for handling one email | |
796 | self.db = self.instance.open ('admin') | |
797 | try: | |
798 | return self._handle_message (message) | |
799 | finally: | |
800 | self.db.close() | |
801 | ||
802 | def _handle_message(self, message): | |
803 | ''' message - a Message instance | |
804 | ||
805 | Parse the message as per the module docstring. | |
806 | ||
807 | The implementation expects an opened database and a try/finally | |
808 | that closes the database. | |
809 | ''' | |
810 | # detect loops | |
811 | if message.getheader('x-roundup-loop', ''): | |
812 | raise IgnoreLoop | |
813 | ||
814 | # handle the subject line | |
815 | subject = message.getheader('subject', '') | |
816 | if not subject: | |
817 | raise MailUsageError, _(""" | |
818 | Emails to Roundup trackers must include a Subject: line! | |
819 | """) | |
820 | ||
821 | # detect Precedence: Bulk, or Microsoft Outlook autoreplies | |
822 | if (message.getheader('precedence', '') == 'bulk' | |
823 | or subject.lower().find("autoreply") > 0): | |
824 | raise IgnoreBulk | |
825 | ||
826 | if subject.strip().lower() == 'help': | |
827 | raise MailUsageHelp | |
828 | ||
829 | # config is used many times in this method. | |
830 | # make local variable for easier access | |
831 | config = self.instance.config | |
832 | ||
833 | # determine the sender's address | |
834 | from_list = message.getaddrlist('resent-from') | |
835 | if not from_list: | |
836 | from_list = message.getaddrlist('from') | |
837 | ||
838 | # XXX Don't enable. This doesn't work yet. | |
839 | # "[^A-z.]tracker\+(?P<classname>[^\d\s]+)(?P<nodeid>\d+)\@some.dom.ain[^A-z.]" | |
840 | # handle delivery to addresses like:tracker+issue25@some.dom.ain | |
841 | # use the embedded issue number as our issue | |
842 | # issue_re = config['MAILGW_ISSUE_ADDRESS_RE'] | |
843 | # if issue_re: | |
844 | # for header in ['to', 'cc', 'bcc']: | |
845 | # addresses = message.getheader(header, '') | |
846 | # if addresses: | |
847 | # # FIXME, this only finds the first match in the addresses. | |
848 | # issue = re.search(issue_re, addresses, 'i') | |
849 | # if issue: | |
850 | # classname = issue.group('classname') | |
851 | # nodeid = issue.group('nodeid') | |
852 | # break | |
853 | ||
854 | # Matches subjects like: | |
855 | # Re: "[issue1234] title of issue [status=resolved]" | |
856 | ||
857 | # Alias since we need a reference to the original subject for | |
858 | # later use in error messages | |
859 | tmpsubject = subject | |
860 | ||
861 | sd_open, sd_close = config['MAILGW_SUBJECT_SUFFIX_DELIMITERS'] | |
862 | delim_open = re.escape(sd_open) | |
863 | if delim_open in '[(': delim_open = '\\' + delim_open | |
864 | delim_close = re.escape(sd_close) | |
865 | if delim_close in '[(': delim_close = '\\' + delim_close | |
866 | ||
867 | matches = dict.fromkeys(['refwd', 'quote', 'classname', | |
868 | 'nodeid', 'title', 'args', | |
869 | 'argswhole']) | |
870 | ||
871 | # Look for Re: et. al. Used later on for MAILGW_SUBJECT_CONTENT_MATCH | |
872 | re_re = r"(?P<refwd>%s)\s*" % config["MAILGW_REFWD_RE"].pattern | |
873 | m = re.match(re_re, tmpsubject, re.IGNORECASE|re.VERBOSE|re.UNICODE) | |
874 | if m: | |
875 | m = m.groupdict() | |
876 | if m['refwd']: | |
877 | matches.update(m) | |
878 | tmpsubject = tmpsubject[len(m['refwd']):] # Consume Re: | |
879 | ||
880 | # Look for Leading " | |
881 | m = re.match(r'(?P<quote>\s*")', tmpsubject, | |
882 | re.IGNORECASE) | |
883 | if m: | |
884 | matches.update(m.groupdict()) | |
885 | tmpsubject = tmpsubject[len(matches['quote']):] # Consume quote | |
886 | ||
887 | has_prefix = re.search(r'^%s(\w+)%s'%(delim_open, | |
888 | delim_close), tmpsubject.strip()) | |
889 | ||
890 | class_re = r'%s(?P<classname>(%s))(?P<nodeid>\d+)?%s'%(delim_open, | |
891 | "|".join(self.db.getclasses()), delim_close) | |
892 | # Note: re.search, not re.match as there might be garbage | |
893 | # (mailing list prefix, etc.) before the class identifier | |
894 | m = re.search(class_re, tmpsubject, re.IGNORECASE) | |
895 | if m: | |
896 | matches.update(m.groupdict()) | |
897 | # Skip to the end of the class identifier, including any | |
898 | # garbage before it. | |
899 | ||
900 | tmpsubject = tmpsubject[m.end():] | |
901 | ||
902 | # if we've not found a valid classname prefix then force the | |
903 | # scanning to handle there being a leading delimiter | |
904 | title_re = r'(?P<title>%s[^%s]*)'%( | |
905 | not matches['classname'] and '.' or '', delim_open) | |
906 | m = re.match(title_re, tmpsubject.strip(), re.IGNORECASE) | |
907 | if m: | |
908 | matches.update(m.groupdict()) | |
909 | tmpsubject = tmpsubject[len(matches['title']):] # Consume title | |
910 | ||
911 | args_re = r'(?P<argswhole>%s(?P<args>.+?)%s)?'%(delim_open, | |
912 | delim_close) | |
913 | m = re.search(args_re, tmpsubject.strip(), re.IGNORECASE|re.VERBOSE) | |
914 | if m: | |
915 | matches.update(m.groupdict()) | |
916 | ||
917 | # figure subject line parsing modes | |
918 | pfxmode = config['MAILGW_SUBJECT_PREFIX_PARSING'] | |
919 | sfxmode = config['MAILGW_SUBJECT_SUFFIX_PARSING'] | |
920 | ||
921 | # check for registration OTK | |
922 | # or fallback on the default class | |
923 | if self.db.config['EMAIL_REGISTRATION_CONFIRMATION']: | |
924 | otk_re = re.compile('-- key (?P<otk>[a-zA-Z0-9]{32})') | |
925 | otk = otk_re.search(matches['title'] or '') | |
926 | if otk: | |
927 | self.db.confirm_registration(otk.group('otk')) | |
928 | subject = 'Your registration to %s is complete' % \ | |
929 | config['TRACKER_NAME'] | |
930 | sendto = [from_list[0][1]] | |
931 | self.mailer.standard_message(sendto, subject, '') | |
932 | return | |
933 | ||
934 | # get the classname | |
935 | if pfxmode == 'none': | |
936 | classname = None | |
937 | else: | |
938 | classname = matches['classname'] | |
939 | ||
940 | if not classname and has_prefix and pfxmode == 'strict': | |
941 | raise MailUsageError, _(""" | |
942 | The message you sent to roundup did not contain a properly formed subject | |
943 | line. The subject must contain a class name or designator to indicate the | |
944 | 'topic' of the message. For example: | |
945 | Subject: [issue] This is a new issue | |
946 | - this will create a new issue in the tracker with the title 'This is | |
947 | a new issue'. | |
948 | Subject: [issue1234] This is a followup to issue 1234 | |
949 | - this will append the message's contents to the existing issue 1234 | |
950 | in the tracker. | |
951 | ||
952 | Subject was: '%(subject)s' | |
953 | """) % locals() | |
954 | ||
955 | # try to get the class specified - if "loose" or "none" then fall | |
956 | # back on the default | |
957 | attempts = [] | |
958 | if classname: | |
959 | attempts.append(classname) | |
960 | ||
961 | if self.default_class: | |
962 | attempts.append(self.default_class) | |
963 | else: | |
964 | attempts.append(config['MAILGW_DEFAULT_CLASS']) | |
965 | ||
966 | # first valid class name wins | |
967 | cl = None | |
968 | for trycl in attempts: | |
969 | try: | |
970 | cl = self.db.getclass(trycl) | |
971 | classname = trycl | |
972 | break | |
973 | except KeyError: | |
974 | pass | |
975 | ||
976 | if not cl: | |
977 | validname = ', '.join(self.db.getclasses()) | |
978 | if classname: | |
979 | raise MailUsageError, _(""" | |
980 | The class name you identified in the subject line ("%(classname)s") does | |
981 | not exist in the database. | |
982 | ||
983 | Valid class names are: %(validname)s | |
984 | Subject was: "%(subject)s" | |
985 | """) % locals() | |
986 | else: | |
987 | raise MailUsageError, _(""" | |
988 | You did not identify a class name in the subject line and there is no | |
989 | default set for this tracker. The subject must contain a class name or | |
990 | designator to indicate the 'topic' of the message. For example: | |
991 | Subject: [issue] This is a new issue | |
992 | - this will create a new issue in the tracker with the title 'This is | |
993 | a new issue'. | |
994 | Subject: [issue1234] This is a followup to issue 1234 | |
995 | - this will append the message's contents to the existing issue 1234 | |
996 | in the tracker. | |
997 | ||
998 | Subject was: '%(subject)s' | |
999 | """) % locals() | |
1000 | ||
1001 | # get the optional nodeid | |
1002 | if pfxmode == 'none': | |
1003 | nodeid = None | |
1004 | else: | |
1005 | nodeid = matches['nodeid'] | |
1006 | ||
1007 | # try in-reply-to to match the message if there's no nodeid | |
1008 | inreplyto = message.getheader('in-reply-to') or '' | |
1009 | if nodeid is None and inreplyto: | |
1010 | l = self.db.getclass('msg').stringFind(messageid=inreplyto) | |
1011 | if l: | |
1012 | nodeid = cl.filter(None, {'messages':l})[0] | |
1013 | ||
1014 | # title is optional too | |
1015 | title = matches['title'] | |
1016 | if title: | |
1017 | title = title.strip() | |
1018 | else: | |
1019 | title = '' | |
1020 | ||
1021 | # strip off the quotes that dumb emailers put around the subject, like | |
1022 | # Re: "[issue1] bla blah" | |
1023 | if matches['quote'] and title.endswith('"'): | |
1024 | title = title[:-1] | |
1025 | ||
1026 | # but we do need either a title or a nodeid... | |
1027 | if nodeid is None and not title: | |
1028 | raise MailUsageError, _(""" | |
1029 | I cannot match your message to a node in the database - you need to either | |
1030 | supply a full designator (with number, eg "[issue123]") or keep the | |
1031 | previous subject title intact so I can match that. | |
1032 | ||
1033 | Subject was: "%(subject)s" | |
1034 | """) % locals() | |
1035 | ||
1036 | # If there's no nodeid, check to see if this is a followup and | |
1037 | # maybe someone's responded to the initial mail that created an | |
1038 | # entry. Try to find the matching nodes with the same title, and | |
1039 | # use the _last_ one matched (since that'll _usually_ be the most | |
1040 | # recent...). The subject_content_match config may specify an | |
1041 | # additional restriction based on the matched node's creation or | |
1042 | # activity. | |
1043 | tmatch_mode = config['MAILGW_SUBJECT_CONTENT_MATCH'] | |
1044 | if tmatch_mode != 'never' and nodeid is None and matches['refwd']: | |
1045 | l = cl.stringFind(title=title) | |
1046 | limit = None | |
1047 | if (tmatch_mode.startswith('creation') or | |
1048 | tmatch_mode.startswith('activity')): | |
1049 | limit, interval = tmatch_mode.split(' ', 1) | |
1050 | threshold = date.Date('.') - date.Interval(interval) | |
1051 | for id in l: | |
1052 | if limit: | |
1053 | if threshold < cl.get(id, limit): | |
1054 | nodeid = id | |
1055 | else: | |
1056 | nodeid = id | |
1057 | ||
1058 | # if a nodeid was specified, make sure it's valid | |
1059 | if nodeid is not None and not cl.hasnode(nodeid): | |
1060 | if pfxmode == 'strict': | |
1061 | raise MailUsageError, _(""" | |
1062 | The node specified by the designator in the subject of your message | |
1063 | ("%(nodeid)s") does not exist. | |
1064 | ||
1065 | Subject was: "%(subject)s" | |
1066 | """) % locals() | |
1067 | else: | |
1068 | title = subject | |
1069 | nodeid = None | |
1070 | ||
1071 | # Handle the arguments specified by the email gateway command line. | |
1072 | # We do this by looping over the list of self.arguments looking for | |
1073 | # a -C to tell us what class then the -S setting string. | |
1074 | msg_props = {} | |
1075 | user_props = {} | |
1076 | file_props = {} | |
1077 | issue_props = {} | |
1078 | # so, if we have any arguments, use them | |
1079 | if self.arguments: | |
1080 | current_class = 'msg' | |
1081 | for option, propstring in self.arguments: | |
1082 | if option in ( '-C', '--class'): | |
1083 | current_class = propstring.strip() | |
1084 | # XXX this is not flexible enough. | |
1085 | # we should chect for subclasses of these classes, | |
1086 | # not for the class name... | |
1087 | if current_class not in ('msg', 'file', 'user', 'issue'): | |
1088 | mailadmin = config['ADMIN_EMAIL'] | |
1089 | raise MailUsageError, _(""" | |
1090 | The mail gateway is not properly set up. Please contact | |
1091 | %(mailadmin)s and have them fix the incorrect class specified as: | |
1092 | %(current_class)s | |
1093 | """) % locals() | |
1094 | if option in ('-S', '--set'): | |
1095 | if current_class == 'issue' : | |
1096 | errors, issue_props = setPropArrayFromString(self, | |
1097 | cl, propstring.strip(), nodeid) | |
1098 | elif current_class == 'file' : | |
1099 | temp_cl = self.db.getclass('file') | |
1100 | errors, file_props = setPropArrayFromString(self, | |
1101 | temp_cl, propstring.strip()) | |
1102 | elif current_class == 'msg' : | |
1103 | temp_cl = self.db.getclass('msg') | |
1104 | errors, msg_props = setPropArrayFromString(self, | |
1105 | temp_cl, propstring.strip()) | |
1106 | elif current_class == 'user' : | |
1107 | temp_cl = self.db.getclass('user') | |
1108 | errors, user_props = setPropArrayFromString(self, | |
1109 | temp_cl, propstring.strip()) | |
1110 | if errors: | |
1111 | mailadmin = config['ADMIN_EMAIL'] | |
1112 | raise MailUsageError, _(""" | |
1113 | The mail gateway is not properly set up. Please contact | |
1114 | %(mailadmin)s and have them fix the incorrect properties: | |
1115 | %(errors)s | |
1116 | """) % locals() | |
1117 | ||
1118 | # | |
1119 | # handle the users | |
1120 | # | |
1121 | # Don't create users if anonymous isn't allowed to register | |
1122 | create = 1 | |
1123 | anonid = self.db.user.lookup('anonymous') | |
1124 | if not (self.db.security.hasPermission('Register', anonid, 'user') | |
1125 | and self.db.security.hasPermission('Email Access', anonid)): | |
1126 | create = 0 | |
1127 | ||
1128 | # ok, now figure out who the author is - create a new user if the | |
1129 | # "create" flag is true | |
1130 | author = uidFromAddress(self.db, from_list[0], create=create) | |
1131 | ||
1132 | # if we're not recognised, and we don't get added as a user, then we | |
1133 | # must be anonymous | |
1134 | if not author: | |
1135 | author = anonid | |
1136 | ||
1137 | # make sure the author has permission to use the email interface | |
1138 | if not self.db.security.hasPermission('Email Access', author): | |
1139 | if author == anonid: | |
1140 | # we're anonymous and we need to be a registered user | |
1141 | from_address = from_list[0][1] | |
1142 | registration_info = "" | |
1143 | if self.db.security.hasPermission('Web Access', author) and \ | |
1144 | self.db.security.hasPermission('Register', anonid, 'user'): | |
1145 | tracker_web = self.instance.config.TRACKER_WEB | |
1146 | registration_info = """ Please register at: | |
1147 | ||
1148 | %(tracker_web)suser?template=register | |
1149 | ||
1150 | ...before sending mail to the tracker.""" % locals() | |
1151 | ||
1152 | raise Unauthorized, _(""" | |
1153 | You are not a registered user.%(registration_info)s | |
1154 | ||
1155 | Unknown address: %(from_address)s | |
1156 | """) % locals() | |
1157 | else: | |
1158 | # we're registered and we're _still_ not allowed access | |
1159 | raise Unauthorized, _( | |
1160 | 'You are not permitted to access this tracker.') | |
1161 | ||
1162 | # make sure they're allowed to edit or create this class of information | |
1163 | if nodeid: | |
1164 | if not self.db.security.hasPermission('Edit', author, classname, | |
1165 | itemid=nodeid): | |
1166 | raise Unauthorized, _( | |
1167 | 'You are not permitted to edit %(classname)s.') % locals() | |
1168 | else: | |
1169 | if not self.db.security.hasPermission('Create', author, classname): | |
1170 | raise Unauthorized, _( | |
1171 | 'You are not permitted to create %(classname)s.' | |
1172 | ) % locals() | |
1173 | ||
1174 | # the author may have been created - make sure the change is | |
1175 | # committed before we reopen the database | |
1176 | self.db.commit() | |
1177 | ||
1178 | # set the database user as the author | |
1179 | username = self.db.user.get(author, 'username') | |
1180 | self.db.setCurrentUser(username) | |
1181 | ||
1182 | # re-get the class with the new database connection | |
1183 | cl = self.db.getclass(classname) | |
1184 | ||
1185 | # now update the recipients list | |
1186 | recipients = [] | |
1187 | tracker_email = config['TRACKER_EMAIL'].lower() | |
1188 | for recipient in message.getaddrlist('to') + message.getaddrlist('cc'): | |
1189 | r = recipient[1].strip().lower() | |
1190 | if r == tracker_email or not r: | |
1191 | continue | |
1192 | ||
1193 | # look up the recipient - create if necessary (and we're | |
1194 | # allowed to) | |
1195 | recipient = uidFromAddress(self.db, recipient, create, **user_props) | |
1196 | ||
1197 | # if all's well, add the recipient to the list | |
1198 | if recipient: | |
1199 | recipients.append(recipient) | |
1200 | ||
1201 | # | |
1202 | # handle the subject argument list | |
1203 | # | |
1204 | # figure what the properties of this Class are | |
1205 | properties = cl.getprops() | |
1206 | props = {} | |
1207 | args = matches['args'] | |
1208 | argswhole = matches['argswhole'] | |
1209 | if args: | |
1210 | if sfxmode == 'none': | |
1211 | title += ' ' + argswhole | |
1212 | else: | |
1213 | errors, props = setPropArrayFromString(self, cl, args, nodeid) | |
1214 | # handle any errors parsing the argument list | |
1215 | if errors: | |
1216 | if sfxmode == 'strict': | |
1217 | errors = '\n- '.join(map(str, errors)) | |
1218 | raise MailUsageError, _(""" | |
1219 | There were problems handling your subject line argument list: | |
1220 | - %(errors)s | |
1221 | ||
1222 | Subject was: "%(subject)s" | |
1223 | """) % locals() | |
1224 | else: | |
1225 | title += ' ' + argswhole | |
1226 | ||
1227 | ||
1228 | # set the issue title to the subject | |
1229 | title = title.strip() | |
1230 | if (title and properties.has_key('title') and not | |
1231 | issue_props.has_key('title')): | |
1232 | issue_props['title'] = title | |
1233 | ||
1234 | # | |
1235 | # handle message-id and in-reply-to | |
1236 | # | |
1237 | messageid = message.getheader('message-id') | |
1238 | # generate a messageid if there isn't one | |
1239 | if not messageid: | |
1240 | messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(), | |
1241 | classname, nodeid, config['MAIL_DOMAIN']) | |
1242 | ||
1243 | # if they've enabled PGP processing then verify the signature | |
1244 | # or decrypt the message | |
1245 | ||
1246 | # if PGP_ROLES is specified the user must have a Role in the list | |
1247 | # or we will skip PGP processing | |
1248 | def pgp_role(): | |
1249 | if self.instance.config.PGP_ROLES: | |
1250 | return self.db.user.has_role(author, | |
1251 | iter_roles(self.instance.config.PGP_ROLES)) | |
1252 | else: | |
1253 | return True | |
1254 | ||
1255 | if self.instance.config.PGP_ENABLE and pgp_role(): | |
1256 | assert pyme, 'pyme is not installed' | |
1257 | # signed/encrypted mail must come from the primary address | |
1258 | author_address = self.db.user.get(author, 'address') | |
1259 | if self.instance.config.PGP_HOMEDIR: | |
1260 | os.environ['GNUPGHOME'] = self.instance.config.PGP_HOMEDIR | |
1261 | if message.pgp_signed(): | |
1262 | message.verify_signature(author_address) | |
1263 | elif message.pgp_encrypted(): | |
1264 | # replace message with the contents of the decrypted | |
1265 | # message for content extraction | |
1266 | # TODO: encrypted message handling is far from perfect | |
1267 | # bounces probably include the decrypted message, for | |
1268 | # instance :( | |
1269 | message = message.decrypt(author_address) | |
1270 | else: | |
1271 | raise MailUsageError, _(""" | |
1272 | This tracker has been configured to require all email be PGP signed or | |
1273 | encrypted.""") | |
1274 | # now handle the body - find the message | |
1275 | ig = self.instance.config.MAILGW_IGNORE_ALTERNATIVES | |
1276 | content, attachments = message.extract_content(ignore_alternatives = ig) | |
1277 | if content is None: | |
1278 | raise MailUsageError, _(""" | |
1279 | Roundup requires the submission to be plain text. The message parser could | |
1280 | not find a text/plain part to use. | |
1281 | """) | |
1282 | ||
1283 | # parse the body of the message, stripping out bits as appropriate | |
1284 | summary, content = parseContent(content, config=config) | |
1285 | content = content.strip() | |
1286 | ||
1287 | # | |
1288 | # handle the attachments | |
1289 | # | |
1290 | files = [] | |
1291 | if attachments and properties.has_key('files'): | |
1292 | for (name, mime_type, data) in attachments: | |
1293 | if not self.db.security.hasPermission('Create', author, 'file'): | |
1294 | raise Unauthorized, _( | |
1295 | 'You are not permitted to create files.') | |
1296 | if not name: | |
1297 | name = "unnamed" | |
1298 | try: | |
1299 | fileid = self.db.file.create(type=mime_type, name=name, | |
1300 | content=data, **file_props) | |
1301 | except exceptions.Reject: | |
1302 | pass | |
1303 | else: | |
1304 | files.append(fileid) | |
1305 | # allowed to attach the files to an existing node? | |
1306 | if nodeid and not self.db.security.hasPermission('Edit', author, | |
1307 | classname, 'files'): | |
1308 | raise Unauthorized, _( | |
1309 | 'You are not permitted to add files to %(classname)s.' | |
1310 | ) % locals() | |
1311 | ||
1312 | if nodeid: | |
1313 | # extend the existing files list | |
1314 | fileprop = cl.get(nodeid, 'files') | |
1315 | fileprop.extend(files) | |
1316 | props['files'] = fileprop | |
1317 | else: | |
1318 | # pre-load the files list | |
1319 | props['files'] = files | |
1320 | ||
1321 | # | |
1322 | # create the message if there's a message body (content) | |
1323 | # | |
1324 | if (content and properties.has_key('messages')): | |
1325 | if not self.db.security.hasPermission('Create', author, 'msg'): | |
1326 | raise Unauthorized, _( | |
1327 | 'You are not permitted to create messages.') | |
1328 | ||
1329 | try: | |
1330 | message_id = self.db.msg.create(author=author, | |
1331 | recipients=recipients, date=date.Date('.'), | |
1332 | summary=summary, content=content, files=files, | |
1333 | messageid=messageid, inreplyto=inreplyto, **msg_props) | |
1334 | except exceptions.Reject, error: | |
1335 | raise MailUsageError, _(""" | |
1336 | Mail message was rejected by a detector. | |
1337 | %(error)s | |
1338 | """) % locals() | |
1339 | # allowed to attach the message to the existing node? | |
1340 | if nodeid and not self.db.security.hasPermission('Edit', author, | |
1341 | classname, 'messages'): | |
1342 | raise Unauthorized, _( | |
1343 | 'You are not permitted to add messages to %(classname)s.' | |
1344 | ) % locals() | |
1345 | ||
1346 | if nodeid: | |
1347 | # add the message to the node's list | |
1348 | messages = cl.get(nodeid, 'messages') | |
1349 | messages.append(message_id) | |
1350 | props['messages'] = messages | |
1351 | else: | |
1352 | # pre-load the messages list | |
1353 | props['messages'] = [message_id] | |
1354 | ||
1355 | # | |
1356 | # perform the node change / create | |
1357 | # | |
1358 | try: | |
1359 | # merge the command line props defined in issue_props into | |
1360 | # the props dictionary because function(**props, **issue_props) | |
1361 | # is a syntax error. | |
1362 | for prop in issue_props.keys() : | |
1363 | if not props.has_key(prop) : | |
1364 | props[prop] = issue_props[prop] | |
1365 | ||
1366 | if nodeid: | |
1367 | # Check permissions for each property | |
1368 | for prop in props.keys(): | |
1369 | if not self.db.security.hasPermission('Edit', author, | |
1370 | classname, prop): | |
1371 | raise Unauthorized, _('You are not permitted to edit ' | |
1372 | 'property %(prop)s of class %(classname)s.') % locals() | |
1373 | cl.set(nodeid, **props) | |
1374 | else: | |
1375 | # Check permissions for each property | |
1376 | for prop in props.keys(): | |
1377 | if not self.db.security.hasPermission('Create', author, | |
1378 | classname, prop): | |
1379 | raise Unauthorized, _('You are not permitted to set ' | |
1380 | 'property %(prop)s of class %(classname)s.') % locals() | |
1381 | nodeid = cl.create(**props) | |
1382 | except (TypeError, IndexError, ValueError, exceptions.Reject), message: | |
1383 | raise MailUsageError, _(""" | |
1384 | There was a problem with the message you sent: | |
1385 | %(message)s | |
1386 | """) % locals() | |
1387 | ||
1388 | # commit the changes to the DB | |
1389 | self.db.commit() | |
1390 | ||
1391 | return nodeid | |
1392 | ||
1393 | ||
1394 | def setPropArrayFromString(self, cl, propString, nodeid=None): | |
1395 | ''' takes string of form prop=value,value;prop2=value | |
1396 | and returns (error, prop[..]) | |
1397 | ''' | |
1398 | props = {} | |
1399 | errors = [] | |
1400 | for prop in string.split(propString, ';'): | |
1401 | # extract the property name and value | |
1402 | try: | |
1403 | propname, value = prop.split('=') | |
1404 | except ValueError, message: | |
1405 | errors.append(_('not of form [arg=value,value,...;' | |
1406 | 'arg=value,value,...]')) | |
1407 | return (errors, props) | |
1408 | # convert the value to a hyperdb-usable value | |
1409 | propname = propname.strip() | |
1410 | try: | |
1411 | props[propname] = hyperdb.rawToHyperdb(self.db, cl, nodeid, | |
1412 | propname, value) | |
1413 | except hyperdb.HyperdbValueError, message: | |
1414 | errors.append(str(message)) | |
1415 | return errors, props | |
1416 | ||
1417 | ||
1418 | def extractUserFromList(userClass, users): | |
1419 | '''Given a list of users, try to extract the first non-anonymous user | |
1420 | and return that user, otherwise return None | |
1421 | ''' | |
1422 | if len(users) > 1: | |
1423 | for user in users: | |
1424 | # make sure we don't match the anonymous or admin user | |
1425 | if userClass.get(user, 'username') in ('admin', 'anonymous'): | |
1426 | continue | |
1427 | # first valid match will do | |
1428 | return user | |
1429 | # well, I guess we have no choice | |
1430 | return user[0] | |
1431 | elif users: | |
1432 | return users[0] | |
1433 | return None | |
1434 | ||
1435 | ||
1436 | def uidFromAddress(db, address, create=1, **user_props): | |
1437 | ''' address is from the rfc822 module, and therefore is (name, addr) | |
1438 | ||
1439 | user is created if they don't exist in the db already | |
1440 | user_props may supply additional user information | |
1441 | ''' | |
1442 | (realname, address) = address | |
1443 | ||
1444 | # try a straight match of the address | |
1445 | user = extractUserFromList(db.user, db.user.stringFind(address=address)) | |
1446 | if user is not None: | |
1447 | return user | |
1448 | ||
1449 | # try the user alternate addresses if possible | |
1450 | props = db.user.getprops() | |
1451 | if props.has_key('alternate_addresses'): | |
1452 | users = db.user.filter(None, {'alternate_addresses': address}) | |
1453 | user = extractUserFromList(db.user, users) | |
1454 | if user is not None: | |
1455 | return user | |
1456 | ||
1457 | # try to match the username to the address (for local | |
1458 | # submissions where the address is empty) | |
1459 | user = extractUserFromList(db.user, db.user.stringFind(username=address)) | |
1460 | ||
1461 | # couldn't match address or username, so create a new user | |
1462 | if create: | |
1463 | # generate a username | |
1464 | if '@' in address: | |
1465 | username = address.split('@')[0] | |
1466 | else: | |
1467 | username = address | |
1468 | trying = username | |
1469 | n = 0 | |
1470 | while 1: | |
1471 | try: | |
1472 | # does this username exist already? | |
1473 | db.user.lookup(trying) | |
1474 | except KeyError: | |
1475 | break | |
1476 | n += 1 | |
1477 | trying = username + str(n) | |
1478 | ||
1479 | # create! | |
1480 | try: | |
1481 | return db.user.create(username=trying, address=address, | |
1482 | realname=realname, roles=db.config.NEW_EMAIL_USER_ROLES, | |
1483 | password=password.Password(password.generatePassword()), | |
1484 | **user_props) | |
1485 | except exceptions.Reject: | |
1486 | return 0 | |
1487 | else: | |
1488 | return 0 | |
1489 | ||
1490 | def parseContent(content, keep_citations=None, keep_body=None, config=None): | |
1491 | """Parse mail message; return message summary and stripped content | |
1492 | ||
1493 | The message body is divided into sections by blank lines. | |
1494 | Sections where the second and all subsequent lines begin with a ">" | |
1495 | or "|" character are considered "quoting sections". The first line of | |
1496 | the first non-quoting section becomes the summary of the message. | |
1497 | ||
1498 | Arguments: | |
1499 | ||
1500 | keep_citations: declared for backward compatibility. | |
1501 | If omitted or None, use config["MAILGW_KEEP_QUOTED_TEXT"] | |
1502 | ||
1503 | keep_body: declared for backward compatibility. | |
1504 | If omitted or None, use config["MAILGW_LEAVE_BODY_UNCHANGED"] | |
1505 | ||
1506 | config: tracker configuration object. | |
1507 | If omitted or None, use default configuration. | |
1508 | ||
1509 | """ | |
1510 | if config is None: | |
1511 | config = configuration.CoreConfig() | |
1512 | if keep_citations is None: | |
1513 | keep_citations = config["MAILGW_KEEP_QUOTED_TEXT"] | |
1514 | if keep_body is None: | |
1515 | keep_body = config["MAILGW_LEAVE_BODY_UNCHANGED"] | |
1516 | eol = config["MAILGW_EOL_RE"] | |
1517 | signature = config["MAILGW_SIGN_RE"] | |
1518 | original_msg = config["MAILGW_ORIGMSG_RE"] | |
1519 | ||
1520 | # strip off leading carriage-returns / newlines | |
1521 | i = 0 | |
1522 | for i in range(len(content)): | |
1523 | if content[i] not in '\r\n': | |
1524 | break | |
1525 | if i > 0: | |
1526 | sections = config["MAILGW_BLANKLINE_RE"].split(content[i:]) | |
1527 | else: | |
1528 | sections = config["MAILGW_BLANKLINE_RE"].split(content) | |
1529 | ||
1530 | # extract out the summary from the message | |
1531 | summary = '' | |
1532 | l = [] | |
1533 | for section in sections: | |
1534 | #section = section.strip() | |
1535 | if not section: | |
1536 | continue | |
1537 | lines = eol.split(section) | |
1538 | if (lines[0] and lines[0][0] in '>|') or (len(lines) > 1 and | |
1539 | lines[1] and lines[1][0] in '>|'): | |
1540 | # see if there's a response somewhere inside this section (ie. | |
1541 | # no blank line between quoted message and response) | |
1542 | for line in lines[1:]: | |
1543 | if line and line[0] not in '>|': | |
1544 | break | |
1545 | else: | |
1546 | # we keep quoted bits if specified in the config | |
1547 | if keep_citations: | |
1548 | l.append(section) | |
1549 | continue | |
1550 | # keep this section - it has reponse stuff in it | |
1551 | lines = lines[lines.index(line):] | |
1552 | section = '\n'.join(lines) | |
1553 | # and while we're at it, use the first non-quoted bit as | |
1554 | # our summary | |
1555 | summary = section | |
1556 | ||
1557 | if not summary: | |
1558 | # if we don't have our summary yet use the first line of this | |
1559 | # section | |
1560 | summary = section | |
1561 | elif signature.match(lines[0]) and 2 <= len(lines) <= 10: | |
1562 | # lose any signature | |
1563 | break | |
1564 | elif original_msg.match(lines[0]): | |
1565 | # ditch the stupid Outlook quoting of the entire original message | |
1566 | break | |
1567 | ||
1568 | # and add the section to the output | |
1569 | l.append(section) | |
1570 | ||
1571 | # figure the summary - find the first sentence-ending punctuation or the | |
1572 | # first whole line, whichever is longest | |
1573 | sentence = re.search(r'^([^!?\.]+[!?\.])', summary) | |
1574 | if sentence: | |
1575 | sentence = sentence.group(1) | |
1576 | else: | |
1577 | sentence = '' | |
1578 | first = eol.split(summary)[0] | |
1579 | summary = max(sentence, first) | |
1580 | ||
1581 | # Now reconstitute the message content minus the bits we don't care | |
1582 | # about. | |
1583 | if not keep_body: | |
1584 | content = '\n\n'.join(l) | |
1585 | ||
1586 | return summary, content | |
1587 | ||
1588 | # vim: set filetype=python sts=4 sw=4 et si : |