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(); 43 bool DataAvailable(); 44 int32_t Read(); 45 bool Read(std::vector<char>& data); 46 std::vector<char> Read(size_t size); 47 std::future<std::vector<char>> ReadAsync(size_t size); 48 49 bool ReadMessage(std::vector<char>& data); 50 std::vector<char> ReadMessage(); 51 std::future<std::vector<char>> ReadMessageAsync(); 52 Json::Value ReadJsonMessage(); 53 std::future<Json::Value> ReadJsonMessageAsync(); 54 55 bool Write(int32_t data); 56 bool Write(const char* data, unsigned int size); 57 bool Write(const std::vector<char>& data); 58 bool WriteMessage(const std::string& data); 59 bool WriteMessage(const std::vector<char>& data); 60 bool WriteMessage(const Json::Value& data); 61 bool WriteStrides(const char* data, unsigned int size, 62 unsigned int num_strides, int stride_size); 63 64 protected: 65 std::recursive_mutex read_mutex_; 66 std::recursive_mutex write_mutex_; 67 std::function<void()> disconnect_callback_; 68 SharedFD fd_; 69 }; 70 71 class VsockClientConnection : public VsockConnection { 72 public: 73 // the value of vhost_user_vsock_cid isn't actually used, it works like bool, 74 // so any value except nullopt means true 75 bool Connect(unsigned int port, unsigned int cid, 76 std::optional<int> vhost_user) override; 77 }; 78 79 class VsockServerConnection : public VsockConnection { 80 public: 81 virtual ~VsockServerConnection(); 82 void ServerShutdown(); 83 bool Connect(unsigned int port, unsigned int cid, 84 std::optional<int> vhost_user_vsock_cid) override; 85 86 private: 87 SharedFD server_fd_; 88 }; 89 90 } // namespace cuttlefish 91