blob: 13fee9d762dad854662c388dab60114fd6056164 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02002
Bence Szépkúti1e148272020-08-07 13:07:28 +02003# Copyright The Mbed TLS Contributors
Bence Szépkútic7da1fe2020-05-26 01:54:15 +02004# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
Gilles Peskine7dfcfce2019-07-04 19:31:02 +020017
Darryl Green10d9ce32018-02-28 10:02:55 +000018"""
Darryl Green10d9ce32018-02-28 10:02:55 +000019This script checks the current state of the source code for minor issues,
20including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine55b49ee2019-07-04 19:31:33 +020021trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-02-28 10:02:55 +000022Note: requires python 3, must be run from Mbed TLS root.
23"""
24
25import os
26import argparse
27import logging
28import codecs
Gilles Peskine0598db82020-05-10 16:57:16 +020029import re
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +020030import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000031import sys
32
33
Gilles Peskine184c0962020-03-24 18:25:17 +010034class FileIssueTracker:
Gilles Peskine6ee576e2019-02-25 20:59:05 +010035 """Base class for file-wide issue tracking.
36
37 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine1e9698a2019-02-25 21:10:04 +010038 this class and implement `check_file_for_issue` and define ``heading``.
39
Gilles Peskine05a51a82020-05-10 16:52:44 +020040 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010041 will not be checked.
42
Gilles Peskine0598db82020-05-10 16:57:16 +020043 ``path_exemptions``: files whose path (relative to the root of the source
44 tree) matches this regular expression will not be checked. This can be
45 ``None`` to match no path. Paths are normalized and converted to ``/``
46 separators before matching.
47
Gilles Peskine1e9698a2019-02-25 21:10:04 +010048 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010049 """
Darryl Green10d9ce32018-02-28 10:02:55 +000050
Gilles Peskine05a51a82020-05-10 16:52:44 +020051 suffix_exemptions = frozenset()
Gilles Peskine0598db82020-05-10 16:57:16 +020052 path_exemptions = None
Gilles Peskine1e9698a2019-02-25 21:10:04 +010053 # heading must be defined in derived classes.
54 # pylint: disable=no-member
55
Darryl Green10d9ce32018-02-28 10:02:55 +000056 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000057 self.files_with_issues = {}
58
Gilles Peskine0598db82020-05-10 16:57:16 +020059 @staticmethod
60 def normalize_path(filepath):
Gilles Peskineeca95db2020-05-28 18:19:20 +020061 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskine0598db82020-05-10 16:57:16 +020062 filepath = os.path.normpath(filepath)
Gilles Peskineeca95db2020-05-28 18:19:20 +020063 # On Windows, we may have backslashes to separate directories.
64 # We need slashes to match exemption lists.
Gilles Peskine0598db82020-05-10 16:57:16 +020065 seps = os.path.sep
66 if os.path.altsep is not None:
67 seps += os.path.altsep
68 return '/'.join(filepath.split(seps))
69
Darryl Green10d9ce32018-02-28 10:02:55 +000070 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010071 """Whether the given file name should be checked.
72
Gilles Peskine05a51a82020-05-10 16:52:44 +020073 Files whose name ends with a string listed in ``self.suffix_exemptions``
74 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010075 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020076 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000077 if filepath.endswith(files_exemption):
78 return False
Gilles Peskine0598db82020-05-10 16:57:16 +020079 if self.path_exemptions and \
80 re.match(self.path_exemptions, self.normalize_path(filepath)):
81 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000082 return True
83
Darryl Green10d9ce32018-02-28 10:02:55 +000084 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010085 """Check the specified file for the issue that this class is for.
86
87 Subclasses must implement this method.
88 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010089 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000090
Gilles Peskine04398052018-11-23 21:11:30 +010091 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010092 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010093 if filepath not in self.files_with_issues.keys():
94 self.files_with_issues[filepath] = []
95 self.files_with_issues[filepath].append(line_number)
96
Darryl Green10d9ce32018-02-28 10:02:55 +000097 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010098 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000099 if self.files_with_issues.values():
100 logger.info(self.heading)
101 for filename, lines in sorted(self.files_with_issues.items()):
102 if lines:
103 logger.info("{}: {}".format(
104 filename, ", ".join(str(x) for x in lines)
105 ))
106 else:
107 logger.info(filename)
108 logger.info("")
109
Gilles Peskined4a853d2020-05-10 16:57:59 +0200110BINARY_FILE_PATH_RE_LIST = [
111 r'docs/.*\.pdf\Z',
112 r'programs/fuzz/corpuses/[^.]+\Z',
113 r'tests/data_files/[^.]+\Z',
114 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
115 r'tests/data_files/.*\.req\.[^/]+\Z',
116 r'tests/data_files/.*malformed[^/]+\Z',
117 r'tests/data_files/format_pkcs12\.fmt\Z',
118]
119BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
120
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100121class LineIssueTracker(FileIssueTracker):
122 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000123
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100124 To implement a checker that processes files line by line, inherit from
125 this class and implement `line_with_issue`.
126 """
127
Gilles Peskined4a853d2020-05-10 16:57:59 +0200128 # Exclude binary files.
129 path_exemptions = BINARY_FILE_PATH_RE
130
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100131 def issue_with_line(self, line, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100132 """Check the specified line for the issue that this class is for.
133
134 Subclasses must implement this method.
135 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100136 raise NotImplementedError
137
138 def check_file_line(self, filepath, line, line_number):
139 if self.issue_with_line(line, filepath):
140 self.record_issue(filepath, line_number)
141
142 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100143 """Check the lines of the specified file.
144
145 Subclasses must implement the ``issue_with_line`` method.
146 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100147 with open(filepath, "rb") as f:
148 for i, line in enumerate(iter(f.readline, b"")):
149 self.check_file_line(filepath, line, i + 1)
150
Gilles Peskine2c618732020-03-24 22:26:01 +0100151
152def is_windows_file(filepath):
153 _root, ext = os.path.splitext(filepath)
Gilles Peskined2df86f2020-05-10 17:36:51 +0200154 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100155
156
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100157class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100158 """Track files with bad permissions.
159
160 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000161
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100162 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000163
164 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100165 is_executable = os.access(filepath, os.X_OK)
166 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
167 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000168 self.files_with_issues[filepath] = None
169
170
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100171class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100172 """Track files that end with an incomplete line
173 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000174
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100175 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000176
Gilles Peskined4a853d2020-05-10 16:57:59 +0200177 path_exemptions = BINARY_FILE_PATH_RE
178
Darryl Green10d9ce32018-02-28 10:02:55 +0000179 def check_file_for_issue(self, filepath):
180 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200181 try:
182 f.seek(-1, 2)
183 except OSError:
184 # This script only works on regular files. If we can't seek
185 # 1 before the end, it means that this position is before
186 # the beginning of the file, i.e. that the file is empty.
187 return
188 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000189 self.files_with_issues[filepath] = None
190
191
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100192class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100193 """Track files that start with a UTF-8 BOM.
194 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000195
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100196 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000197
Gilles Peskine05a51a82020-05-10 16:52:44 +0200198 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200199 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100200
Darryl Green10d9ce32018-02-28 10:02:55 +0000201 def check_file_for_issue(self, filepath):
202 with open(filepath, "rb") as f:
203 if f.read().startswith(codecs.BOM_UTF8):
204 self.files_with_issues[filepath] = None
205
206
Gilles Peskine2c618732020-03-24 22:26:01 +0100207class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100208 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000209
Gilles Peskine2c618732020-03-24 22:26:01 +0100210 heading = "Non-Unix line endings:"
211
212 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200213 if not super().should_check_file(filepath):
214 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100215 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000216
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100217 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000218 return b"\r" in line
219
220
Gilles Peskine545e13f2020-03-24 22:29:11 +0100221class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200222 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100223
224 heading = "Non-Windows line endings:"
225
226 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200227 if not super().should_check_file(filepath):
228 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100229 return is_windows_file(filepath)
230
231 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200232 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100233
234
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100235class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100236 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000237
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100238 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200239 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000240
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100241 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000242 return line.rstrip(b"\r\n") != line.rstrip()
243
244
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100245class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100246 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000247
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100248 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200249 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200250 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100251 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100252 "/Makefile",
253 "/Makefile.inc",
254 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100255 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000256
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100257 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000258 return b"\t" in line
259
260
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100261class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100262 """Track lines with merge artifacts.
263 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100264
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100265 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100266
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100267 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100268 # Detect leftover git conflict markers.
269 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
270 return True
271 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
272 return True
273 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100274 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100275 return True
276 return False
277
Darryl Green10d9ce32018-02-28 10:02:55 +0000278
Gilles Peskine184c0962020-03-24 18:25:17 +0100279class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100280 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000281
282 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100283 """Instantiate the sanity checker.
284 Check files under the current directory.
285 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000286 self.check_repo_path()
287 self.logger = None
288 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000289 self.issues_to_check = [
290 PermissionIssueTracker(),
291 EndOfFileNewlineIssueTracker(),
292 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100293 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100294 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000295 TrailingWhitespaceIssueTracker(),
296 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100297 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000298 ]
299
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100300 @staticmethod
301 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000302 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
303 raise Exception("Must be run from Mbed TLS root")
304
305 def setup_logger(self, log_file, level=logging.INFO):
306 self.logger = logging.getLogger()
307 self.logger.setLevel(level)
308 if log_file:
309 handler = logging.FileHandler(log_file)
310 self.logger.addHandler(handler)
311 else:
312 console = logging.StreamHandler()
313 self.logger.addHandler(console)
314
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200315 @staticmethod
316 def collect_files():
317 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
318 bytes_filepaths = bytes_output.split(b'\0')[:-1]
319 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
320 # Prepend './' to files in the top-level directory so that
321 # something like `'/Makefile' in fp` matches in the top-level
322 # directory as well as in subdirectories.
323 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
324 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200325
Darryl Green10d9ce32018-02-28 10:02:55 +0000326 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200327 for issue_to_check in self.issues_to_check:
328 for filepath in self.collect_files():
329 if issue_to_check.should_check_file(filepath):
330 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000331
332 def output_issues(self):
333 integrity_return_code = 0
334 for issue_to_check in self.issues_to_check:
335 if issue_to_check.files_with_issues:
336 integrity_return_code = 1
337 issue_to_check.output_file_issues(self.logger)
338 return integrity_return_code
339
340
341def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200342 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000343 parser.add_argument(
344 "-l", "--log_file", type=str, help="path to optional output log",
345 )
346 check_args = parser.parse_args()
347 integrity_check = IntegrityChecker(check_args.log_file)
348 integrity_check.check_files()
349 return_code = integrity_check.output_issues()
350 sys.exit(return_code)
351
352
353if __name__ == "__main__":
354 run_main()