Andreea Costinas | c7d5ad0 | 2020-03-09 09:41:51 +0100 | [diff] [blame] | 1 | // Copyright 2020 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "system-proxy/protobuf_util.h" |
| 6 | |
| 7 | #include <vector> |
| 8 | |
| 9 | #include <base/files/file_util.h> |
| 10 | |
| 11 | namespace system_proxy { |
| 12 | |
| 13 | bool ReadProtobuf(int in_fd, google::protobuf::MessageLite* message) { |
| 14 | size_t proto_size = 0; |
| 15 | // The first part of the message will be the size of the actual message. |
| 16 | // Because the message is a serialized protobuf, we need to read the whole |
| 17 | // message before deserializing it. |
| 18 | if (!base::ReadFromFD(in_fd, reinterpret_cast<char*>(&proto_size), |
| 19 | sizeof(proto_size))) |
| 20 | return false; |
| 21 | std::vector<char> buf(proto_size); |
| 22 | // Tries to read exactly buf.size() bytes from in_fd and returns true if |
| 23 | // succeeded, false otherwise. If the read() get interrupted by EINTR it will |
| 24 | // resume reading by itself with a limited number of attempts. |
| 25 | if (!base::ReadFromFD(in_fd, buf.data(), buf.size())) |
| 26 | return false; |
| 27 | |
| 28 | return message->ParseFromArray(buf.data(), buf.size()); |
| 29 | } |
| 30 | |
| 31 | bool WriteProtobuf(int out_fd, const google::protobuf::MessageLite& message) { |
| 32 | size_t size = message.ByteSizeLong(); |
| 33 | char* size_data = reinterpret_cast<char*>(&size); |
| 34 | std::vector<char> buf(size_data, size_data + sizeof(size)); |
| 35 | buf.resize(size + sizeof(size)); |
| 36 | |
| 37 | if (!message.SerializeToArray(buf.data() + sizeof(size), size)) |
| 38 | return false; |
| 39 | |
| 40 | return base::WriteFileDescriptor(out_fd, buf.data(), buf.size()); |
| 41 | } |
| 42 | } // namespace system_proxy |