summaryrefslogtreecommitdiff
path: root/apps/patchwork/bin/parsemail.py
blob: fe643d802ffdb50ac6534ed3cedbd37154daacc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#!/usr/bin/python
#
# Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchwork is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import chardet
import datetime
import operator
import re
import settings
import sys

from email import message_from_file

try:
    from email.header import Header, decode_header
    from email.utils import parsedate_tz, mktime_tz
except ImportError:
    # Python 2.4 compatibility
    from email.Header import Header, decode_header
    from email.Utils import parsedate_tz, mktime_tz

from patchmetrics.crowd import Crowd
from patchwork.db import PatchworkDB
from patchwork.parser import parse_patch
from patchwork.models import Patch, Project, Person, Comment, State
from patchwork.utils import (
    is_linaro_user,
    parse_name_and_email,
)
from django.contrib.auth.models import User

default_patch_state = 'New'
list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']

whitespace_re = re.compile('\s+')


def normalise_space(str):
    return whitespace_re.sub(' ', str).strip()


def clean_header(header):
    """ Decode (possibly non-ascii) headers """

    def decode(fragment):
        (frag_str, frag_encoding) = fragment
        if frag_encoding:
            return frag_str.decode(frag_encoding)
        return frag_str.decode()

    fragments = map(decode, decode_header(header))

    return normalise_space(u' '.join(fragments))


def find_project_by_listid(mail):
    project = None
    listid_res = [re.compile('.*<([^>]+)>.*', re.S),
                  re.compile('^([\S]+)$', re.S)]

    for header in list_id_headers:
        if header in mail:

            for listid_re in listid_res:
                match = listid_re.match(mail.get(header))
                if match:
                    break

            if not match:
                continue

            listid = match.group(1)

            try:
                project = Project.objects.get(listid=listid)
                break
            except:
                pass

    return project


def extract_email_addresses(str):
    email_re = re.compile(
        r"([\w\.\-+=]+@(?:(?:[0-9a-zA-Z-]{1,}\.)*)[a-zA-Z]{2,})")
    return email_re.findall(str)


def find_project_by_list_address(mail):
    recipients = mail.get('To', '') + ' ' + mail.get('CC', '')
    email_addresses = extract_email_addresses(recipients)
    for email_address in email_addresses:
        try:
            return Project.objects.get(listemail=email_address)
        except Project.DoesNotExist:
            pass
    print("Unable to find a project for any of the recipients: %s" %
          email_addresses)
    return None


def find_project(mail):
    project = find_project_by_listid(mail)
    if project is None and settings.PATCHWORK_FALLBACK_TO_LISTEMAIL:
        project = find_project_by_list_address(mail)
    return project


def find_submitter(mail):

    from_header = clean_header(mail.get('From'))
    name, email = parse_name_and_email(from_header)

    if email is None:
        raise Exception("Could not parse From: header")

    new_person = False
    try:
        person = Person.objects.get(email__iexact=email)
    except Person.DoesNotExist:
        person = Person(name=name, email=email)
        new_person = True

    return (person, new_person)


def mail_date(mail):
    t = parsedate_tz(mail.get('Date', ''))
    if not t:
        return datetime.datetime.utcnow()
    return datetime.datetime.utcfromtimestamp(mktime_tz(t))


def mail_headers(mail):
    return reduce(operator.__concat__,
                  ['%s: %s\n' % (k, Header(v, header_name=k,
                                           continuation_ws='\t').encode())
                   for (k, v) in mail.items()])


def find_pull_request(content):
    git_re = re.compile('^The following changes since commit.*' +
                        '^are available in the git repository at:\n'
                        '^\s*([\S]+://[^\n]+)$',
                        re.DOTALL | re.MULTILINE)
    match = git_re.search(content)
    if match:
        return match.group(1)
    return None


def string_to_unicode(text, charset=None):
    """Converts the given string to unicode.

    Will first try the character set passed in and if that fails, will use
    chardet to detect a probable encoding. During this second decode the
    decoder is set to replace characters that don't decode properly with
    the UTF8 [?] character

    """
    # if we don't have a charset, detect it
    if charset is None:
        charset = chardet.detect(text)['encoding']

    if text is None or charset is None:
        return None  # Nothing to decode / no character encoding makes sense.

    if not isinstance(text, unicode):
        try:
            text = unicode(text, charset)
        except (UnicodeDecodeError, LookupError):
            # Character set was incorrectly set or message is malformed.
            # Try detecting the character set. LookupError means charset is
            # not a character set that we understand (probably garbage).
            # UnicodeDecodeError means that charset is a valid encoding, but
            # text can not be decoded using it.
            charset = chardet.detect(text)['encoding']

            if not charset:
                return None  # chardet can't work out a character set.

            # Sometimes chardet says that the encoding is <something> and it
            # doesn't decode (input charset may agree). This is normally
            # an illegally encoded email - most I have seen are gb2312 (Chinese
            # simplified). Using errors="replace" works fine and replaces
            # unknown characters with [?]. This should make it obvious to
            # anyone viewing the output if the decode worked well or not.
            text = unicode(text, charset, errors="replace")

    return text


