1  /*
2   * Copyright (C) 2019 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  #pragma once
18  
19  #include <sys/socket.h>
20  #include <unistd.h>
21  
22  #include <string>
23  
24  #include "result.h"
25  
26  namespace android {
27  namespace init {
28  
29  constexpr size_t kBufferSize = 4096;
30  
ReadMessage(int socket)31  inline Result<std::string> ReadMessage(int socket) {
32      char buffer[kBufferSize] = {};
33      auto result = TEMP_FAILURE_RETRY(recv(socket, buffer, sizeof(buffer), 0));
34      if (result == 0) {
35          return Error();
36      } else if (result < 0) {
37          return ErrnoError();
38      }
39      return std::string(buffer, result);
40  }
41  
42  template <typename T>
SendMessage(int socket,const T & message)43  Result<void> SendMessage(int socket, const T& message) {
44      std::string message_string;
45      if (!message.SerializeToString(&message_string)) {
46          return Error() << "Unable to serialize message";
47      }
48  
49      if (message_string.size() > kBufferSize) {
50          return Error() << "Serialized message too long to send";
51      }
52  
53      if (auto result =
54                  TEMP_FAILURE_RETRY(send(socket, message_string.c_str(), message_string.size(), 0));
55          result != static_cast<long>(message_string.size())) {
56          return ErrnoError() << "send() failed to send message contents";
57      }
58      return {};
59  }
60  
61  }  // namespace init
62  }  // namespace android
63