1 /*
2  * Copyright 2020 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 "keymaster/android_keymaster_messages.h"
20 #include "keymaster/serializable.h"
21 
22 #include "common/libs/fs/shared_fd.h"
23 
24 #include <memory>
25 
26 namespace keymaster {
27 
28 /**
29  * keymaster_message - Serial header for communicating with KM server
30  * @cmd: the command, one of AndroidKeymasterCommand.
31  * @payload: start of the serialized command specific payload
32  */
33 struct keymaster_message {
34     AndroidKeymasterCommand cmd : 31;
35     bool is_response : 1;
36     uint32_t payload_size;
37     uint8_t payload[0];
38 };
39 
40 } // namespace keymaster
41 
42 namespace cuttlefish {
43 
44 using keymaster::AndroidKeymasterCommand;
45 using keymaster::keymaster_message;
46 
47 /**
48  * A destroyer for keymaster_message instances created with
49  * CreateKeymasterMessage. Wipes memory from the keymaster_message instances.
50  */
51 class KeymasterCommandDestroyer {
52 public:
53   void operator()(keymaster_message* ptr);
54 };
55 
56 /** An owning pointer for a keymaster_message instance. */
57 using ManagedKeymasterMessage =
58     std::unique_ptr<keymaster_message, KeymasterCommandDestroyer>;
59 
60 /**
61  * Allocates memory for a keymaster_message carrying a message of size
62  * `payload_size`.
63  */
64 ManagedKeymasterMessage CreateKeymasterMessage(
65     AndroidKeymasterCommand command, bool is_response, size_t payload_size);
66 
67 /*
68  * Interface for communication channels that synchronously communicate Keymaster
69  * IPC/RPC calls. Sends messages over a file descriptor.
70  */
71 class KeymasterChannel {
72 private:
73   SharedFD channel_;
74   bool SendMessage(AndroidKeymasterCommand command, bool response,
75                    const keymaster::Serializable& message);
76 public:
77   KeymasterChannel(SharedFD channel);
78 
79   bool SendRequest(AndroidKeymasterCommand command,
80                    const keymaster::Serializable& message);
81   bool SendResponse(AndroidKeymasterCommand command,
82                     const keymaster::Serializable& message);
83   ManagedKeymasterMessage ReceiveMessage();
84 };
85 
86 } // namespace cuttlefish
87