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) = 0; 36 virtual void Disconnect(); 37 std::future<bool> ConnectAsync(unsigned int port, unsigned int cid); 38 void SetDisconnectCallback(std::function<void()> callback); 39 40 bool IsConnected() const; 41 bool DataAvailable() const; 42 43 int32_t Read(); 44 bool Read(std::vector<char>& data); 45 std::vector<char> Read(size_t size); 46 std::future<std::vector<char>> ReadAsync(size_t size); 47 48 bool ReadMessage(std::vector<char>& data); 49 std::vector<char> ReadMessage(); 50 std::future<std::vector<char>> ReadMessageAsync(); 51 Json::Value ReadJsonMessage(); 52 std::future<Json::Value> ReadJsonMessageAsync(); 53 54 bool Write(int32_t data); 55 bool Write(const char* data, unsigned int size); 56 bool Write(const std::vector<char>& data); 57 bool WriteMessage(const std::string& data); 58 bool WriteMessage(const std::vector<char>& data); 59 bool WriteMessage(const Json::Value& data); 60 bool WriteStrides(const char* data, unsigned int size, 61 unsigned int num_strides, int stride_size); 62 63 protected: 64 std::recursive_mutex read_mutex_; 65 std::recursive_mutex write_mutex_; 66 std::function<void()> disconnect_callback_; 67 SharedFD fd_; 68 }; 69 70 class VsockClientConnection : public VsockConnection { 71 public: 72 bool Connect(unsigned int port, unsigned int cid) override; 73 }; 74 75 class VsockServerConnection : public VsockConnection { 76 public: 77 virtual ~VsockServerConnection(); 78 void ServerShutdown(); 79 bool Connect(unsigned int port, unsigned int cid) override; 80 81 private: 82 SharedFD server_fd_; 83 }; 84 85 } // namespace cuttlefish 86