mailpipe: skip `.gitignore` files in Maildir mailboxes.
[pygrader.git] / pygrader / mailpipe.py
1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of pygrader.
4 #
5 # pygrader is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # pygrader is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # pygrader.  If not, see <http://www.gnu.org/licenses/>.
16
17 "Incoming email processing."
18
19 from __future__ import absolute_import
20
21 from email import message_from_file as _message_from_file
22 from email.header import decode_header as _decode_header
23 from email.mime.text import MIMEText as _MIMEText
24 import mailbox as _mailbox
25 import re as _re
26 import sys as _sys
27
28 import pgp_mime as _pgp_mime
29 from lxml import etree as _etree
30
31 from . import LOG as _LOG
32 from .email import construct_email as _construct_email
33 from .email import construct_response as _construct_response
34 from .model.person import Person as _Person
35
36 from .handler import InvalidMessage as _InvalidMessage
37 from .handler import InvalidSubjectMessage as _InvalidSubjectMessage
38 from .handler import Response as _Response
39 from .handler import UnsignedMessage as _UnsignedMessage
40 from .handler.get import InvalidStudent as _InvalidStudent
41 from .handler.get import run as _handle_get
42 from .handler.submission import InvalidAssignment as _InvalidAssignment
43 from .handler.submission import run as _handle_submission
44
45
46 _TAG_REGEXP = _re.compile('^.*\[([^]]*)\].*$')
47
48
49 class NoReturnPath (_InvalidMessage):
50     def __init__(self, address, **kwargs):
51         if 'error' not in kwargs:
52             kwargs['error'] = 'no Return-Path'
53         super(NoReturnPath, self).__init__(**kwargs)
54
55
56 class UnregisteredAddress (_InvalidMessage):
57     def __init__(self, address, **kwargs):
58         if 'error' not in kwargs:
59             kwargs['error'] = 'unregistered address {}'.format(address)
60         super(UnregisteredAddress, self).__init__(**kwargs)
61         self.address = address
62
63
64 class AmbiguousAddress (_InvalidMessage):
65     def __init__(self, address, people, **kwargs):
66         if 'error' not in kwargs:
67             kwargs['error'] = 'ambiguous address {}'.format(address)
68         super(AmbiguousAddress, self).__init__(**kwargs)
69         self.address = address
70         self.people = people
71
72
73 class SubjectlessMessage (_InvalidSubjectMessage):
74     def __init__(self, **kwargs):
75         if 'error' not in kwargs:
76             kwargs['error'] = 'no subject'
77         super(SubjectlessMessage, self).__init__(**kwargs)
78
79
80 class InvalidHandlerMessage (_InvalidSubjectMessage):
81     def __init__(self, target=None, handlers=None, **kwargs):
82         if 'error' not in kwargs:
83             kwargs['error'] = 'no handler for {!r}'.format(target)
84         super(InvalidHandlerMessage, self).__init__(**kwargs)
85         self.target = target
86         self.handlers = handlers
87
88
89 def mailpipe(basedir, course, stream=None, mailbox=None, input_=None,
90              output=None, continue_after_invalid_message=False, max_late=0,
91              handlers={
92         'get': _handle_get,
93         'submit': _handle_submission,
94         }, respond=None, dry_run=False, **kwargs):
95     """Run from procmail to sort incomming submissions
96
97     For example, you can setup your ``.procmailrc`` like this::
98
99       SHELL=/bin/sh
100       DEFAULT=$MAIL
101       MAILDIR=$HOME/mail
102       DEFAULT=$MAILDIR/mbox
103       LOGFILE=$MAILDIR/procmail.log
104       #VERBOSE=yes
105       PYGRADE_MAILPIPE="pg.py -d $HOME/grades/phys160"
106
107       # Grab all incoming homeworks emails.  This rule eats matching emails
108       # (i.e. no further procmail processing).
109       :0
110       * ^Subject:.*\[phys160:submit]
111       | "$PYGRADE_MAILPIPE" mailpipe
112
113     If you don't want procmail to eat the message, you can use the
114     ``c`` flag (carbon copy) by starting your rule off with ``:0 c``.
115
116     >>> from io import StringIO
117     >>> from pgp_mime.email import encodedMIMEText
118     >>> from .handler import InvalidMessage, Response
119     >>> from .test.course import StubCourse
120
121     >>> course = StubCourse()
122     >>> def respond(message):
123     ...     print('respond with:\\n{}'.format(message.as_string()))
124     >>> def process(message):
125     ...     mailpipe(
126     ...         basedir=course.basedir, course=course.course,
127     ...         stream=StringIO(message.as_string()),
128     ...         output=course.mailbox,
129     ...         continue_after_invalid_message=True,
130     ...         respond=respond)
131     >>> message = encodedMIMEText('The answer is 42.')
132     >>> message['Message-ID'] = '<123.456@home.net>'
133     >>> message['Received'] = (
134     ...     'from smtp.home.net (smtp.home.net [123.456.123.456]) '
135     ...     'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
136     ...     'for <wking@tremily.us>; Sun, 09 Oct 2011 11:50:46 -0400 (EDT)')
137     >>> message['From'] = 'Billy B <bb@greyhavens.net>'
138     >>> message['To'] = 'phys101 <phys101@tower.edu>'
139     >>> message['Subject'] = '[submit] assignment 1'
140
141     Messages with unrecognized ``Return-Path``\s are silently dropped:
142
143     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
144     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
145     course.conf
146     mail
147     mail/cur
148     mail/new
149     mail/tmp
150
151     Response to a message from an unregistered person:
152
153     >>> message['Return-Path'] = '<invalid.return.path@home.net>'
154     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
155     respond with:
156     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
157     MIME-Version: 1.0
158     Content-Disposition: inline
159     Date: ...
160     From: Robot101 <phys101@tower.edu>
161     Reply-to: Robot101 <phys101@tower.edu>
162     To: "invalid.return.path@home.net" <invalid.return.path@home.net>
163     Subject: unregistered address invalid.return.path@home.net
164     <BLANKLINE>
165     --===============...==
166     Content-Type: multipart/mixed; boundary="===============...=="
167     MIME-Version: 1.0
168     <BLANKLINE>
169     --===============...==
170     Content-Type: text/plain; charset="us-ascii"
171     MIME-Version: 1.0
172     Content-Transfer-Encoding: 7bit
173     Content-Disposition: inline
174     <BLANKLINE>
175     invalid.return.path@home.net,
176     <BLANKLINE>
177     Your email address is not registered with pygrader for
178     Physics 101.  If you feel it should be, contact your professor
179     or TA.
180     <BLANKLINE>
181     Yours,
182     phys-101 robot
183     <BLANKLINE>
184     --===============...==
185     Content-Type: message/rfc822
186     MIME-Version: 1.0
187     <BLANKLINE>
188     Content-Type: text/plain; charset="us-ascii"
189     MIME-Version: 1.0
190     Content-Transfer-Encoding: 7bit
191     Content-Disposition: inline
192     Message-ID: <123.456@home.net>
193     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Sun, 09 Oct 2011 11:50:46 -0400 (EDT)
194     From: Billy B <bb@greyhavens.net>
195     To: phys101 <phys101@tower.edu>
196     Subject: [submit] assignment 1
197     Return-Path: <invalid.return.path@home.net>
198     <BLANKLINE>
199     The answer is 42.
200     --===============...==--
201     --===============...==
202     MIME-Version: 1.0
203     Content-Transfer-Encoding: 7bit
204     Content-Description: OpenPGP digital signature
205     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
206     <BLANKLINE>
207     -----BEGIN PGP SIGNATURE-----
208     Version: GnuPG v2.0.19 (GNU/Linux)
209     <BLANKLINE>
210     ...
211     -----END PGP SIGNATURE-----
212     <BLANKLINE>
213     --===============...==--
214
215     If we add a valid ``Return-Path``, we get the expected delivery:
216
217     >>> del message['Return-Path']
218     >>> message['Return-Path'] = '<bb@greyhavens.net>'
219     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
220     respond with:
221     Content-Type: text/plain; charset="us-ascii"
222     MIME-Version: 1.0
223     Content-Disposition: inline
224     Content-Transfer-Encoding: 7bit
225     <BLANKLINE>
226     Billy,
227     <BLANKLINE>
228     We received your submission for Assignment 1 on Sun, 09 Oct 2011 15:50:46 -0000.
229     <BLANKLINE>
230     Yours,
231     phys-101 robot
232     <BLANKLINE>
233
234     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
235     Bilbo_Baggins
236     Bilbo_Baggins/Assignment_1
237     Bilbo_Baggins/Assignment_1/mail
238     Bilbo_Baggins/Assignment_1/mail/cur
239     Bilbo_Baggins/Assignment_1/mail/new
240     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
241     Bilbo_Baggins/Assignment_1/mail/tmp
242     course.conf
243     mail
244     mail/cur
245     mail/new
246     mail/new/...
247     mail/tmp
248
249     The last ``Received`` is used to timestamp the message:
250
251     >>> del message['Message-ID']
252     >>> message['Message-ID'] = '<abc.def@home.net>'
253     >>> del message['Received']
254     >>> message['Received'] = (
255     ...     'from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) '
256     ...     'by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 '
257     ...     'for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)')
258     >>> message['Received'] = (
259     ...     'from smtp.home.net (smtp.home.net [123.456.123.456]) '
260     ...     'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
261     ...     'for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)')
262     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
263     respond with:
264     Content-Type: text/plain; charset="us-ascii"
265     MIME-Version: 1.0
266     Content-Disposition: inline
267     Content-Transfer-Encoding: 7bit
268     <BLANKLINE>
269     Billy,
270     <BLANKLINE>
271     We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
272     <BLANKLINE>
273     Yours,
274     phys-101 robot
275     <BLANKLINE>
276     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
277     Bilbo_Baggins
278     Bilbo_Baggins/Assignment_1
279     Bilbo_Baggins/Assignment_1/late
280     Bilbo_Baggins/Assignment_1/mail
281     Bilbo_Baggins/Assignment_1/mail/cur
282     Bilbo_Baggins/Assignment_1/mail/new
283     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
284     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
285     Bilbo_Baggins/Assignment_1/mail/tmp
286     course.conf
287     mail
288     mail/cur
289     mail/new
290     mail/new/...
291     mail/new/...
292     mail/tmp
293
294     You can send receipts to the acknowledge incoming messages, which
295     includes warnings about dropped messages (except for messages
296     without ``Return-Path`` and messages where the ``Return-Path``
297     email belongs to multiple ``People``.  The former should only
298     occur with malicious emails, and the latter with improper pygrader
299     configurations).
300
301     Response to a successful submission:
302
303     >>> del message['Message-ID']
304     >>> message['Message-ID'] = '<hgi.jlk@home.net>'
305     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
306     respond with:
307     Content-Type: text/plain; charset="us-ascii"
308     MIME-Version: 1.0
309     Content-Disposition: inline
310     Content-Transfer-Encoding: 7bit
311     <BLANKLINE>
312     Billy,
313     <BLANKLINE>
314     We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
315     <BLANKLINE>
316     Yours,
317     phys-101 robot
318     <BLANKLINE>
319
320     Response to a submission on an unsubmittable assignment:
321
322     >>> del message['Subject']
323     >>> message['Subject'] = '[submit] attendance 1'
324     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
325     respond with:
326     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
327     MIME-Version: 1.0
328     Content-Disposition: inline
329     Date: ...
330     From: Robot101 <phys101@tower.edu>
331     Reply-to: Robot101 <phys101@tower.edu>
332     To: Bilbo Baggins <bb@shire.org>
333     Subject: Received invalid Attendance 1 submission
334     <BLANKLINE>
335     --===============...==
336     Content-Type: multipart/mixed; boundary="===============...=="
337     MIME-Version: 1.0
338     <BLANKLINE>
339     --===============...==
340     Content-Type: text/plain; charset="us-ascii"
341     MIME-Version: 1.0
342     Content-Transfer-Encoding: 7bit
343     Content-Disposition: inline
344     <BLANKLINE>
345     Billy,
346     <BLANKLINE>
347     We received your submission for Attendance 1, but you are not
348     allowed to submit that assignment via email.
349     <BLANKLINE>
350     Yours,
351     phys-101 robot
352     <BLANKLINE>
353     --===============...==
354     Content-Type: message/rfc822
355     MIME-Version: 1.0
356     <BLANKLINE>
357     Content-Type: text/plain; charset="us-ascii"
358     MIME-Version: 1.0
359     Content-Transfer-Encoding: 7bit
360     Content-Disposition: inline
361     From: Billy B <bb@greyhavens.net>
362     To: phys101 <phys101@tower.edu>
363     Return-Path: <bb@greyhavens.net>
364     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
365     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
366     Message-ID: <hgi.jlk@home.net>
367     Subject: [submit] attendance 1
368     <BLANKLINE>
369     The answer is 42.
370     --===============...==--
371     --===============...==
372     MIME-Version: 1.0
373     Content-Transfer-Encoding: 7bit
374     Content-Description: OpenPGP digital signature
375     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
376     <BLANKLINE>
377     -----BEGIN PGP SIGNATURE-----
378     Version: GnuPG v2.0.19 (GNU/Linux)
379     <BLANKLINE>
380     ...
381     -----END PGP SIGNATURE-----
382     <BLANKLINE>
383     --===============...==--
384
385     Response to a bad subject:
386
387     >>> del message['Subject']
388     >>> message['Subject'] = 'need help for the first homework'
389     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
390     respond with:
391     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
392     MIME-Version: 1.0
393     Content-Disposition: inline
394     Date: ...
395     From: Robot101 <phys101@tower.edu>
396     Reply-to: Robot101 <phys101@tower.edu>
397     To: Bilbo Baggins <bb@shire.org>
398     Subject: no tag in 'need help for the first homework'
399     <BLANKLINE>
400     --===============...==
401     Content-Type: multipart/mixed; boundary="===============...=="
402     MIME-Version: 1.0
403     <BLANKLINE>
404     --===============...==
405     Content-Type: text/plain; charset="us-ascii"
406     MIME-Version: 1.0
407     Content-Transfer-Encoding: 7bit
408     Content-Disposition: inline
409     <BLANKLINE>
410     Billy,
411     <BLANKLINE>
412     We received an email message from you with an invalid
413     subject.
414     <BLANKLINE>
415     Yours,
416     phys-101 robot
417     <BLANKLINE>
418     --===============...==
419     Content-Type: message/rfc822
420     MIME-Version: 1.0
421     <BLANKLINE>
422     Content-Type: text/plain; charset="us-ascii"
423     MIME-Version: 1.0
424     Content-Transfer-Encoding: 7bit
425     Content-Disposition: inline
426     From: Billy B <bb@greyhavens.net>
427     To: phys101 <phys101@tower.edu>
428     Return-Path: <bb@greyhavens.net>
429     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
430     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
431     Message-ID: <hgi.jlk@home.net>
432     Subject: need help for the first homework
433     <BLANKLINE>
434     The answer is 42.
435     --===============...==--
436     --===============...==
437     MIME-Version: 1.0
438     Content-Transfer-Encoding: 7bit
439     Content-Description: OpenPGP digital signature
440     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
441     <BLANKLINE>
442     -----BEGIN PGP SIGNATURE-----
443     Version: GnuPG v2.0.19 (GNU/Linux)
444     <BLANKLINE>
445     ...
446     -----END PGP SIGNATURE-----
447     <BLANKLINE>
448     --===============...==--
449
450     Response to a missing subject:
451
452     >>> del message['Subject']
453     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
454     respond with:
455     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
456     MIME-Version: 1.0
457     Content-Disposition: inline
458     Date: ...
459     From: Robot101 <phys101@tower.edu>
460     Reply-to: Robot101 <phys101@tower.edu>
461     To: Bilbo Baggins <bb@shire.org>
462     Subject: no subject in <hgi.jlk@home.net>
463     <BLANKLINE>
464     --===============...==
465     Content-Type: multipart/mixed; boundary="===============...=="
466     MIME-Version: 1.0
467     <BLANKLINE>
468     --===============...==
469     Content-Type: text/plain; charset="us-ascii"
470     MIME-Version: 1.0
471     Content-Transfer-Encoding: 7bit
472     Content-Disposition: inline
473     <BLANKLINE>
474     Billy,
475     <BLANKLINE>
476     We received an email message from you without a subject.
477     <BLANKLINE>
478     Yours,
479     phys-101 robot
480     <BLANKLINE>
481     --===============...==
482     Content-Type: message/rfc822
483     MIME-Version: 1.0
484     <BLANKLINE>
485     Content-Type: text/plain; charset="us-ascii"
486     MIME-Version: 1.0
487     Content-Transfer-Encoding: 7bit
488     Content-Disposition: inline
489     From: Billy B <bb@greyhavens.net>
490     To: phys101 <phys101@tower.edu>
491     Return-Path: <bb@greyhavens.net>
492     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
493     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
494     Message-ID: <hgi.jlk@home.net>
495     <BLANKLINE>
496     The answer is 42.
497     --===============...==--
498     --===============...==
499     MIME-Version: 1.0
500     Content-Transfer-Encoding: 7bit
501     Content-Description: OpenPGP digital signature
502     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
503     <BLANKLINE>
504     -----BEGIN PGP SIGNATURE-----
505     Version: GnuPG v2.0.19 (GNU/Linux)
506     <BLANKLINE>
507     ...
508     -----END PGP SIGNATURE-----
509     <BLANKLINE>
510     --===============...==--
511
512     Response to an insecure message from a person with a PGP key:
513
514     >>> student = course.course.person(email='bb@greyhavens.net')
515     >>> student.pgp_key = '4332B6E3'
516     >>> del message['Subject']
517     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
518     respond with:
519     Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; micalg="pgp-sha1"; boundary="===============...=="
520     MIME-Version: 1.0
521     Content-Disposition: inline
522     Date: ...
523     From: Robot101 <phys101@tower.edu>
524     Reply-to: Robot101 <phys101@tower.edu>
525     To: Bilbo Baggins <bb@shire.org>
526     Subject: unsigned message <hgi.jlk@home.net>
527     <BLANKLINE>
528     --===============...==
529     MIME-Version: 1.0
530     Content-Transfer-Encoding: 7bit
531     Content-Type: application/pgp-encrypted; charset="us-ascii"
532     <BLANKLINE>
533     Version: 1
534     <BLANKLINE>
535     --===============...==
536     MIME-Version: 1.0
537     Content-Transfer-Encoding: 7bit
538     Content-Description: OpenPGP encrypted message
539     Content-Type: application/octet-stream; name="encrypted.asc"; charset="us-ascii"
540     <BLANKLINE>
541     -----BEGIN PGP MESSAGE-----
542     Version: GnuPG v2.0.19 (GNU/Linux)
543     <BLANKLINE>
544     ...
545     -----END PGP MESSAGE-----
546     <BLANKLINE>
547     --===============...==--
548
549     >>> course.cleanup()
550     """
551     if stream is None:
552         stream = _sys.stdin
553     for original,message,person,subject,target in _load_messages(
554         course=course, stream=stream, mailbox=mailbox, input_=input_,
555         output=output, dry_run=dry_run,
556         continue_after_invalid_message=continue_after_invalid_message,
557         respond=respond):
558         try:
559             handler = _get_handler(handlers=handlers, target=target)
560             handler(
561                 basedir=basedir, course=course, message=message,
562                 person=person, subject=subject,
563                 max_late=max_late, dry_run=dry_run)
564         except _InvalidMessage as error:
565             error.course = course
566             error.message = original
567             if person is not None and not hasattr(error, 'person'):
568                 error.person = person
569             if subject is not None and not hasattr(error, 'subject'):
570                 error.subject = subject
571             if target is not None and not hasattr(error, 'target'):
572                 error.target = target
573             _LOG.warn('invalid message {}'.format(error.message_id()))
574             if not continue_after_invalid_message:
575                 raise
576             if respond:
577                 response = _get_error_response(error)
578                 respond(response)
579         except _Response as response:
580             if respond:
581                 author = course.robot
582                 target = person
583                 msg = response.message
584                 if isinstance(response.message, _MIMEText):
585                     # Manipulate body (based on pgp_mime.append_text)
586                     original_encoding = msg.get_charset().input_charset
587                     original_payload = str(
588                         msg.get_payload(decode=True), original_encoding)
589                     new_payload = (
590                         '{},\n\n'
591                         '{}\n\n'
592                         'Yours,\n'
593                         '{}\n').format(
594                         target.alias(), original_payload, author.alias())
595                     new_encoding = _pgp_mime.guess_encoding(new_payload)
596                     if msg.get('content-transfer-encoding', None):
597                         # clear CTE so set_payload will set it properly
598                         del msg['content-transfer-encoding']
599                     msg.set_payload(new_payload, new_encoding)
600                 subject = msg['Subject']
601                 del msg['Subject']
602                 assert subject is not None, msg
603                 msg = _construct_email(
604                     author=author, targets=[person], subject=subject,
605                     message=msg)
606                 respond(response.message)
607
608
609 def _load_messages(course, stream, mailbox=None, input_=None, output=None,
610                    continue_after_invalid_message=False, respond=None,
611                    dry_run=False):
612     if mailbox is None:
613         mbox = None
614         messages = [(None,_message_from_file(stream))]
615         if output is not None:
616             ombox = _mailbox.Maildir(output, factory=None, create=True)
617     elif mailbox == 'mbox':
618         mbox = _mailbox.mbox(input_, factory=None, create=False)
619         messages = mbox.items()
620         if output is not None:
621             ombox = _mailbox.mbox(output, factory=None, create=True)
622     elif mailbox == 'maildir':
623         mbox = _mailbox.Maildir(input_, factory=None, create=False)
624         messages = []
625         for key,msg in mbox.items():
626             subpath = mbox._lookup(key)
627             if subpath.endswith('.gitignore'):
628                 _LOG.debug('skipping non-message {}'.format(subpath))
629                 continue
630             messages.append((key, msg))
631         if output is not None:
632             ombox = _mailbox.Maildir(output, factory=None, create=True)
633     else:
634         raise ValueError(mailbox)
635     for key,msg in messages:
636         try:
637             ret = _parse_message(course=course, message=msg)
638         except _InvalidMessage as error:
639             error.message = msg
640             _LOG.warn('invalid message {}'.format(error.message_id()))
641             if not continue_after_invalid_message:
642                 raise
643             if respond:
644                 response = _get_error_response(error)
645                 if response is not None:
646                     respond(response)
647             continue
648         if output is not None and dry_run is False:
649             # move message from input mailbox to output mailbox
650             ombox.add(msg)
651             if mbox is not None:
652                 del mbox[key]
653         yield ret
654
655 def _parse_message(course, message):
656     """Parse an incoming email and respond if neccessary.
657
658     Return ``(msg, person, assignment, time)`` on successful parsing.
659     Return ``None`` on failure.
660     """
661     original = message
662     person = subject = target = None
663     try:
664         person = _get_message_person(course=course, message=message)
665         if person.pgp_key:
666             message = _get_decoded_message(
667                 course=course, message=message, person=person)
668         subject = _get_message_subject(message=message)
669         target = _get_message_target(subject=subject)
670     except _InvalidMessage as error:
671         error.course = course
672         error.message = original
673         if person is not None and not hasattr(error, 'person'):
674             error.person = person
675         if subject is not None and not hasattr(error, 'subject'):
676             error.subject = subject
677         if target is not None and not hasattr(error, 'target'):
678             error.target = target
679         raise
680     return (original, message, person, subject, target)
681
682 def _get_message_person(course, message):
683     sender = message['Return-Path']  # RFC 822
684     if sender is None:
685         raise NoReturnPath(message)
686     sender = sender[1:-1]  # strip wrapping '<' and '>'
687     people = list(course.find_people(email=sender))
688     if len(people) == 0:
689         raise UnregisteredAddress(message=message, address=sender)
690     if len(people) > 1:
691         raise AmbiguousAddress(message=message, address=sender, people=people)
692     return people[0]
693
694 def _get_decoded_message(course, message, person):
695     msg = _get_verified_message(message, person.pgp_key)
696     if msg is None:
697         raise _UnsignedMessage(message=message)
698     return msg
699
700 def _get_message_subject(message):
701     """
702     >>> from email.header import Header
703     >>> from pgp_mime.email import encodedMIMEText
704     >>> message = encodedMIMEText('The answer is 42.')
705     >>> message['Message-ID'] = 'msg-id'
706     >>> _get_message_subject(message=message)
707     Traceback (most recent call last):
708       ...
709     pygrader.mailpipe.SubjectlessMessage: no subject
710     >>> del message['Subject']
711     >>> subject = Header('unicode part', 'utf-8')
712     >>> subject.append('-ascii part', 'ascii')
713     >>> message['Subject'] = subject.encode()
714     >>> _get_message_subject(message=message)
715     'unicode part-ascii part'
716     >>> del message['Subject']
717     >>> message['Subject'] = 'clean subject'
718     >>> _get_message_subject(message=message)
719     'clean subject'
720     """
721     if message['Subject'] is None:
722         raise SubjectlessMessage(subject=None, message=message)
723
724     parts = _decode_header(message['Subject'])
725     part_strings = []
726     for string,encoding in parts:
727         if encoding is None:
728             encoding = 'ascii'
729         if not isinstance(string, str):
730             string = str(string, encoding)
731         part_strings.append(string)
732     subject = ''.join(part_strings)
733     _LOG.debug('decoded header {} -> {}'.format(parts[0], subject))
734     return subject.lower().replace('#', '')
735
736 def _get_message_target(subject):
737     """
738     >>> _get_message_target(subject='no tag')
739     Traceback (most recent call last):
740       ...
741     pygrader.handler.InvalidSubjectMessage: no tag in 'no tag'
742     >>> _get_message_target(subject='[] empty tag')
743     Traceback (most recent call last):
744       ...
745     pygrader.handler.InvalidSubjectMessage: empty tag in '[] empty tag'
746     >>> _get_message_target(subject='[abc] empty tag')
747     'abc'
748     >>> _get_message_target(subject='[phys160:abc] empty tag')
749     'abc'
750     """
751     match = _TAG_REGEXP.match(subject)
752     if match is None:
753         raise _InvalidSubjectMessage(
754             subject=subject, error='no tag in {!r}'.format(subject))
755     tag = match.group(1)
756     if tag == '':
757         raise _InvalidSubjectMessage(
758             subject=subject, error='empty tag in {!r}'.format(subject))
759     target = tag.rsplit(':', 1)[-1]
760     _LOG.debug('extracted target {} -> {}'.format(subject, target))
761     return target
762
763 def _get_handler(handlers, target):
764     try:
765         handler = handlers[target]
766     except KeyError as error:
767         raise InvalidHandlerMessage(
768             target=target, handlers=handlers) from error
769     return handler
770
771 def _get_verified_message(message, pgp_key):
772     """
773
774     >>> from pgp_mime import sign, encodedMIMEText
775
776     The student composes a message...
777
778     >>> message = encodedMIMEText('1.23 joules')
779
780     ... and signs it (with the pgp-mime test key).
781
782     >>> signed = sign(message, signers=['pgp-mime-test'])
783
784     As it is being delivered, the message picks up extra headers.
785
786     >>> signed['Message-ID'] = '<01234567@home.net>'
787     >>> signed['Received'] = 'from smtp.mail.uu.edu ...'
788     >>> signed['Received'] = 'from smtp.home.net ...'
789
790     We check that the message is signed, and that it is signed by the
791     appropriate key.
792
793     >>> signed.authenticated
794     Traceback (most recent call last):
795       ...
796     AttributeError: 'MIMEMultipart' object has no attribute 'authenticated'
797     >>> our_message = _get_verified_message(signed, pgp_key='4332B6E3')
798     >>> print(our_message.as_string())  # doctest: +REPORT_UDIFF
799     Content-Type: text/plain; charset="us-ascii"
800     MIME-Version: 1.0
801     Content-Transfer-Encoding: 7bit
802     Content-Disposition: inline
803     Message-ID: <01234567@home.net>
804     Received: from smtp.mail.uu.edu ...
805     Received: from smtp.home.net ...
806     <BLANKLINE>
807     1.23 joules
808     >>> our_message.authenticated
809     True
810
811     If it is signed, but not by the right key, we get ``None``.
812
813     >>> print(_get_verified_message(signed, pgp_key='01234567'))
814     None
815
816     If it is not signed at all, we get ``None``.
817
818     >>> print(_get_verified_message(message, pgp_key='4332B6E3'))
819     None
820     """
821     mid = message['message-id']
822     try:
823         decrypted,verified,result = _pgp_mime.verify(message=message)
824     except (ValueError, AssertionError):
825         _LOG.warning('could not verify {} (not signed?)'.format(mid))
826         return None
827     _LOG.debug(str(result, 'utf-8'))
828     tree = _etree.fromstring(result.replace(b'\x00', b''))
829     match = None
830     for signature in tree.findall('.//signature'):
831         for fingerprint in signature.iterchildren('fpr'):
832             if fingerprint.text.endswith(pgp_key):
833                 match = signature
834                 break
835     if match is None:
836         _LOG.warning('{} is not signed by the expected key'.format(mid))
837         return None
838     if not verified:
839         sumhex = list(signature.iterchildren('summary'))[0].get('value')
840         summary = int(sumhex, 16)
841         if summary != 0:
842             _LOG.warning('{} has an unverified signature'.format(mid))
843             return None
844         # otherwise, we may have an untrusted key.  We'll count that
845         # as verified here, because the caller is explicity looking
846         # for signatures by this fingerprint.
847     for k,v in message.items(): # copy over useful headers
848         if k.lower() not in ['content-type',
849                              'mime-version',
850                              'content-disposition',
851                              ]:
852             decrypted[k] = v
853     decrypted.authenticated = True
854     return decrypted
855
856 def _get_error_response(error):
857     author = error.course.robot
858     target = getattr(error, 'person', None)
859     subject = str(error)
860     if isinstance(error, InvalidHandlerMessage):
861         targets = sorted(error.handlers.keys())
862         if not targets:
863             hint = (
864                 'In fact, there are no available handlers for this\n'
865                 'course!')
866         else:
867             hint = (
868                 'Perhaps you meant to use one of the following:\n'
869                 '  {}').format('\n  '.join(targets))
870         text = (
871             'We got an email from you with the following subject:\n'
872             '  {!r}\n'
873             'which does not match any submittable handler name for\n'
874             '{}.\n'
875             '{}').format(repr(error.subject), error.course.name, hint)
876     elif isinstance(error, SubjectlessMessage):
877         subject = 'no subject in {}'.format(error.message['Message-ID'])
878         text = 'We received an email message from you without a subject.'
879     elif isinstance(error, AmbiguousAddress):
880         text = (
881             'Multiple people match {} ({})'.format(
882                 error.address, ', '.join(p.name for p in error.people)))
883     elif isinstance(error, UnregisteredAddress):
884         target = _Person(name=error.address, emails=[error.address])
885         text = (
886             'Your email address is not registered with pygrader for\n'
887             '{}.  If you feel it should be, contact your professor\n'
888             'or TA.').format(error.course.name)
889     elif isinstance(error, NoReturnPath):
890         return
891     elif isinstance(error, _InvalidSubjectMessage):
892         text = (
893             'We received an email message from you with an invalid\n'
894             'subject.')
895     elif isinstance(error, _UnsignedMessage):
896         subject = 'unsigned message {}'.format(error.message['Message-ID'])
897         text = (
898             'We received an email message from you without a valid\n'
899             'PGP signature.')
900     elif isinstance(error, _InvalidAssignment):
901         text = (
902             'We received your submission for {}, but you are not\n'
903             'allowed to submit that assignment via email.'
904             ).format(error.assignment.name)
905     elif isinstance(error, _InvalidStudent):
906         text = (
907             'We got an email from you with the following subject:\n'
908             '  {!r}\n'
909             'but it matches several students:\n'
910             '  * {}').format(
911             error.subject, '\n  * '.join(s.name for s in error.students))
912     elif isinstance(error, _InvalidMessage):
913         text = subject
914     else:
915         raise NotImplementedError((type(error), error))
916     if target is None:
917         raise NotImplementedError((type(error), error))
918     return _construct_response(
919         author=author,
920         targets=[target],
921         subject=subject,
922         text=(
923             '{},\n\n'
924             '{}\n\n'
925             'Yours,\n'
926             '{}\n'.format(target.alias(), text, author.alias())),
927         original=error.message)