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/util/proto_helper.h"
16
17 #include <cstddef>
18 #include <cstdint>
19 #include <string>
20 #include <utility>
21 #include <vector>
22
23 #include "absl/status/status.h"
24 #include "absl/status/statusor.h"
25 #include "google/protobuf/message_lite.h"
26 #include "sandboxed_api/util/proto_arg.pb.h"
27
28 namespace sapi {
29
30 namespace internal {
31
DeserializeProto(const char * data,size_t len,google::protobuf::MessageLite & output)32 absl::Status DeserializeProto(const char* data, size_t len,
33 google::protobuf::MessageLite& output) {
34 ProtoArg envelope;
35 if (!envelope.ParseFromArray(data, len)) {
36 return absl::InternalError("Unable to parse proto from array");
37 }
38
39 auto pb_data = envelope.protobuf_data();
40 if (!output.ParseFromArray(pb_data.data(), pb_data.size())) {
41 return absl::InternalError("Unable to parse proto from envelope data");
42 }
43 return absl::OkStatus();
44 }
45
46 } // namespace internal
47
SerializeProto(const google::protobuf::MessageLite & proto)48 absl::StatusOr<std::vector<uint8_t>> SerializeProto(
49 const google::protobuf::MessageLite& proto) {
50 // Wrap protobuf in a envelope so that we know the name of the protobuf
51 // structure when deserializing in the sandboxee.
52 ProtoArg proto_arg;
53 std::string proto_data;
54 if (!proto.SerializeToString(&proto_data)) {
55 return absl::InternalError("Unable to serialize proto data");
56 }
57 proto_arg.set_protobuf_data(std::move(proto_data));
58 proto_arg.set_full_name(proto.GetTypeName());
59 std::vector<uint8_t> serialized_proto(proto_arg.ByteSizeLong());
60 if (!proto_arg.SerializeToArray(serialized_proto.data(),
61 serialized_proto.size())) {
62 return absl::InternalError("Unable to serialize proto to array");
63 }
64 return serialized_proto;
65 }
66
67 } // namespace sapi
68