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 <https/RunLoop.h>
20 
21 #include <sys/socket.h>
22 #include "common/libs/fs/vm_sockets.h"
23 
24 #include <memory>
25 
26 struct HostToGuestComms : std::enable_shared_from_this<HostToGuestComms> {
27     using ReceiveCb = std::function<void(const void *data, size_t size)>;
28 
29     explicit HostToGuestComms(
30             std::shared_ptr<RunLoop> runLoop,
31             bool isServer,
32             uint32_t cid,
33             uint16_t port,
34             ReceiveCb onReceive);
35 
36     explicit HostToGuestComms(
37             std::shared_ptr<RunLoop> runLoop,
38             bool isServer,
39             int fd,
40             ReceiveCb onReceive);
41 
42     ~HostToGuestComms();
43 
44     void start();
45 
46     void send(const void *data, size_t size, bool addFraming = true);
47 
48 private:
49     std::shared_ptr<RunLoop> mRunLoop;
50     bool mIsServer;
51     ReceiveCb mOnReceive;
52 
53     int mServerSock;
54     int mSock;
55     sockaddr_vm mConnectToAddr;
56 
57     std::vector<uint8_t> mInBuffer;
58     size_t mInBufferLen;
59 
60     std::mutex mLock;
61     std::vector<uint8_t> mOutBuffer;
62     bool mSendPending;
63 
64     bool mConnected;
65 
66     void onServerConnection();
67     void onSocketReceive();
68     void onSocketSend();
69     void drainInBuffer();
70 
71     void onAttemptToConnect(const sockaddr_vm &addr);
72     void onCheckConnection(const sockaddr_vm &addr);
73     void onConnected();
74 };
75 
76