blob: 09ab615ab621fb2bcb4894c2a3273c9253d910d0 [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
Gilles Peskine15898ee2020-08-08 23:14:27 +0200164 # .py files can be either full scripts or modules, so they may or may
165 # not be executable.
166 suffix_exemptions = frozenset({".py"})
167
Darryl Green10d9ce32018-02-28 10:02:55 +0000168 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100169 is_executable = os.access(filepath, os.X_OK)
Gilles Peskine15898ee2020-08-08 23:14:27 +0200170 should_be_executable = filepath.endswith((".sh", ".pl"))
Gilles Peskine23e64f22019-02-25 21:24:27 +0100171 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000172 self.files_with_issues[filepath] = None
173
174
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200175class ShebangIssueTracker(FileIssueTracker):
176 """Track files with a bad, missing or extraneous shebang line.
177
178 Executable scripts must start with a valid shebang (#!) line.
179 """
180
181 heading = "Invalid shebang line:"
182
183 # Allow either /bin/sh, /bin/bash, or /usr/bin/env.
184 # Allow at most one argument (this is a Linux limitation).
185 # For sh and bash, the argument if present must be options.
186 # For env, the argument must be the base name of the interpeter.
187 _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
188 rb'|/usr/bin/env ([^\n /]+))$')
189 _extensions = {
190 b'bash': 'sh',
191 b'perl': 'pl',
192 b'python3': 'py',
193 b'sh': 'sh',
194 }
195
196 def is_valid_shebang(self, first_line, filepath):
197 m = re.match(self._shebang_re, first_line)
198 if not m:
199 return False
200 interpreter = m.group(1) or m.group(2)
201 if interpreter not in self._extensions:
202 return False
203 if not filepath.endswith('.' + self._extensions[interpreter]):
204 return False
205 return True
206
207 def check_file_for_issue(self, filepath):
208 is_executable = os.access(filepath, os.X_OK)
209 with open(filepath, "rb") as f:
210 first_line = f.readline()
211 if first_line.startswith(b'#!'):
212 if not is_executable:
213 # Shebang on a non-executable file
214 self.files_with_issues[filepath] = None
215 elif not self.is_valid_shebang(first_line, filepath):
216 self.files_with_issues[filepath] = [1]
217 elif is_executable:
218 # Executable without a shebang
219 self.files_with_issues[filepath] = None
220
221
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100222class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100223 """Track files that end with an incomplete line
224 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000225
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100226 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000227
Gilles Peskined4a853d2020-05-10 16:57:59 +0200228 path_exemptions = BINARY_FILE_PATH_RE
229
Darryl Green10d9ce32018-02-28 10:02:55 +0000230 def check_file_for_issue(self, filepath):
231 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200232 try:
233 f.seek(-1, 2)
234 except OSError:
235 # This script only works on regular files. If we can't seek
236 # 1 before the end, it means that this position is before
237 # the beginning of the file, i.e. that the file is empty.
238 return
239 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000240 self.files_with_issues[filepath] = None
241
242
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100243class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100244 """Track files that start with a UTF-8 BOM.
245 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000246
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100247 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000248
Gilles Peskine05a51a82020-05-10 16:52:44 +0200249 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200250 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100251
Darryl Green10d9ce32018-02-28 10:02:55 +0000252 def check_file_for_issue(self, filepath):
253 with open(filepath, "rb") as f:
254 if f.read().startswith(codecs.BOM_UTF8):
255 self.files_with_issues[filepath] = None
256
257
Gilles Peskine2c618732020-03-24 22:26:01 +0100258class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100259 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000260
Gilles Peskine2c618732020-03-24 22:26:01 +0100261 heading = "Non-Unix line endings:"
262
263 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200264 if not super().should_check_file(filepath):
265 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100266 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000267
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100268 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000269 return b"\r" in line
270
271
Gilles Peskine545e13f2020-03-24 22:29:11 +0100272class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200273 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100274
275 heading = "Non-Windows line endings:"
276
277 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200278 if not super().should_check_file(filepath):
279 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100280 return is_windows_file(filepath)
281
282 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200283 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100284
285
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100286class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100287 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000288
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100289 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200290 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000291
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100292 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000293 return line.rstrip(b"\r\n") != line.rstrip()
294
295
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100296class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100297 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000298
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100299 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200300 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200301 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100302 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100303 "/Makefile",
304 "/Makefile.inc",
305 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100306 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000307
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100308 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000309 return b"\t" in line
310
311
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100312class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100313 """Track lines with merge artifacts.
314 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100315
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100316 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100317
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100318 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100319 # Detect leftover git conflict markers.
320 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
321 return True
322 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
323 return True
324 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100325 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100326 return True
327 return False
328
Darryl Green10d9ce32018-02-28 10:02:55 +0000329
Gilles Peskine184c0962020-03-24 18:25:17 +0100330class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100331 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000332
333 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100334 """Instantiate the sanity checker.
335 Check files under the current directory.
336 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000337 self.check_repo_path()
338 self.logger = None
339 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000340 self.issues_to_check = [
341 PermissionIssueTracker(),
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200342 ShebangIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000343 EndOfFileNewlineIssueTracker(),
344 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100345 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100346 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000347 TrailingWhitespaceIssueTracker(),
348 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100349 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000350 ]
351
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100352 @staticmethod
353 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000354 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
355 raise Exception("Must be run from Mbed TLS root")
356
357 def setup_logger(self, log_file, level=logging.INFO):
358 self.logger = logging.getLogger()
359 self.logger.setLevel(level)
360 if log_file:
361 handler = logging.FileHandler(log_file)
362 self.logger.addHandler(handler)
363 else:
364 console = logging.StreamHandler()
365 self.logger.addHandler(console)
366
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200367 @staticmethod
368 def collect_files():
369 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
370 bytes_filepaths = bytes_output.split(b'\0')[:-1]
371 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
372 # Prepend './' to files in the top-level directory so that
373 # something like `'/Makefile' in fp` matches in the top-level
374 # directory as well as in subdirectories.
375 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
376 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200377
Darryl Green10d9ce32018-02-28 10:02:55 +0000378 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200379 for issue_to_check in self.issues_to_check:
380 for filepath in self.collect_files():
381 if issue_to_check.should_check_file(filepath):
382 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000383
384 def output_issues(self):
385 integrity_return_code = 0
386 for issue_to_check in self.issues_to_check:
387 if issue_to_check.files_with_issues:
388 integrity_return_code = 1
389 issue_to_check.output_file_issues(self.logger)
390 return integrity_return_code
391
392
393def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200394 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000395 parser.add_argument(
396 "-l", "--log_file", type=str, help="path to optional output log",
397 )
398 check_args = parser.parse_args()
399 integrity_check = IntegrityChecker(check_args.log_file)
400 integrity_check.check_files()
401 return_code = integrity_check.output_issues()
402 sys.exit(return_code)
403
404
405if __name__ == "__main__":
406 run_main()