Imported Upstream version 2.6.1
[platform/upstream/cryptsetup.git] / tests / fuzz / plain_json_proto_to_luks2.cc
1 /*
2  * cryptsetup LUKS2 protobuf to image converter
3  *
4  * Copyright (C) 2022-2023 Daniel Zatovic <daniel.zatovic@gmail.com>
5  * Copyright (C) 2022-2023 Red Hat, Inc. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <iostream>
23 #include <string>
24
25 #include <fcntl.h>
26 #include <unistd.h>
27
28 #include <google/protobuf/text_format.h>
29 #include <google/protobuf/io/zero_copy_stream_impl.h>
30
31 #include "plain_json_proto_to_luks2_converter.h"
32
33 using namespace json_proto;
34
35 int main(int argc, char *argv[]) {
36   LUKS2_both_headers headers;
37   LUKS2ProtoConverter converter;
38   int fd;
39
40   std::string out_img_name;
41
42   if (argc != 2) {
43     std::cerr << "Usage: " << argv[0] << " <LUKS2 proto>\n";
44     return EXIT_FAILURE;
45   }
46
47   fd = open(argv[1], O_RDONLY);
48   if (fd < 0) {
49     std::cerr << "Failed to open " << argv[1] << std::endl;
50     return EXIT_FAILURE;
51   }
52
53   google::protobuf::io::FileInputStream fileInput(fd);
54
55   if (!google::protobuf::TextFormat::Parse(&fileInput, &headers)) {
56     std::cerr << "Failed to parse protobuf " << argv[1] << std::endl;
57     close(fd);
58     return EXIT_FAILURE;
59   }
60   close(fd);
61
62   out_img_name = argv[1];
63   out_img_name += ".img";
64
65   fd = open(out_img_name.c_str(), O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC|O_TRUNC, 0644);
66   if (fd < 0) {
67     std::cerr << "Failed to open output file " << out_img_name << std::endl;
68     return EXIT_FAILURE;
69   }
70   converter.set_write_headers_only(false);
71   converter.convert(headers, fd);
72
73   close(fd);
74   return EXIT_SUCCESS;
75 }