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 <cstddef> 19 #include <cstdint> 20 #include <functional> 21 #include <future> 22 #include <mutex> 23 #include <string> 24 #include <vector> 25 26 #include <json/json.h> 27 28 #include "common/libs/fs/shared_fd.h" 29 30 namespace cuttlefish { 31 32 class VsockConnection { 33 public: 34 virtual ~VsockConnection(); 35 virtual bool Connect(unsigned int port, unsigned int cid, 36 std::optional<int> vhost_user_vsock_cid) = 0; 37 virtual void Disconnect(); 38 std::future<bool> ConnectAsync(unsigned int port, unsigned int cid, 39 std::optional<int> vhost_user_vsock_cid); 40 void SetDisconnectCallback(std::function<void()> callback); 41 42 bool IsConnected_Unguarded(); 43 bool IsConnected(); 44 bool DataAvailable(); 45 int32_t Read(); 46 bool Read(std::vector<char>& data); 47 std::vector<char> Read(size_t size); 48 std::future<std::vector<char>> ReadAsync(size_t size); 49 50 bool ReadMessage(std::vector<char>& data); 51 std::vector<char> ReadMessage(); 52 std::future<std::vector<char>> ReadMessageAsync(); 53 Json::Value ReadJsonMessage(); 54 std::future<Json::Value> ReadJsonMessageAsync(); 55 56 bool Write(int32_t data); 57 bool Write(const char* data, unsigned int size); 58 bool Write(const std::vector<char>& data); 59 bool WriteMessage(const std::string& data); 60 bool WriteMessage(const std::vector<char>& data); 61 bool WriteMessage(const Json::Value& data); 62 bool WriteStrides(const char* data, unsigned int size, 63 unsigned int num_strides, int stride_size); 64 65 protected: 66 std::recursive_mutex read_mutex_; 67 std::recursive_mutex write_mutex_; 68 std::function<void()> disconnect_callback_; 69 SharedFD fd_; 70 }; 71 72 class VsockClientConnection : public VsockConnection { 73 public: 74 // the value of vhost_user_vsock_cid isn't actually used, it works like bool, 75 // so any value except nullopt means true 76 bool Connect(unsigned int port, unsigned int cid, 77 std::optional<int> vhost_user) override; 78 }; 79 80 class VsockServerConnection : public VsockConnection { 81 public: 82 virtual ~VsockServerConnection(); 83 void ServerShutdown(); 84 bool Connect(unsigned int port, unsigned int cid, 85 std::optional<int> vhost_user_vsock_cid) override; 86 87 private: 88 SharedFD server_fd_; 89 }; 90 91 } // namespace cuttlefish 92