1#!/usr/bin/env python
2# SPDX-License-Identifier: GPL-2.0
3# Copyright Thomas Gleixner <tglx@linutronix.de>
4
5from argparse import ArgumentParser
6from ply import lex, yacc
7import locale
8import traceback
9import sys
10import git
11import re
12import os
13
14class ParserException(Exception):
15    def __init__(self, tok, txt):
16        self.tok = tok
17        self.txt = txt
18
19class SPDXException(Exception):
20    def __init__(self, el, txt):
21        self.el = el
22        self.txt = txt
23
24class SPDXdata(object):
25    def __init__(self):
26        self.license_files = 0
27        self.exception_files = 0
28        self.licenses = [ ]
29        self.exceptions = { }
30
31# Read the spdx data from the LICENSES directory
32def read_spdxdata(repo):
33
34    # The subdirectories of LICENSES in the kernel source
35    # Note: exceptions needs to be parsed as last directory.
36    license_dirs = [ "preferred", "dual", "deprecated", "exceptions" ]
37    lictree = repo.head.commit.tree['LICENSES']
38
39    spdx = SPDXdata()
40
41    for d in license_dirs:
42        for el in lictree[d].traverse():
43            if not os.path.isfile(el.path):
44                continue
45
46            exception = None
47            for l in open(el.path).readlines():
48                if l.startswith('Valid-License-Identifier:'):
49                    lid = l.split(':')[1].strip().upper()
50                    if lid in spdx.licenses:
51                        raise SPDXException(el, 'Duplicate License Identifier: %s' %lid)
52                    else:
53                        spdx.licenses.append(lid)
54
55                elif l.startswith('SPDX-Exception-Identifier:'):
56                    exception = l.split(':')[1].strip().upper()
57                    spdx.exceptions[exception] = []
58
59                elif l.startswith('SPDX-Licenses:'):
60                    for lic in l.split(':')[1].upper().strip().replace(' ', '').replace('\t', '').split(','):
61                        if not lic in spdx.licenses:
62                            raise SPDXException(None, 'Exception %s missing license %s' %(exception, lic))
63                        spdx.exceptions[exception].append(lic)
64
65                elif l.startswith("License-Text:"):
66                    if exception:
67                        if not len(spdx.exceptions[exception]):
68                            raise SPDXException(el, 'Exception %s is missing SPDX-Licenses' %exception)
69                        spdx.exception_files += 1
70                    else:
71                        spdx.license_files += 1
72                    break
73    return spdx
74
75class id_parser(object):
76
77    reserved = [ 'AND', 'OR', 'WITH' ]
78    tokens = [ 'LPAR', 'RPAR', 'ID', 'EXC' ] + reserved
79
80    precedence = ( ('nonassoc', 'AND', 'OR'), )
81
82    t_ignore = ' \t'
83
84    def __init__(self, spdx):
85        self.spdx = spdx
86        self.lasttok = None
87        self.lastid = None
88        self.lexer = lex.lex(module = self, reflags = re.UNICODE)
89        # Initialize the parser. No debug file and no parser rules stored on disk
90        # The rules are small enough to be generated on the fly
91        self.parser = yacc.yacc(module = self, write_tables = False, debug = False)
92        self.lines_checked = 0
93        self.checked = 0
94        self.spdx_valid = 0
95        self.spdx_errors = 0
96        self.curline = 0
97        self.deepest = 0
98
99    # Validate License and Exception IDs
100    def validate(self, tok):
101        id = tok.value.upper()
102        if tok.type == 'ID':
103            if not id in self.spdx.licenses:
104                raise ParserException(tok, 'Invalid License ID')
105            self.lastid = id
106        elif tok.type == 'EXC':
107            if id not in self.spdx.exceptions:
108                raise ParserException(tok, 'Invalid Exception ID')
109            if self.lastid not in self.spdx.exceptions[id]:
110                raise ParserException(tok, 'Exception not valid for license %s' %self.lastid)
111            self.lastid = None
112        elif tok.type != 'WITH':
113            self.lastid = None
114
115    # Lexer functions
116    def t_RPAR(self, tok):
117        r'\)'
118        self.lasttok = tok.type
119        return tok
120
121    def t_LPAR(self, tok):
122        r'\('
123        self.lasttok = tok.type
124        return tok
125
126    def t_ID(self, tok):
127        r'[A-Za-z.0-9\-+]+'
128
129        if self.lasttok == 'EXC':
130            print(tok)
131            raise ParserException(tok, 'Missing parentheses')
132
133        tok.value = tok.value.strip()
134        val = tok.value.upper()
135
136        if val in self.reserved:
137            tok.type = val
138        elif self.lasttok == 'WITH':
139            tok.type = 'EXC'
140
141        self.lasttok = tok.type
142        self.validate(tok)
143        return tok
144
145    def t_error(self, tok):
146        raise ParserException(tok, 'Invalid token')
147
148    def p_expr(self, p):
149        '''expr : ID
150                | ID WITH EXC
151                | expr AND expr
152                | expr OR expr
153                | LPAR expr RPAR'''
154        pass
155
156    def p_error(self, p):
157        if not p:
158            raise ParserException(None, 'Unfinished license expression')
159        else:
160            raise ParserException(p, 'Syntax error')
161
162    def parse(self, expr):
163        self.lasttok = None
164        self.lastid = None
165        self.parser.parse(expr, lexer = self.lexer)
166
167    def parse_lines(self, fd, maxlines, fname):
168        self.checked += 1
169        self.curline = 0
170        try:
171            for line in fd:
172                line = line.decode(locale.getpreferredencoding(False), errors='ignore')
173                self.curline += 1
174                if self.curline > maxlines:
175                    break
176                self.lines_checked += 1
177                if line.find("SPDX-License-Identifier:") < 0:
178                    continue
179                expr = line.split(':')[1].strip()
180                # Remove trailing comment closure
181                if line.strip().endswith('*/'):
182                    expr = expr.rstrip('*/').strip()
183                # Special case for SH magic boot code files
184                if line.startswith('LIST \"'):
185                    expr = expr.rstrip('\"').strip()
186                self.parse(expr)
187                self.spdx_valid += 1
188                #
189                # Should we check for more SPDX ids in the same file and
190                # complain if there are any?
191                #
192                break
193
194        except ParserException as pe:
195            if pe.tok:
196                col = line.find(expr) + pe.tok.lexpos
197                tok = pe.tok.value
198                sys.stdout.write('%s: %d:%d %s: %s\n' %(fname, self.curline, col, pe.txt, tok))
199            else:
200                sys.stdout.write('%s: %d:0 %s\n' %(fname, self.curline, col, pe.txt))
201            self.spdx_errors += 1
202
203def scan_git_tree(tree):
204    for el in tree.traverse():
205        # Exclude stuff which would make pointless noise
206        # FIXME: Put this somewhere more sensible
207        if el.path.startswith("LICENSES"):
208            continue
209        if el.path.find("license-rules.rst") >= 0:
210            continue
211        if not os.path.isfile(el.path):
212            continue
213        with open(el.path, 'rb') as fd:
214            parser.parse_lines(fd, args.maxlines, el.path)
215
216def scan_git_subtree(tree, path):
217    for p in path.strip('/').split('/'):
218        tree = tree[p]
219    scan_git_tree(tree)
220
221if __name__ == '__main__':
222
223    ap = ArgumentParser(description='SPDX expression checker')
224    ap.add_argument('path', nargs='*', help='Check path or file. If not given full git tree scan. For stdin use "-"')
225    ap.add_argument('-m', '--maxlines', type=int, default=15,
226                    help='Maximum number of lines to scan in a file. Default 15')
227    ap.add_argument('-v', '--verbose', action='store_true', help='Verbose statistics output')
228    args = ap.parse_args()
229
230    # Sanity check path arguments
231    if '-' in args.path and len(args.path) > 1:
232        sys.stderr.write('stdin input "-" must be the only path argument\n')
233        sys.exit(1)
234
235    try:
236        # Use git to get the valid license expressions
237        repo = git.Repo(os.getcwd())
238        assert not repo.bare
239
240        # Initialize SPDX data
241        spdx = read_spdxdata(repo)
242
243        # Initilize the parser
244        parser = id_parser(spdx)
245
246    except SPDXException as se:
247        if se.el:
248            sys.stderr.write('%s: %s\n' %(se.el.path, se.txt))
249        else:
250            sys.stderr.write('%s\n' %se.txt)
251        sys.exit(1)
252
253    except Exception as ex:
254        sys.stderr.write('FAIL: %s\n' %ex)
255        sys.stderr.write('%s\n' %traceback.format_exc())
256        sys.exit(1)
257
258    try:
259        if len(args.path) and args.path[0] == '-':
260            stdin = os.fdopen(sys.stdin.fileno(), 'rb')
261            parser.parse_lines(stdin, args.maxlines, '-')
262        else:
263            if args.path:
264                for p in args.path:
265                    if os.path.isfile(p):
266                        parser.parse_lines(open(p, 'rb'), args.maxlines, p)
267                    elif os.path.isdir(p):
268                        scan_git_subtree(repo.head.reference.commit.tree, p)
269                    else:
270                        sys.stderr.write('path %s does not exist\n' %p)
271                        sys.exit(1)
272            else:
273                # Full git tree scan
274                scan_git_tree(repo.head.commit.tree)
275
276            if args.verbose:
277                sys.stderr.write('\n')
278                sys.stderr.write('License files:     %12d\n' %spdx.license_files)
279                sys.stderr.write('Exception files:   %12d\n' %spdx.exception_files)
280                sys.stderr.write('License IDs        %12d\n' %len(spdx.licenses))
281                sys.stderr.write('Exception IDs      %12d\n' %len(spdx.exceptions))
282                sys.stderr.write('\n')
283                sys.stderr.write('Files checked:     %12d\n' %parser.checked)
284                sys.stderr.write('Lines checked:     %12d\n' %parser.lines_checked)
285                sys.stderr.write('Files with SPDX:   %12d\n' %parser.spdx_valid)
286                sys.stderr.write('Files with errors: %12d\n' %parser.spdx_errors)
287
288            sys.exit(0)
289
290    except Exception as ex:
291        sys.stderr.write('FAIL: %s\n' %ex)
292        sys.stderr.write('%s\n' %traceback.format_exc())
293        sys.exit(1)
294