blob: 4494917ef73cf577bd6589c59b7aeb4deab65894 [file] [log] [blame]
Jerry Yu58118692023-05-23 16:14:47 +08001#!/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
10#
11# Licensed under the Apache License, Version 2.0 (the "License"); you may
12# not use this file except in compliance with the License.
13# You may obtain a copy of the License at
14#
15# http://www.apache.org/licenses/LICENSE-2.0
16#
17# Unless required by applicable law or agreed to in writing, software
18# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20# See the License for the specific language governing permissions and
21# limitations under the License.
22
23
24import os
25import sys
26import argparse
27import jinja2
28
Jerry Yu99a82dd2023-05-24 15:02:11 +080029class MacroDefineAction(argparse.Action):
30 #pylint: disable=signature-differs, too-few-public-methods
Jerry Yu58118692023-05-23 16:14:47 +080031 def __call__(self, parser, namespace, values, option_string):
32 if not hasattr(namespace, 'values'):
33 setattr(namespace, 'values', [])
34 macro_name, filename = values
35 if self.dest in ('string', 'binary') and not os.path.exists(filename):
36 raise argparse.ArgumentError(
37 None, '`{}`: Input file does not exist.'.format(filename))
38 namespace.values.append((self.dest, macro_name, filename))
39
40
Jerry Yu99a82dd2023-05-24 15:02:11 +080041def macro_define_type(value):
Jerry Yu58118692023-05-23 16:14:47 +080042 ret = value.split('=', 1)
43 if len(ret) != 2:
44 raise argparse.ArgumentTypeError(
45 '`{}` is not MACRO=value format'.format(value))
46 return ret
47
48
49def build_argparser(parser):
50 parser.description = __doc__
Jerry Yu99a82dd2023-05-24 15:02:11 +080051 parser.add_argument('--string', type=macro_define_type, action=MacroDefineAction,
Jerry Yu58118692023-05-23 16:14:47 +080052 metavar='MACRO_NAME=path/to/file', help='PEM to C string. ')
Jerry Yu99a82dd2023-05-24 15:02:11 +080053 parser.add_argument('--binary', type=macro_define_type, action=MacroDefineAction,
54 metavar='MACRO_NAME=path/to/file',
Jerry Yu58118692023-05-23 16:14:47 +080055 help='DER to C arrary.')
Jerry Yu99a82dd2023-05-24 15:02:11 +080056 parser.add_argument('--password', type=macro_define_type, action=MacroDefineAction,
Jerry Yu58118692023-05-23 16:14:47 +080057 metavar='MACRO_NAME=password', help='Password to C string.')
58 parser.add_argument('--output', type=str, required=True)
59
60
61def main():
62 parser = argparse.ArgumentParser()
63 build_argparser(parser)
64 args = parser.parse_args()
65 return generate(**vars(args))
66
Jerry Yu99a82dd2023-05-24 15:02:11 +080067#pylint: disable=dangerous-default-value, unused-argument
68def generate(values=[], output=None, **kwargs):
69 """Generate C header file.
70 """
Jerry Yu58118692023-05-23 16:14:47 +080071 this_dir = os.path.dirname(os.path.abspath(__file__))
Jerry Yu58118692023-05-23 16:14:47 +080072 template_loader = jinja2.FileSystemLoader(
73 searchpath=os.path.join(this_dir, '..', 'data_files'))
74 template_env = jinja2.Environment(
75 loader=template_loader, lstrip_blocks=True, trim_blocks=True)
76
77 def read_as_c_array(filename):
78 with open(filename, 'rb') as f:
79 data = f.read(12)
80 while data:
81 yield ', '.join(['{:#04x}'.format(b) for b in data])
82 data = f.read(12)
83
84 def read_lines(filename):
85 with open(filename) as f:
86 try:
87 for line in f:
88 yield line.strip()
89 except:
90 print(filename)
91 raise
92
93 def put_to_column(value, position=0):
94 return ' '*position + value
95
96 template_env.filters['read_as_c_array'] = read_as_c_array
97 template_env.filters['read_lines'] = read_lines
98 template_env.filters['put_to_column'] = put_to_column
99
100 template = template_env.get_template('test_certs.h.jinja2')
101
102 with open(output, 'w') as f:
103 f.write(template.render(macros=values))
104
105
106if __name__ == '__main__':
107 sys.exit(main())