blob: 2e04650216dd1475e5a755feef0ed30eb3ecce97 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine79cfef02019-07-04 19:31:02 +02002
Bence Szépkútia2947ac2020-08-19 16:37:36 +02003# Copyright The Mbed TLS Contributors
Bence Szépkútif744bd72020-06-05 13:02:18 +02004# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5#
6# This file is provided under the Apache License 2.0, or the
7# GNU General Public License v2.0 or later.
8#
9# **********
10# Apache License 2.0:
Bence Szépkúti51b41d52020-05-26 01:54:15 +020011#
12# Licensed under the Apache License, Version 2.0 (the "License"); you may
13# not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
23#
Bence Szépkútif744bd72020-06-05 13:02:18 +020024# **********
25#
26# **********
27# GNU General Public License v2.0 or later:
28#
29# This program is free software; you can redistribute it and/or modify
30# it under the terms of the GNU General Public License as published by
31# the Free Software Foundation; either version 2 of the License, or
32# (at your option) any later version.
33#
34# This program is distributed in the hope that it will be useful,
35# but WITHOUT ANY WARRANTY; without even the implied warranty of
36# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37# GNU General Public License for more details.
38#
39# You should have received a copy of the GNU General Public License along
40# with this program; if not, write to the Free Software Foundation, Inc.,
41# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
42#
43# **********
Gilles Peskine79cfef02019-07-04 19:31:02 +020044
Darryl Green10d9ce32018-02-28 10:02:55 +000045"""
Darryl Green10d9ce32018-02-28 10:02:55 +000046This script checks the current state of the source code for minor issues,
47including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine47d7c2d2019-07-04 19:31:33 +020048trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-02-28 10:02:55 +000049Note: requires python 3, must be run from Mbed TLS root.
50"""
51
52import os
53import argparse
54import logging
55import codecs
Gilles Peskinee6f1f242020-05-10 16:57:16 +020056import re
Gilles Peskinece5d8542020-05-10 17:18:06 +020057import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000058import sys
59
60
Gilles Peskine5d1dfd42020-03-24 18:25:17 +010061class FileIssueTracker:
Gilles Peskined5240ec2019-02-25 20:59:05 +010062 """Base class for file-wide issue tracking.
63
64 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine21e85f72019-02-25 21:10:04 +010065 this class and implement `check_file_for_issue` and define ``heading``.
66
Gilles Peskinee856ba12020-05-10 16:52:44 +020067 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine21e85f72019-02-25 21:10:04 +010068 will not be checked.
69
Gilles Peskinee6f1f242020-05-10 16:57:16 +020070 ``path_exemptions``: files whose path (relative to the root of the source
71 tree) matches this regular expression will not be checked. This can be
72 ``None`` to match no path. Paths are normalized and converted to ``/``
73 separators before matching.
74
Gilles Peskine21e85f72019-02-25 21:10:04 +010075 ``heading``: human-readable description of the issue
Gilles Peskined5240ec2019-02-25 20:59:05 +010076 """
Darryl Green10d9ce32018-02-28 10:02:55 +000077
Gilles Peskinee856ba12020-05-10 16:52:44 +020078 suffix_exemptions = frozenset()
Gilles Peskinee6f1f242020-05-10 16:57:16 +020079 path_exemptions = None
Gilles Peskine21e85f72019-02-25 21:10:04 +010080 # heading must be defined in derived classes.
81 # pylint: disable=no-member
82
Darryl Green10d9ce32018-02-28 10:02:55 +000083 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000084 self.files_with_issues = {}
85
Gilles Peskinee6f1f242020-05-10 16:57:16 +020086 @staticmethod
87 def normalize_path(filepath):
Gilles Peskineb6484872020-05-28 18:19:20 +020088 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskinee6f1f242020-05-10 16:57:16 +020089 filepath = os.path.normpath(filepath)
Gilles Peskineb6484872020-05-28 18:19:20 +020090 # On Windows, we may have backslashes to separate directories.
91 # We need slashes to match exemption lists.
Gilles Peskinee6f1f242020-05-10 16:57:16 +020092 seps = os.path.sep
93 if os.path.altsep is not None:
94 seps += os.path.altsep
95 return '/'.join(filepath.split(seps))
96
Darryl Green10d9ce32018-02-28 10:02:55 +000097 def should_check_file(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010098 """Whether the given file name should be checked.
99
Gilles Peskinee856ba12020-05-10 16:52:44 +0200100 Files whose name ends with a string listed in ``self.suffix_exemptions``
101 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100102 """
Gilles Peskinee856ba12020-05-10 16:52:44 +0200103 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +0000104 if filepath.endswith(files_exemption):
105 return False
Gilles Peskinee6f1f242020-05-10 16:57:16 +0200106 if self.path_exemptions and \
107 re.match(self.path_exemptions, self.normalize_path(filepath)):
108 return False
Darryl Green10d9ce32018-02-28 10:02:55 +0000109 return True
110
Darryl Green10d9ce32018-02-28 10:02:55 +0000111 def check_file_for_issue(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100112 """Check the specified file for the issue that this class is for.
113
114 Subclasses must implement this method.
115 """
Gilles Peskined5240ec2019-02-25 20:59:05 +0100116 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +0000117
Gilles Peskine04398052018-11-23 21:11:30 +0100118 def record_issue(self, filepath, line_number):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100119 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +0100120 if filepath not in self.files_with_issues.keys():
121 self.files_with_issues[filepath] = []
122 self.files_with_issues[filepath].append(line_number)
123
Darryl Green10d9ce32018-02-28 10:02:55 +0000124 def output_file_issues(self, logger):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100125 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000126 if self.files_with_issues.values():
127 logger.info(self.heading)
128 for filename, lines in sorted(self.files_with_issues.items()):
129 if lines:
130 logger.info("{}: {}".format(
131 filename, ", ".join(str(x) for x in lines)
132 ))
133 else:
134 logger.info(filename)
135 logger.info("")
136
Gilles Peskineffaef812020-05-10 16:57:59 +0200137BINARY_FILE_PATH_RE_LIST = [
138 r'docs/.*\.pdf\Z',
139 r'programs/fuzz/corpuses/[^.]+\Z',
140 r'tests/data_files/[^.]+\Z',
141 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
142 r'tests/data_files/.*\.req\.[^/]+\Z',
143 r'tests/data_files/.*malformed[^/]+\Z',
144 r'tests/data_files/format_pkcs12\.fmt\Z',
145]
146BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
147
Gilles Peskined5240ec2019-02-25 20:59:05 +0100148class LineIssueTracker(FileIssueTracker):
149 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000150
Gilles Peskined5240ec2019-02-25 20:59:05 +0100151 To implement a checker that processes files line by line, inherit from
152 this class and implement `line_with_issue`.
153 """
154
Gilles Peskineffaef812020-05-10 16:57:59 +0200155 # Exclude binary files.
156 path_exemptions = BINARY_FILE_PATH_RE
157
Gilles Peskined5240ec2019-02-25 20:59:05 +0100158 def issue_with_line(self, line, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100159 """Check the specified line for the issue that this class is for.
160
161 Subclasses must implement this method.
162 """
Gilles Peskined5240ec2019-02-25 20:59:05 +0100163 raise NotImplementedError
164
165 def check_file_line(self, filepath, line, line_number):
166 if self.issue_with_line(line, filepath):
167 self.record_issue(filepath, line_number)
168
169 def check_file_for_issue(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100170 """Check the lines of the specified file.
171
172 Subclasses must implement the ``issue_with_line`` method.
173 """
Gilles Peskined5240ec2019-02-25 20:59:05 +0100174 with open(filepath, "rb") as f:
175 for i, line in enumerate(iter(f.readline, b"")):
176 self.check_file_line(filepath, line, i + 1)
177
Gilles Peskinececc7262020-03-24 22:26:01 +0100178
179def is_windows_file(filepath):
180 _root, ext = os.path.splitext(filepath)
Gilles Peskine40182512020-05-10 17:36:51 +0200181 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskinececc7262020-03-24 22:26:01 +0100182
183
Gilles Peskined5240ec2019-02-25 20:59:05 +0100184class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100185 """Track files with bad permissions.
186
187 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000188
Gilles Peskine21e85f72019-02-25 21:10:04 +0100189 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000190
191 def check_file_for_issue(self, filepath):
Gilles Peskine6fc52152019-02-25 21:24:27 +0100192 is_executable = os.access(filepath, os.X_OK)
193 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
194 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000195 self.files_with_issues[filepath] = None
196
197
Gilles Peskined5240ec2019-02-25 20:59:05 +0100198class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100199 """Track files that end with an incomplete line
200 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000201
Gilles Peskine21e85f72019-02-25 21:10:04 +0100202 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000203
Gilles Peskineffaef812020-05-10 16:57:59 +0200204 path_exemptions = BINARY_FILE_PATH_RE
205
Darryl Green10d9ce32018-02-28 10:02:55 +0000206 def check_file_for_issue(self, filepath):
207 with open(filepath, "rb") as f:
Gilles Peskine66de3112020-05-10 17:36:42 +0200208 try:
209 f.seek(-1, 2)
210 except OSError:
211 # This script only works on regular files. If we can't seek
212 # 1 before the end, it means that this position is before
213 # the beginning of the file, i.e. that the file is empty.
214 return
215 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000216 self.files_with_issues[filepath] = None
217
218
Gilles Peskined5240ec2019-02-25 20:59:05 +0100219class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100220 """Track files that start with a UTF-8 BOM.
221 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000222
Gilles Peskine21e85f72019-02-25 21:10:04 +0100223 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000224
Gilles Peskinee856ba12020-05-10 16:52:44 +0200225 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskineffaef812020-05-10 16:57:59 +0200226 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskinececc7262020-03-24 22:26:01 +0100227
Darryl Green10d9ce32018-02-28 10:02:55 +0000228 def check_file_for_issue(self, filepath):
229 with open(filepath, "rb") as f:
230 if f.read().startswith(codecs.BOM_UTF8):
231 self.files_with_issues[filepath] = None
232
233
Gilles Peskinececc7262020-03-24 22:26:01 +0100234class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100235 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000236
Gilles Peskinececc7262020-03-24 22:26:01 +0100237 heading = "Non-Unix line endings:"
238
239 def should_check_file(self, filepath):
Gilles Peskinee6f1f242020-05-10 16:57:16 +0200240 if not super().should_check_file(filepath):
241 return False
Gilles Peskinececc7262020-03-24 22:26:01 +0100242 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000243
Gilles Peskined5240ec2019-02-25 20:59:05 +0100244 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000245 return b"\r" in line
246
247
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100248class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine368ccd42020-04-01 13:35:46 +0200249 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100250
251 heading = "Non-Windows line endings:"
252
253 def should_check_file(self, filepath):
Gilles Peskinee6f1f242020-05-10 16:57:16 +0200254 if not super().should_check_file(filepath):
255 return False
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100256 return is_windows_file(filepath)
257
258 def issue_with_line(self, line, _filepath):
Gilles Peskine368ccd42020-04-01 13:35:46 +0200259 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100260
261
Gilles Peskined5240ec2019-02-25 20:59:05 +0100262class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100263 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000264
Gilles Peskine21e85f72019-02-25 21:10:04 +0100265 heading = "Trailing whitespace:"
Gilles Peskinee856ba12020-05-10 16:52:44 +0200266 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000267
Gilles Peskined5240ec2019-02-25 20:59:05 +0100268 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000269 return line.rstrip(b"\r\n") != line.rstrip()
270
271
Gilles Peskined5240ec2019-02-25 20:59:05 +0100272class TabIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100273 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000274
Gilles Peskine21e85f72019-02-25 21:10:04 +0100275 heading = "Tabs present:"
Gilles Peskinee856ba12020-05-10 16:52:44 +0200276 suffix_exemptions = frozenset([
Gilles Peskine43c74d22020-05-10 17:37:02 +0200277 ".pem", # some openssl dumps have tabs
Gilles Peskinececc7262020-03-24 22:26:01 +0100278 ".sln",
Gilles Peskined69f51b2020-03-24 22:01:28 +0100279 "/Makefile",
280 "/generate_visualc_files.pl",
Gilles Peskine21e85f72019-02-25 21:10:04 +0100281 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000282
Gilles Peskined5240ec2019-02-25 20:59:05 +0100283 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000284 return b"\t" in line
285
286
Gilles Peskined5240ec2019-02-25 20:59:05 +0100287class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100288 """Track lines with merge artifacts.
289 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100290
Gilles Peskine21e85f72019-02-25 21:10:04 +0100291 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100292
Gilles Peskined5240ec2019-02-25 20:59:05 +0100293 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100294 # Detect leftover git conflict markers.
295 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
296 return True
297 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
298 return True
299 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskined5240ec2019-02-25 20:59:05 +0100300 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100301 return True
302 return False
303
Darryl Green10d9ce32018-02-28 10:02:55 +0000304
Gilles Peskine5d1dfd42020-03-24 18:25:17 +0100305class IntegrityChecker:
Gilles Peskine76605492019-02-25 20:35:31 +0100306 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000307
308 def __init__(self, log_file):
Gilles Peskine76605492019-02-25 20:35:31 +0100309 """Instantiate the sanity checker.
310 Check files under the current directory.
311 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000312 self.check_repo_path()
313 self.logger = None
314 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000315 self.issues_to_check = [
316 PermissionIssueTracker(),
317 EndOfFileNewlineIssueTracker(),
318 Utf8BomIssueTracker(),
Gilles Peskinececc7262020-03-24 22:26:01 +0100319 UnixLineEndingIssueTracker(),
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100320 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000321 TrailingWhitespaceIssueTracker(),
322 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100323 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000324 ]
325
Gilles Peskine76605492019-02-25 20:35:31 +0100326 @staticmethod
327 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000328 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
329 raise Exception("Must be run from Mbed TLS root")
330
331 def setup_logger(self, log_file, level=logging.INFO):
332 self.logger = logging.getLogger()
333 self.logger.setLevel(level)
334 if log_file:
335 handler = logging.FileHandler(log_file)
336 self.logger.addHandler(handler)
337 else:
338 console = logging.StreamHandler()
339 self.logger.addHandler(console)
340
Gilles Peskinece5d8542020-05-10 17:18:06 +0200341 @staticmethod
342 def collect_files():
343 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
344 bytes_filepaths = bytes_output.split(b'\0')[:-1]
345 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
346 # Prepend './' to files in the top-level directory so that
347 # something like `'/Makefile' in fp` matches in the top-level
348 # directory as well as in subdirectories.
349 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
350 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200351
Darryl Green10d9ce32018-02-28 10:02:55 +0000352 def check_files(self):
Gilles Peskinece5d8542020-05-10 17:18:06 +0200353 for issue_to_check in self.issues_to_check:
354 for filepath in self.collect_files():
355 if issue_to_check.should_check_file(filepath):
356 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000357
358 def output_issues(self):
359 integrity_return_code = 0
360 for issue_to_check in self.issues_to_check:
361 if issue_to_check.files_with_issues:
362 integrity_return_code = 1
363 issue_to_check.output_file_issues(self.logger)
364 return integrity_return_code
365
366
367def run_main():
Gilles Peskine79cfef02019-07-04 19:31:02 +0200368 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000369 parser.add_argument(
370 "-l", "--log_file", type=str, help="path to optional output log",
371 )
372 check_args = parser.parse_args()
373 integrity_check = IntegrityChecker(check_args.log_file)
374 integrity_check.check_files()
375 return_code = integrity_check.output_issues()
376 sys.exit(return_code)
377
378
379if __name__ == "__main__":
380 run_main()