1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "sandboxed_api/proto_helper.h"
16
17 #include <cstddef>
18 #include <cstdint>
19 #include <string>
20 #include <vector>
21
22 #include "absl/status/status.h"
23 #include "absl/status/statusor.h"
24
25 namespace sapi {
26
27 namespace internal {
28
DeserializeProto(const char * data,size_t len,google::protobuf::MessageLite & output)29 absl::Status DeserializeProto(const char* data, size_t len,
30 google::protobuf::MessageLite& output) {
31 ProtoArg envelope;
32 if (!envelope.ParseFromArray(data, len)) {
33 return absl::InternalError("Unable to parse proto from array");
34 }
35
36 auto pb_data = envelope.protobuf_data();
37 if (!output.ParseFromArray(pb_data.data(), pb_data.size())) {
38 return absl::InternalError("Unable to parse proto from envelope data");
39 }
40 return absl::OkStatus();
41 }
42
43 } // namespace internal
44
SerializeProto(const google::protobuf::MessageLite & proto)45 absl::StatusOr<std::vector<uint8_t>> SerializeProto(
46 const google::protobuf::MessageLite& proto) {
47 // Wrap protobuf in a envelope so that we know the name of the protobuf
48 // structure when deserializing in the sandboxee.
49 ProtoArg proto_arg;
50 proto_arg.set_protobuf_data(proto.SerializeAsString());
51 proto_arg.set_full_name(proto.GetTypeName());
52 std::vector<uint8_t> serialized_proto(proto_arg.ByteSizeLong());
53 if (!proto_arg.SerializeToArray(serialized_proto.data(),
54 serialized_proto.size())) {
55 return absl::InternalError("Unable to serialize proto to array");
56 }
57 return serialized_proto;
58 }
59
60 } // namespace sapi
61