1#!/usr/bin/env python3 2 3# Copyright The Mbed TLS Contributors 4# 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. 17 18""" 19This script checks the current state of the source code for minor issues, 20including incorrect file permissions, presence of tabs, non-Unix line endings, 21trailing whitespace, and presence of UTF-8 BOM. 22Note: requires python 3, must be run from Mbed TLS root. 23""" 24 25import os 26import argparse 27import logging 28import codecs 29import re 30import subprocess 31import sys 32try: 33 from typing import FrozenSet, Optional, Pattern # pylint: disable=unused-import 34except ImportError: 35 pass 36 37import scripts_path # pylint: disable=unused-import 38from mbedtls_dev import build_tree 39 40 41class FileIssueTracker: 42 """Base class for file-wide issue tracking. 43 44 To implement a checker that processes a file as a whole, inherit from 45 this class and implement `check_file_for_issue` and define ``heading``. 46 47 ``suffix_exemptions``: files whose name ends with a string in this set 48 will not be checked. 49 50 ``path_exemptions``: files whose path (relative to the root of the source 51 tree) matches this regular expression will not be checked. This can be 52 ``None`` to match no path. Paths are normalized and converted to ``/`` 53 separators before matching. 54 55 ``heading``: human-readable description of the issue 56 """ 57 58 suffix_exemptions = frozenset() #type: FrozenSet[str] 59 path_exemptions = None #type: Optional[Pattern[str]] 60 # heading must be defined in derived classes. 61 # pylint: disable=no-member 62 63 def __init__(self): 64 self.files_with_issues = {} 65 66 @staticmethod 67 def normalize_path(filepath): 68 """Normalize ``filepath`` with / as the directory separator.""" 69 filepath = os.path.normpath(filepath) 70 # On Windows, we may have backslashes to separate directories. 71 # We need slashes to match exemption lists. 72 seps = os.path.sep 73 if os.path.altsep is not None: 74 seps += os.path.altsep 75 return '/'.join(filepath.split(seps)) 76 77 def should_check_file(self, filepath): 78 """Whether the given file name should be checked. 79 80 Files whose name ends with a string listed in ``self.suffix_exemptions`` 81 or whose path matches ``self.path_exemptions`` will not be checked. 82 """ 83 for files_exemption in self.suffix_exemptions: 84 if filepath.endswith(files_exemption): 85 return False 86 if self.path_exemptions and \ 87 re.match(self.path_exemptions, self.normalize_path(filepath)): 88 return False 89 return True 90 91 def check_file_for_issue(self, filepath): 92 """Check the specified file for the issue that this class is for. 93 94 Subclasses must implement this method. 95 """ 96 raise NotImplementedError 97 98 def record_issue(self, filepath, line_number): 99 """Record that an issue was found at the specified location.""" 100 if filepath not in self.files_with_issues.keys(): 101 self.files_with_issues[filepath] = [] 102 self.files_with_issues[filepath].append(line_number) 103 104 def output_file_issues(self, logger): 105 """Log all the locations where the issue was found.""" 106 if self.files_with_issues.values(): 107 logger.info(self.heading) 108 for filename, lines in sorted(self.files_with_issues.items()): 109 if lines: 110 logger.info("{}: {}".format( 111 filename, ", ".join(str(x) for x in lines) 112 )) 113 else: 114 logger.info(filename) 115 logger.info("") 116 117BINARY_FILE_PATH_RE_LIST = [ 118 r'docs/.*\.pdf\Z', 119 r'programs/fuzz/corpuses/[^.]+\Z', 120 r'tests/data_files/[^.]+\Z', 121 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z', 122 r'tests/data_files/.*\.req\.[^/]+\Z', 123 r'tests/data_files/.*malformed[^/]+\Z', 124 r'tests/data_files/format_pkcs12\.fmt\Z', 125 r'tests/data_files/.*\.bin\Z', 126] 127BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST)) 128 129class LineIssueTracker(FileIssueTracker): 130 """Base class for line-by-line issue tracking. 131 132 To implement a checker that processes files line by line, inherit from 133 this class and implement `line_with_issue`. 134 """ 135 136 # Exclude binary files. 137 path_exemptions = BINARY_FILE_PATH_RE 138 139 def issue_with_line(self, line, filepath, line_number): 140 """Check the specified line for the issue that this class is for. 141 142 Subclasses must implement this method. 143 """ 144 raise NotImplementedError 145 146 def check_file_line(self, filepath, line, line_number): 147 if self.issue_with_line(line, filepath, line_number): 148 self.record_issue(filepath, line_number) 149 150 def check_file_for_issue(self, filepath): 151 """Check the lines of the specified file. 152 153 Subclasses must implement the ``issue_with_line`` method. 154 """ 155 with open(filepath, "rb") as f: 156 for i, line in enumerate(iter(f.readline, b"")): 157 self.check_file_line(filepath, line, i + 1) 158 159 160def is_windows_file(filepath): 161 _root, ext = os.path.splitext(filepath) 162 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj') 163 164 165class PermissionIssueTracker(FileIssueTracker): 166 """Track files with bad permissions. 167 168 Files that are not executable scripts must not be executable.""" 169 170 heading = "Incorrect permissions:" 171 172 # .py files can be either full scripts or modules, so they may or may 173 # not be executable. 174 suffix_exemptions = frozenset({".py"}) 175 176 def check_file_for_issue(self, filepath): 177 is_executable = os.access(filepath, os.X_OK) 178 should_be_executable = filepath.endswith((".sh", ".pl")) 179 if is_executable != should_be_executable: 180 self.files_with_issues[filepath] = None 181 182 183class ShebangIssueTracker(FileIssueTracker): 184 """Track files with a bad, missing or extraneous shebang line. 185 186 Executable scripts must start with a valid shebang (#!) line. 187 """ 188 189 heading = "Invalid shebang line:" 190 191 # Allow either /bin/sh, /bin/bash, or /usr/bin/env. 192 # Allow at most one argument (this is a Linux limitation). 193 # For sh and bash, the argument if present must be options. 194 # For env, the argument must be the base name of the interpreter. 195 _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?' 196 rb'|/usr/bin/env ([^\n /]+))$') 197 _extensions = { 198 b'bash': 'sh', 199 b'perl': 'pl', 200 b'python3': 'py', 201 b'sh': 'sh', 202 } 203 204 def is_valid_shebang(self, first_line, filepath): 205 m = re.match(self._shebang_re, first_line) 206 if not m: 207 return False 208 interpreter = m.group(1) or m.group(2) 209 if interpreter not in self._extensions: 210 return False 211 if not filepath.endswith('.' + self._extensions[interpreter]): 212 return False 213 return True 214 215 def check_file_for_issue(self, filepath): 216 is_executable = os.access(filepath, os.X_OK) 217 with open(filepath, "rb") as f: 218 first_line = f.readline() 219 if first_line.startswith(b'#!'): 220 if not is_executable: 221 # Shebang on a non-executable file 222 self.files_with_issues[filepath] = None 223 elif not self.is_valid_shebang(first_line, filepath): 224 self.files_with_issues[filepath] = [1] 225 elif is_executable: 226 # Executable without a shebang 227 self.files_with_issues[filepath] = None 228 229 230class EndOfFileNewlineIssueTracker(FileIssueTracker): 231 """Track files that end with an incomplete line 232 (no newline character at the end of the last line).""" 233 234 heading = "Missing newline at end of file:" 235 236 path_exemptions = BINARY_FILE_PATH_RE 237 238 def check_file_for_issue(self, filepath): 239 with open(filepath, "rb") as f: 240 try: 241 f.seek(-1, 2) 242 except OSError: 243 # This script only works on regular files. If we can't seek 244 # 1 before the end, it means that this position is before 245 # the beginning of the file, i.e. that the file is empty. 246 return 247 if f.read(1) != b"\n": 248 self.files_with_issues[filepath] = None 249 250 251class Utf8BomIssueTracker(FileIssueTracker): 252 """Track files that start with a UTF-8 BOM. 253 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM.""" 254 255 heading = "UTF-8 BOM present:" 256 257 suffix_exemptions = frozenset([".vcxproj", ".sln"]) 258 path_exemptions = BINARY_FILE_PATH_RE 259 260 def check_file_for_issue(self, filepath): 261 with open(filepath, "rb") as f: 262 if f.read().startswith(codecs.BOM_UTF8): 263 self.files_with_issues[filepath] = None 264 265 266class UnicodeIssueTracker(LineIssueTracker): 267 """Track lines with invalid characters or invalid text encoding.""" 268 269 heading = "Invalid UTF-8 or forbidden character:" 270 271 # Only allow valid UTF-8, and only other explicitly allowed characters. 272 # We deliberately exclude all characters that aren't a simple non-blank, 273 # non-zero-width glyph, apart from a very small set (tab, ordinary space, 274 # line breaks, "basic" no-break space and soft hyphen). In particular, 275 # non-ASCII control characters, combinig characters, and Unicode state 276 # changes (e.g. right-to-left text) are forbidden. 277 # Note that we do allow some characters with a risk of visual confusion, 278 # for example '-' (U+002D HYPHEN-MINUS) vs '' (U+00AD SOFT HYPHEN) vs 279 # '‐' (U+2010 HYPHEN), or 'A' (U+0041 LATIN CAPITAL LETTER A) vs 280 # 'Α' (U+0391 GREEK CAPITAL LETTER ALPHA). 281 GOOD_CHARACTERS = ''.join([ 282 '\t\n\r -~', # ASCII (tabs and line endings are checked separately) 283 '\u00A0-\u00FF', # Latin-1 Supplement (for NO-BREAK SPACE and punctuation) 284 '\u2010-\u2027\u2030-\u205E', # General Punctuation (printable) 285 '\u2070\u2071\u2074-\u208E\u2090-\u209C', # Superscripts and Subscripts 286 '\u2190-\u21FF', # Arrows 287 '\u2200-\u22FF', # Mathematical Symbols 288 '\u2500-\u257F' # Box Drawings characters used in markdown trees 289 ]) 290 # Allow any of the characters and ranges above, and anything classified 291 # as a word constituent. 292 GOOD_CHARACTERS_RE = re.compile(r'[\w{}]+\Z'.format(GOOD_CHARACTERS)) 293 294 def issue_with_line(self, line, _filepath, line_number): 295 try: 296 text = line.decode('utf-8') 297 except UnicodeDecodeError: 298 return True 299 if line_number == 1 and text.startswith('\uFEFF'): 300 # Strip BOM (U+FEFF ZERO WIDTH NO-BREAK SPACE) at the beginning. 301 # Which files are allowed to have a BOM is handled in 302 # Utf8BomIssueTracker. 303 text = text[1:] 304 return not self.GOOD_CHARACTERS_RE.match(text) 305 306class UnixLineEndingIssueTracker(LineIssueTracker): 307 """Track files with non-Unix line endings (i.e. files with CR).""" 308 309 heading = "Non-Unix line endings:" 310 311 def should_check_file(self, filepath): 312 if not super().should_check_file(filepath): 313 return False 314 return not is_windows_file(filepath) 315 316 def issue_with_line(self, line, _filepath, _line_number): 317 return b"\r" in line 318 319 320class WindowsLineEndingIssueTracker(LineIssueTracker): 321 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF).""" 322 323 heading = "Non-Windows line endings:" 324 325 def should_check_file(self, filepath): 326 if not super().should_check_file(filepath): 327 return False 328 return is_windows_file(filepath) 329 330 def issue_with_line(self, line, _filepath, _line_number): 331 return not line.endswith(b"\r\n") or b"\r" in line[:-2] 332 333 334class TrailingWhitespaceIssueTracker(LineIssueTracker): 335 """Track lines with trailing whitespace.""" 336 337 heading = "Trailing whitespace:" 338 suffix_exemptions = frozenset([".dsp", ".md"]) 339 340 def issue_with_line(self, line, _filepath, _line_number): 341 return line.rstrip(b"\r\n") != line.rstrip() 342 343 344class TabIssueTracker(LineIssueTracker): 345 """Track lines with tabs.""" 346 347 heading = "Tabs present:" 348 suffix_exemptions = frozenset([ 349 ".pem", # some openssl dumps have tabs 350 ".sln", 351 "/Makefile", 352 "/Makefile.inc", 353 "/generate_visualc_files.pl", 354 ]) 355 356 def issue_with_line(self, line, _filepath, _line_number): 357 return b"\t" in line 358 359 360class MergeArtifactIssueTracker(LineIssueTracker): 361 """Track lines with merge artifacts. 362 These are leftovers from a ``git merge`` that wasn't fully edited.""" 363 364 heading = "Merge artifact:" 365 366 def issue_with_line(self, line, _filepath, _line_number): 367 # Detect leftover git conflict markers. 368 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '): 369 return True 370 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3 371 return True 372 if line.rstrip(b'\r\n') == b'=======' and \ 373 not _filepath.endswith('.md'): 374 return True 375 return False 376 377 378class IntegrityChecker: 379 """Sanity-check files under the current directory.""" 380 381 def __init__(self, log_file): 382 """Instantiate the sanity checker. 383 Check files under the current directory. 384 Write a report of issues to log_file.""" 385 build_tree.check_repo_path() 386 self.logger = None 387 self.setup_logger(log_file) 388 self.issues_to_check = [ 389 PermissionIssueTracker(), 390 ShebangIssueTracker(), 391 EndOfFileNewlineIssueTracker(), 392 Utf8BomIssueTracker(), 393 UnicodeIssueTracker(), 394 UnixLineEndingIssueTracker(), 395 WindowsLineEndingIssueTracker(), 396 TrailingWhitespaceIssueTracker(), 397 TabIssueTracker(), 398 MergeArtifactIssueTracker(), 399 ] 400 401 def setup_logger(self, log_file, level=logging.INFO): 402 self.logger = logging.getLogger() 403 self.logger.setLevel(level) 404 if log_file: 405 handler = logging.FileHandler(log_file) 406 self.logger.addHandler(handler) 407 else: 408 console = logging.StreamHandler() 409 self.logger.addHandler(console) 410 411 @staticmethod 412 def collect_files(): 413 bytes_output = subprocess.check_output(['git', 'ls-files', '-z']) 414 bytes_filepaths = bytes_output.split(b'\0')[:-1] 415 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths) 416 # Prepend './' to files in the top-level directory so that 417 # something like `'/Makefile' in fp` matches in the top-level 418 # directory as well as in subdirectories. 419 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp) 420 for fp in ascii_filepaths] 421 422 def check_files(self): 423 for issue_to_check in self.issues_to_check: 424 for filepath in self.collect_files(): 425 if issue_to_check.should_check_file(filepath): 426 issue_to_check.check_file_for_issue(filepath) 427 428 def output_issues(self): 429 integrity_return_code = 0 430 for issue_to_check in self.issues_to_check: 431 if issue_to_check.files_with_issues: 432 integrity_return_code = 1 433 issue_to_check.output_file_issues(self.logger) 434 return integrity_return_code 435 436 437def run_main(): 438 parser = argparse.ArgumentParser(description=__doc__) 439 parser.add_argument( 440 "-l", "--log_file", type=str, help="path to optional output log", 441 ) 442 check_args = parser.parse_args() 443 integrity_check = IntegrityChecker(check_args.log_file) 444 integrity_check.check_files() 445 return_code = integrity_check.output_issues() 446 sys.exit(return_code) 447 448 449if __name__ == "__main__": 450 run_main() 451