1 /*
2  * Copyright 2022 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 <windows.h>
20 #include <string>
21 
22 #include <keymaster/android_keymaster_messages.h>
23 #include <keymaster/serializable.h>
24 
25 #include "common/libs/security/keymaster_channel.h"
26 
27 namespace cuttlefish {
28 
29 using keymaster::AndroidKeymasterCommand;
30 
31 /*
32  * Interface for communication channels that synchronously communicate Keymaster
33  * IPC/RPC calls. Sends messages over a named pipe.
34  */
35 class KeymasterWindowsChannel : public KeymasterChannel {
36  public:
37   ~KeymasterWindowsChannel();
38 
39   static std::unique_ptr<KeymasterWindowsChannel> Create(HANDLE pipe_handle);
40 
41   bool SendRequest(AndroidKeymasterCommand command,
42                    const keymaster::Serializable& message) override;
43   bool SendResponse(AndroidKeymasterCommand command,
44                     const keymaster::Serializable& message) override;
45   ManagedKeymasterMessage ReceiveMessage() override;
46 
47  protected:
48   KeymasterWindowsChannel() = default;
49 
50  private:
51   bool WaitForConnection(HANDLE pipe_handle);
52 
53   bool SendMessage(AndroidKeymasterCommand command, bool response,
54                    const keymaster::Serializable& message);
55 
56   bool ReadFromPipe(LPVOID buffer, DWORD size);
57 
58   // Handle to the (asynchronous) named pipe.
59   HANDLE pipe_handle_ = NULL;
60   // OVERLAPPED struct for the named pipe. It contains an event object and is
61   // used to wait for asynchronous pipe operations.
62   OVERLAPPED pipe_overlapped_ = {};
63 };
64 
65 }  // namespace cuttlefish