• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 #pragma once
17 
18 #include <sys/socket.h>
19 
20 #include <cstdint>
21 #include <vector>
22 
23 #include "common/libs/fs/shared_fd.h"
24 #include "common/libs/utils/result.h"
25 
26 namespace cuttlefish {
27 
28 struct ControlMessage {
29  public:
30   static ControlMessage FromRaw(const cmsghdr*);
31   static Result<ControlMessage> FromFileDescriptors(
32       const std::vector<SharedFD>&);
33   static ControlMessage FromCredentials(const ucred&);
34   ControlMessage(const ControlMessage&) = delete;
35   ControlMessage(ControlMessage&&);
36   ~ControlMessage();
37   ControlMessage& operator=(const ControlMessage&) = delete;
38   ControlMessage& operator=(ControlMessage&&);
39 
40   const cmsghdr* Raw() const;
41 
42   bool IsCredentials() const;
43   Result<ucred> AsCredentials() const;
44 
45   bool IsFileDescriptors() const;
46   Result<std::vector<SharedFD>> AsSharedFDs() const;
47 
48  private:
49   friend class UnixMessageSocket;
50   ControlMessage() = default;
51   cmsghdr* Raw();
52 
53   std::vector<char> data_;
54   std::vector<int> fds_;
55 };
56 
57 struct UnixSocketMessage {
58   std::vector<char> data;
59   std::vector<ControlMessage> control;
60 
61   bool HasFileDescriptors();
62   Result<std::vector<SharedFD>> FileDescriptors();
63   bool HasCredentials();
64   Result<ucred> Credentials();
65 };
66 
67 class UnixMessageSocket {
68  public:
69   UnixMessageSocket(SharedFD);
70   [[nodiscard]] Result<void> WriteMessage(const UnixSocketMessage&);
71   Result<UnixSocketMessage> ReadMessage();
72 
73   [[nodiscard]] Result<void> EnableCredentials(bool);
74 
75  private:
76   SharedFD socket_;
77   std::uint32_t max_message_size_;
78 };
79 
80 }  // namespace cuttlefish
81