def find_content(project, mail):
    patchbuf = None
    commentbuf = ''
    pullurl = None

    for part in mail.walk():
        if part.get_content_maintype() != 'text':
            continue

        payload = part.get_payload(decode=True)
        charset = part.get_content_charset()
        subtype = part.get_content_subtype()

        payload = string_to_unicode(payload, charset)

        if subtype in ['x-patch', 'x-diff']:
            patchbuf = payload

        elif subtype == 'plain':
            c = payload

            if not patchbuf:
                (patchbuf, c) = parse_patch(payload)

            if not pullurl:
                pullurl = find_pull_request(payload)

            if c is not None:
                commentbuf += c.strip() + '\n'

    patch = None
    comment = None

    if pullurl or patchbuf:
        name = clean_subject(mail.get('Subject'), [project.linkname])
        patch = Patch(name=name, pull_url=pullurl, content=patchbuf,
                      date=mail_date(mail), headers=mail_headers(mail))

    if commentbuf:
        if patch:
            cpatch = patch
        else:
            cpatch = find_patch_for_comment(project, mail)
            if not cpatch:
                return (None, None)
        comment = Comment(patch=cpatch, date=mail_date(mail),
                          content=clean_content(commentbuf),
                          headers=mail_headers(mail))

    return (patch, comment)


def find_patch_name_and_author(comment):
    """Finds the patch name, and the patch author.

    The name and author of a patch are sometimes different from the Subject
    and From header fields and so are specified in the body of the message,
    before the actual patch. This is identified by "From: " and "Subject: "
    lines starting the body, which is the format understood by 'git-am'.

    :return A tuple consisting of: the name of the patch, the author of the
        patch, and a boolean indicating if the author needs to be saved in the
        database.
    """
    if not comment:
        return None, None, None
    lines = comment.content.split('\n')
    if len(lines) == 0:
        return None, None, None
    # Append an extra line at the end so that our code can assume there will
    # always be at least two lines, simplifying things significantly.
    lines.append('')
    first_line, second_line = lines[:2]
    author_line = subject_line = None
    if first_line.startswith('From:'):
        author_line = first_line
        if second_line.startswith('Subject:'):
            subject_line = second_line
    elif first_line.startswith('Subject:'):
        subject_line = first_line
        if second_line.startswith('From:'):
            author_line = second_line
    else:
        return None, None, None

    subject = None
    if subject_line is not None:
        subject = subject_line.replace('Subject:', '').strip()

    if author_line is None:
        return subject, None, None

    name, email = parse_name_and_email(author_line.replace('From:', ''))
    if email is None:
        return subject, None, None

    try:
        person = Person.objects.get(email__iexact=email)
        new_person = False
    except Person.DoesNotExist:
        person = Person(name=name, email=email)
        new_person = True
    return subject, person, new_person


def find_patch_for_comment(project, mail):
    # construct a list of possible reply message ids
    refs = []
    if 'In-Reply-To' in mail:
        refs.append(mail.get('In-Reply-To'))

    if 'References' in mail:
        rs = mail.get('References').split()
        rs.reverse()
        for r in rs:
            if r not in refs:
                refs.append(r)

    for ref in refs:
        patch = None

        # first, check for a direct reply
        try:
            patch = Patch.objects.get(project=project, msgid=ref)
            return patch
        except Patch.DoesNotExist:
            pass

        # see if we have comments that refer to a patch
        try:
            comment = Comment.objects.get(
                patch__project=project, msgid=ref)
            return comment.patch
        except Comment.DoesNotExist:
            pass

    return None

split_re = re.compile('[,\s]+')


def split_prefixes(prefix):
    """ Turn a prefix string into a list of prefix tokens

    >>> split_prefixes('PATCH')
    ['PATCH']
    >>> split_prefixes('PATCH,RFC')
    ['PATCH', 'RFC']
    >>> split_prefixes('')
    []
    >>> split_prefixes('PATCH,')
    ['PATCH']
    >>> split_prefixes('PATCH ')
    ['PATCH']
    >>> split_prefixes('PATCH,RFC')
    ['PATCH', 'RFC']
    >>> split_prefixes('PATCH 1/2')
    ['PATCH', '1/2']
    """
    matches = split_re.split(prefix)
    return [s for s in matches if s != '']

re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')


