1#!/usr/bin/env python3 2 3""" 4Generate `tests/src/test_certs.h` which includes certficaties/keys/certificate list for testing. 5""" 6 7# 8# Copyright The Mbed TLS Contributors 9# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 10 11 12import os 13import sys 14import argparse 15import jinja2 16 17class MacroDefineAction(argparse.Action): 18 #pylint: disable=signature-differs, too-few-public-methods 19 def __call__(self, parser, namespace, values, option_string): 20 if not hasattr(namespace, 'values'): 21 setattr(namespace, 'values', []) 22 macro_name, filename = values 23 if self.dest in ('string', 'binary') and not os.path.exists(filename): 24 raise argparse.ArgumentError( 25 None, '`{}`: Input file does not exist.'.format(filename)) 26 namespace.values.append((self.dest, macro_name, filename)) 27 28 29def macro_define_type(value): 30 ret = value.split('=', 1) 31 if len(ret) != 2: 32 raise argparse.ArgumentTypeError( 33 '`{}` is not MACRO=value format'.format(value)) 34 return ret 35 36 37def build_argparser(parser): 38 parser.description = __doc__ 39 parser.add_argument('--string', type=macro_define_type, action=MacroDefineAction, 40 metavar='MACRO_NAME=path/to/file', help='PEM to C string. ') 41 parser.add_argument('--binary', type=macro_define_type, action=MacroDefineAction, 42 metavar='MACRO_NAME=path/to/file', 43 help='DER to C arrary.') 44 parser.add_argument('--password', type=macro_define_type, action=MacroDefineAction, 45 metavar='MACRO_NAME=password', help='Password to C string.') 46 parser.add_argument('--output', type=str, required=True) 47 48 49def main(): 50 parser = argparse.ArgumentParser() 51 build_argparser(parser) 52 args = parser.parse_args() 53 return generate(**vars(args)) 54 55#pylint: disable=dangerous-default-value, unused-argument 56def generate(values=[], output=None, **kwargs): 57 """Generate C header file. 58 """ 59 this_dir = os.path.dirname(os.path.abspath(__file__)) 60 template_loader = jinja2.FileSystemLoader( 61 searchpath=os.path.join(this_dir, '..', 'data_files')) 62 template_env = jinja2.Environment( 63 loader=template_loader, lstrip_blocks=True, trim_blocks=True) 64 65 def read_as_c_array(filename): 66 with open(filename, 'rb') as f: 67 data = f.read(12) 68 while data: 69 yield ', '.join(['{:#04x}'.format(b) for b in data]) 70 data = f.read(12) 71 72 def read_lines(filename): 73 with open(filename) as f: 74 try: 75 for line in f: 76 yield line.strip() 77 except: 78 print(filename) 79 raise 80 81 def put_to_column(value, position=0): 82 return ' '*position + value 83 84 template_env.filters['read_as_c_array'] = read_as_c_array 85 template_env.filters['read_lines'] = read_lines 86 template_env.filters['put_to_column'] = put_to_column 87 88 template = template_env.get_template('test_certs.h.jinja2') 89 90 with open(output, 'w') as f: 91 f.write(template.render(macros=values)) 92 93 94if __name__ == '__main__': 95 sys.exit(main()) 96