xref: /openbsd-src/regress/lib/libcrypto/x509/make-dir-roots.pl (revision b68b63e374015cf0aafaaec62a065293b1be59e3)
1#!/usr/bin/perl
2
3#
4# Copyright (c) 2021 Joel Sing <jsing@openbsd.org>
5#
6# Permission to use, copy, modify, and distribute this software for any
7# purpose with or without fee is hereby granted, provided that the above
8# copyright notice and this permission notice appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17#
18
19sub root_pem_to_dir() {
20	$certs = 0;
21	$in_cert = 0;
22
23	($roots_file, $certs_dir) = @_;
24
25	open ROOTS, "<$roots_file" or
26		die "failed to open roots file '$roots_file'";
27	while (<ROOTS>) {
28		if ($_ eq "-----BEGIN CERTIFICATE-----\n") {
29			$in_cert = 1;
30			$cert_path = "$certs_dir/ca-$certs.pem";
31			open CERT, ">$cert_path" or
32				die "failed to open '$cert_path'";
33			$certs++;
34		}
35		if ($in_cert) {
36			print CERT $_;
37		}
38		if ($_ eq "-----END CERTIFICATE-----\n") {
39			$in_cert = 0;
40		}
41	}
42	close ROOTS;
43
44	my @args = ("openssl", "certhash", $certs_dir);
45	system(@args) == 0 or die "certhash failed";
46}
47
48if (scalar @ARGV != 2) {
49	print("$0 <certs-path> <output-dir>\n");
50	exit(1);
51}
52$certs_path = shift @ARGV;
53$output_dir = shift @ARGV;
54
55opendir CERTS, $certs_path or
56	die "failed to open certs directory '$certs_path'";
57while (readdir CERTS) {
58	next if ($_ !~ '^[0-9]+[a-z]?$');
59
60	$roots_file = join("/", $certs_path, $_, "roots.pem");
61	$roots_dir = join("/", $output_dir, $_, "roots");
62
63	mkdir "$output_dir";
64	mkdir "$output_dir/$_";
65	mkdir "$output_dir/$_/roots";
66
67	&root_pem_to_dir($roots_file, $roots_dir);
68}
69closedir CERTS;
70