def clean_subject(subject, drop_prefixes=None):
    """ Clean a Subject: header from an incoming patch.

    Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
    default, only [PATCH] is removed, and we keep any other bracketed data
    in the subject. If drop_prefixes is provided, remove those too,
    comparing case-insensitively.

    >>> clean_subject('meep')
    'meep'
    >>> clean_subject('Re: meep')
    'meep'
    >>> clean_subject('[PATCH] meep')
    'meep'
    >>> clean_subject('[PATCH] meep \\n meep')
    'meep meep'
    >>> clean_subject('[PATCH RFC] meep')
    '[RFC] meep'
    >>> clean_subject('[PATCH,RFC] meep')
    '[RFC] meep'
    >>> clean_subject('[PATCH,1/2] meep')
    '[1/2] meep'
    >>> clean_subject('[PATCH RFC 1/2] meep')
    '[RFC,1/2] meep'
    >>> clean_subject('[PATCH] [RFC] meep')
    '[RFC] meep'
    >>> clean_subject('[PATCH] [RFC,1/2] meep')
    '[RFC,1/2] meep'
    >>> clean_subject('[PATCH] [RFC] [1/2] meep')
    '[RFC,1/2] meep'
    >>> clean_subject('[PATCH] rewrite [a-z] regexes')
    'rewrite [a-z] regexes'
    >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
    '[RFC] rewrite [a-z] regexes'
    >>> clean_subject('[foo] [bar] meep', ['foo'])
    '[bar] meep'
    >>> clean_subject('[FOO] [bar] meep', ['foo'])
    '[bar] meep'
    """

    subject = clean_header(subject)

    if drop_prefixes is None:
        drop_prefixes = []
    else:
        drop_prefixes = [s.lower() for s in drop_prefixes]

    drop_prefixes.append('patch')

    # remove Re:, Fwd:, etc
    subject = re_re.sub(' ', subject)

    subject = normalise_space(subject)

    prefixes = []

    match = prefix_re.match(subject)

    while match:
        prefix_str = match.group(1)
        prefixes += [p for p in split_prefixes(prefix_str)
                     if p.lower() not in drop_prefixes]

        subject = match.group(2)
        match = prefix_re.match(subject)

    subject = normalise_space(subject)

    subject = subject.strip()
    if prefixes:
        subject = '[%s] %s' % (','.join(prefixes), subject)

    return subject

sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)


def clean_content(str):
    """ Try to remove signature (-- ) and list footer (_____) cruft """
    str = sig_re.sub('', str)
    return str.strip()


def get_state(state_name):
    """ Return the state with the given name or the default State """
    if state_name:
        try:
            return State.objects.get(name__iexact=state_name)
        except State.DoesNotExist:
            pass
    return State.objects.get(name=default_patch_state)


def get_delegate(delegate_email):
    """ Return the delegate with the given email or None """
    if delegate_email:
        try:
            return User.objects.get(email__iexact=delegate_email)
        except User.DoesNotExist:
            pass
    return None


def is_valid_patch(submitter, author):
    """A patch is valid if submitter or author are valid Linaro users.

    :param submitter: The submitter to check, a Person object.
    :param author: The author to check, a Person object.
    :return True if one between submitter and author is a valid Linaro user.
    """
    valid_patch = False

    # XXX: dumb, but effective, and leave the crowd validation only when
    # necessary.
    if "@linaro.org" in submitter.email:
        valid_patch |= True

    if author is not None and "@linaro.org" in author.email:
        valid_patch |= True

    if not valid_patch:
        if (settings.AUTH_CROWD_APPLICATION_USER is not None and
                settings.CROWD_USERS_DB_FILE is not None):
            crwd = Crowd(settings.AUTH_CROWD_APPLICATION_USER,
                         settings.AUTH_CROWD_APPLICATION_PASSWORD,
                         settings.AUTH_CROWD_SERVER_REST_URI)

            cache_db = PatchworkDB(settings.CROWD_USERS_DB_FILE)
            with cache_db:
                valid_patch |= is_linaro_user(submitter.email, cache_db, crwd)
                if author is not None:
                    valid_patch |= is_linaro_user(author.email, cache_db, crwd)

    return valid_patch


def parse_mail(mail):

    # some basic sanity checks
    if 'From' not in mail:
        return 0

    if 'Subject' not in mail:
        return 0

    if 'Message-Id' not in mail:
        return 0

    hint = mail.get('X-Patchwork-Hint', '').lower()
    if hint == 'ignore':
        return 0

    project = find_project(mail)
    if project is None:
        print "no project found"
        return 0

    msgid = mail.get('Message-Id').strip()

    (submitter, save_required) = find_submitter(mail)
    (patch, comment) = find_content(project, mail)
    (name, author, is_new_author) = find_patch_name_and_author(comment)

    # If submitter nor author of a patch are not Linaro, we move on.
    valid_patch = is_valid_patch(submitter, author)

    if patch and valid_patch:
        # we delay the saving until we know we have a patch.
        if save_required:
            submitter.save()
            save_required = False
        patch.submitter = submitter

        if is_new_author:
            author.save()
        if author is not None:
            patch.author = author
        if name is not None:
            patch.name = name

        patch.msgid = msgid
        patch.project = project
        patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
        patch.delegate = get_delegate(
            mail.get('X-Patchwork-Delegate', '').strip())
        try:
            patch.save()
        except Exception, ex:
            print str(ex)

    if comment:
        if save_required:
            submitter.save()
        # looks like the original constructor for Comment takes the pk
        # when the Comment is created. reset it here.
        if patch:
            comment.patch = patch
        comment.submitter = submitter
        comment.msgid = msgid
        try:
            comment.save()
        except Exception, ex:
            print str(ex)

    return 0


def main(args):
    mail = message_from_file(sys.stdin)
    return parse_mail(mail)

if __name__ == '__main__':
    sys.exit(main(sys.argv))