blob: 868033db579dd7a65c7647bdca868c3313d385a3 [file] [log] [blame]
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -08001// 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//
Christian Blichmannd4514782022-01-28 01:38:27 -08007// https://www.apache.org/licenses/LICENSE-2.0
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -08008//
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
Wiktor Garbacz127176d2023-08-24 06:23:03 -070017#include <cstddef>
18#include <cstdint>
19#include <string>
20#include <vector>
21
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -080022#include "absl/status/status.h"
Wiktor Garbacz127176d2023-08-24 06:23:03 -070023#include "absl/status/statusor.h"
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -080024
25namespace sapi {
26
27namespace internal {
28
29absl::Status DeserializeProto(const char* data, size_t len,
Oliver Kunz077203f2022-03-03 04:47:46 -080030 google::protobuf::MessageLite& output) {
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -080031 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
45absl::StatusOr<std::vector<uint8_t>> SerializeProto(
Oliver Kunz077203f2022-03-03 04:47:46 -080046 const google::protobuf::MessageLite& proto) {
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -080047 // 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());
Oliver Kunz077203f2022-03-03 04:47:46 -080051 proto_arg.set_full_name(proto.GetTypeName());
Wiktor Garbacz38a1cb72022-01-19 02:37:25 -080052 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