blob: 62b526ab9452d233caa7ff138a42d1be842806c1 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02002
3# This file is part of Mbed TLS (https://tls.mbed.org)
4# Copyright (c) 2018, Arm Limited, All Rights Reserved
5
Darryl Green10d9ce32018-02-28 10:02:55 +00006"""
Darryl Green10d9ce32018-02-28 10:02:55 +00007This script checks the current state of the source code for minor issues,
8including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine55b49ee2019-07-04 19:31:33 +02009trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-02-28 10:02:55 +000010Note: requires python 3, must be run from Mbed TLS root.
11"""
12
13import os
14import argparse
15import logging
16import codecs
Gilles Peskine0598db82020-05-10 16:57:16 +020017import re
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +020018import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000019import sys
20
21
Gilles Peskine184c0962020-03-24 18:25:17 +010022class FileIssueTracker:
Gilles Peskine6ee576e2019-02-25 20:59:05 +010023 """Base class for file-wide issue tracking.
24
25 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine1e9698a2019-02-25 21:10:04 +010026 this class and implement `check_file_for_issue` and define ``heading``.
27
Gilles Peskine05a51a82020-05-10 16:52:44 +020028 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010029 will not be checked.
30
Gilles Peskine0598db82020-05-10 16:57:16 +020031 ``path_exemptions``: files whose path (relative to the root of the source
32 tree) matches this regular expression will not be checked. This can be
33 ``None`` to match no path. Paths are normalized and converted to ``/``
34 separators before matching.
35
Gilles Peskine1e9698a2019-02-25 21:10:04 +010036 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010037 """
Darryl Green10d9ce32018-02-28 10:02:55 +000038
Gilles Peskine05a51a82020-05-10 16:52:44 +020039 suffix_exemptions = frozenset()
Gilles Peskine0598db82020-05-10 16:57:16 +020040 path_exemptions = None
Gilles Peskine1e9698a2019-02-25 21:10:04 +010041 # heading must be defined in derived classes.
42 # pylint: disable=no-member
43
Darryl Green10d9ce32018-02-28 10:02:55 +000044 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000045 self.files_with_issues = {}
46
Gilles Peskine0598db82020-05-10 16:57:16 +020047 @staticmethod
48 def normalize_path(filepath):
Gilles Peskineeca95db2020-05-28 18:19:20 +020049 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskine0598db82020-05-10 16:57:16 +020050 filepath = os.path.normpath(filepath)
Gilles Peskineeca95db2020-05-28 18:19:20 +020051 # On Windows, we may have backslashes to separate directories.
52 # We need slashes to match exemption lists.
Gilles Peskine0598db82020-05-10 16:57:16 +020053 seps = os.path.sep
54 if os.path.altsep is not None:
55 seps += os.path.altsep
56 return '/'.join(filepath.split(seps))
57
Darryl Green10d9ce32018-02-28 10:02:55 +000058 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010059 """Whether the given file name should be checked.
60
Gilles Peskine05a51a82020-05-10 16:52:44 +020061 Files whose name ends with a string listed in ``self.suffix_exemptions``
62 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010063 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020064 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000065 if filepath.endswith(files_exemption):
66 return False
Gilles Peskine0598db82020-05-10 16:57:16 +020067 if self.path_exemptions and \
68 re.match(self.path_exemptions, self.normalize_path(filepath)):
69 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000070 return True
71
Darryl Green10d9ce32018-02-28 10:02:55 +000072 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010073 """Check the specified file for the issue that this class is for.
74
75 Subclasses must implement this method.
76 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010077 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000078
Gilles Peskine04398052018-11-23 21:11:30 +010079 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010080 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010081 if filepath not in self.files_with_issues.keys():
82 self.files_with_issues[filepath] = []
83 self.files_with_issues[filepath].append(line_number)
84
Darryl Green10d9ce32018-02-28 10:02:55 +000085 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010086 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000087 if self.files_with_issues.values():
88 logger.info(self.heading)
89 for filename, lines in sorted(self.files_with_issues.items()):
90 if lines:
91 logger.info("{}: {}".format(
92 filename, ", ".join(str(x) for x in lines)
93 ))
94 else:
95 logger.info(filename)
96 logger.info("")
97
Gilles Peskined4a853d2020-05-10 16:57:59 +020098BINARY_FILE_PATH_RE_LIST = [
99 r'docs/.*\.pdf\Z',
100 r'programs/fuzz/corpuses/[^.]+\Z',
101 r'tests/data_files/[^.]+\Z',
102 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
103 r'tests/data_files/.*\.req\.[^/]+\Z',
104 r'tests/data_files/.*malformed[^/]+\Z',
105 r'tests/data_files/format_pkcs12\.fmt\Z',
106]
107BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
108
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100109class LineIssueTracker(FileIssueTracker):
110 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000111
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100112 To implement a checker that processes files line by line, inherit from
113 this class and implement `line_with_issue`.
114 """
115
Gilles Peskined4a853d2020-05-10 16:57:59 +0200116 # Exclude binary files.
117 path_exemptions = BINARY_FILE_PATH_RE
118
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100119 def issue_with_line(self, line, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100120 """Check the specified line for the issue that this class is for.
121
122 Subclasses must implement this method.
123 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100124 raise NotImplementedError
125
126 def check_file_line(self, filepath, line, line_number):
127 if self.issue_with_line(line, filepath):
128 self.record_issue(filepath, line_number)
129
130 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100131 """Check the lines of the specified file.
132
133 Subclasses must implement the ``issue_with_line`` method.
134 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100135 with open(filepath, "rb") as f:
136 for i, line in enumerate(iter(f.readline, b"")):
137 self.check_file_line(filepath, line, i + 1)
138
Gilles Peskine2c618732020-03-24 22:26:01 +0100139
140def is_windows_file(filepath):
141 _root, ext = os.path.splitext(filepath)
Gilles Peskined2df86f2020-05-10 17:36:51 +0200142 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100143
144
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100145class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100146 """Track files with bad permissions.
147
148 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000149
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100150 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000151
152 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100153 is_executable = os.access(filepath, os.X_OK)
154 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
155 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000156 self.files_with_issues[filepath] = None
157
158
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100159class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100160 """Track files that end with an incomplete line
161 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000162
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100163 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000164
Gilles Peskined4a853d2020-05-10 16:57:59 +0200165 path_exemptions = BINARY_FILE_PATH_RE
166
Darryl Green10d9ce32018-02-28 10:02:55 +0000167 def check_file_for_issue(self, filepath):
168 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200169 try:
170 f.seek(-1, 2)
171 except OSError:
172 # This script only works on regular files. If we can't seek
173 # 1 before the end, it means that this position is before
174 # the beginning of the file, i.e. that the file is empty.
175 return
176 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000177 self.files_with_issues[filepath] = None
178
179
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100180class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100181 """Track files that start with a UTF-8 BOM.
182 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000183
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100184 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000185
Gilles Peskine05a51a82020-05-10 16:52:44 +0200186 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200187 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100188
Darryl Green10d9ce32018-02-28 10:02:55 +0000189 def check_file_for_issue(self, filepath):
190 with open(filepath, "rb") as f:
191 if f.read().startswith(codecs.BOM_UTF8):
192 self.files_with_issues[filepath] = None
193
194
Gilles Peskine2c618732020-03-24 22:26:01 +0100195class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100196 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000197
Gilles Peskine2c618732020-03-24 22:26:01 +0100198 heading = "Non-Unix line endings:"
199
200 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200201 if not super().should_check_file(filepath):
202 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100203 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000204
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100205 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000206 return b"\r" in line
207
208
Gilles Peskine545e13f2020-03-24 22:29:11 +0100209class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200210 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100211
212 heading = "Non-Windows line endings:"
213
214 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200215 if not super().should_check_file(filepath):
216 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100217 return is_windows_file(filepath)
218
219 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200220 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100221
222
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100223class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100224 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000225
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100226 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000228
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100229 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000230 return line.rstrip(b"\r\n") != line.rstrip()
231
232
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100233class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100234 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000235
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100236 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200237 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200238 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100239 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100240 "/Makefile",
241 "/Makefile.inc",
242 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100243 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000244
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100245 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000246 return b"\t" in line
247
248
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100249class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100250 """Track lines with merge artifacts.
251 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100252
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100253 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100254
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100255 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100256 # Detect leftover git conflict markers.
257 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
258 return True
259 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
260 return True
261 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100262 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100263 return True
264 return False
265
Darryl Green10d9ce32018-02-28 10:02:55 +0000266
Gilles Peskine184c0962020-03-24 18:25:17 +0100267class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100268 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000269
270 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100271 """Instantiate the sanity checker.
272 Check files under the current directory.
273 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000274 self.check_repo_path()
275 self.logger = None
276 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000277 self.issues_to_check = [
278 PermissionIssueTracker(),
279 EndOfFileNewlineIssueTracker(),
280 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100281 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100282 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000283 TrailingWhitespaceIssueTracker(),
284 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100285 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000286 ]
287
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100288 @staticmethod
289 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000290 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
291 raise Exception("Must be run from Mbed TLS root")
292
293 def setup_logger(self, log_file, level=logging.INFO):
294 self.logger = logging.getLogger()
295 self.logger.setLevel(level)
296 if log_file:
297 handler = logging.FileHandler(log_file)
298 self.logger.addHandler(handler)
299 else:
300 console = logging.StreamHandler()
301 self.logger.addHandler(console)
302
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200303 @staticmethod
304 def collect_files():
305 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
306 bytes_filepaths = bytes_output.split(b'\0')[:-1]
307 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
308 # Prepend './' to files in the top-level directory so that
309 # something like `'/Makefile' in fp` matches in the top-level
310 # directory as well as in subdirectories.
311 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
312 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200313
Darryl Green10d9ce32018-02-28 10:02:55 +0000314 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200315 for issue_to_check in self.issues_to_check:
316 for filepath in self.collect_files():
317 if issue_to_check.should_check_file(filepath):
318 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000319
320 def output_issues(self):
321 integrity_return_code = 0
322 for issue_to_check in self.issues_to_check:
323 if issue_to_check.files_with_issues:
324 integrity_return_code = 1
325 issue_to_check.output_file_issues(self.logger)
326 return integrity_return_code
327
328
329def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200330 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000331 parser.add_argument(
332 "-l", "--log_file", type=str, help="path to optional output log",
333 )
334 check_args = parser.parse_args()
335 integrity_check = IntegrityChecker(check_args.log_file)
336 integrity_check.check_files()
337 return_code = integrity_check.output_issues()
338 sys.exit(return_code)
339
340
341if __name__ == "__main__":
342 run_main()