• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "microdroid/signature.h"
18 
19 #include <android-base/endian.h>
20 #include <android-base/file.h>
21 
22 using android::base::ErrnoError;
23 using android::base::Error;
24 using android::base::Result;
25 
26 namespace android {
27 namespace microdroid {
28 
ReadMicrodroidSignature(const std::string & path)29 Result<MicrodroidSignature> ReadMicrodroidSignature(const std::string& path) {
30     std::string content;
31     if (!base::ReadFileToString(path, &content)) {
32         return ErrnoError() << "Failed to read " << path;
33     }
34 
35     // read length prefix (4-byte, big-endian)
36     uint32_t size;
37     const size_t length_prefix_bytes = sizeof(size);
38     if (content.size() < length_prefix_bytes) {
39         return Error() << "Invalid signature: size == " << content.size();
40     }
41     size = be32toh(*reinterpret_cast<uint32_t*>(content.data()));
42     if (content.size() < length_prefix_bytes + size) {
43         return Error() << "Invalid signature: size(" << size << ") mimatches to the content size("
44                        << content.size() - length_prefix_bytes << ")";
45     }
46     content = content.substr(length_prefix_bytes, size);
47 
48     // parse content
49     MicrodroidSignature signature;
50     if (!signature.ParseFromString(content)) {
51         return Error() << "Can't parse MicrodroidSignature from " << path;
52     }
53     return signature;
54 }
55 
WriteMicrodroidSignature(const MicrodroidSignature & signature,std::ostream & out)56 Result<void> WriteMicrodroidSignature(const MicrodroidSignature& signature, std::ostream& out) {
57     // prepare content
58     std::string content;
59     if (!signature.SerializeToString(&content)) {
60         return Error() << "Failed to write protobuf.";
61     }
62 
63     // write length prefix (4-byte, big-endian)
64     uint32_t size = htobe32(static_cast<uint32_t>(content.size()));
65     out.write(reinterpret_cast<const char*>(&size), sizeof(size));
66 
67     // write content
68     out << content;
69 
70     return {};
71 }
72 
73 } // namespace microdroid
74 } // namespace android