1 /* 2 * Copyright (C) 2020 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 <android-base/logging.h> 20 #include <json/json.h> 21 #include <sys/socket.h> 22 #include <sys/types.h> 23 24 #include <algorithm> 25 #include <cstdint> 26 #include <map> 27 #include <memory> 28 #include <optional> 29 #include <string> 30 31 namespace cuttlefish { 32 33 /// Defines operations supported by allocd 34 enum class RequestType : uint16_t { 35 Invalid = 0, // Invalid Request 36 ID, // Allocate and return a new Session ID 37 CreateInterface, // Request to create new network interface 38 DestroyInterface, // Request to destroy a managed network interface 39 StopSession, // Request all resources within a session be released 40 Shutdown, // request allocd to shutdown and clean up all resources 41 }; 42 43 /// Defines interface types supported by allocd 44 enum class IfaceType : uint16_t { 45 Invalid = 0, // an invalid interface 46 mtap, // mobile tap 47 wtap, // bridged wireless tap 48 wifiap, // non bridged wireless tap 49 etap, // ethernet tap 50 wbr, // wireless bridge 51 ebr // ethernet bridge 52 }; 53 54 enum class RequestStatus : uint16_t { 55 Invalid = 0, // Invalid status 56 Pending, // Request which has not been attempted 57 Success, // Request was satisfied 58 Failure // Request failed 59 }; 60 61 /// Defines the format for allocd Request messages 62 struct RequestHeader { 63 uint16_t version; /// used to differentiate between allocd feature sets 64 uint16_t len; /// length in bytes of the message payload 65 }; 66 67 /// Provides a wrapper around libjson's Reader to additionally log errors 68 class JsonRequestReader { 69 public: 70 JsonRequestReader() = default; 71 72 ~JsonRequestReader() = default; 73 parse(std::string msg)74 std::optional<Json::Value> parse(std::string msg) { 75 Json::Value ret; 76 std::unique_ptr<Json::CharReader> reader(reader_builder.newCharReader()); 77 std::string errorMessage; 78 if (!reader->parse(&*msg.begin(), &*msg.end(), &ret, &errorMessage)) { 79 LOG(WARNING) << "Received invalid JSON object in input channel: " 80 << errorMessage; 81 LOG(INFO) << "Invalid JSON: " << msg; 82 return std::nullopt; 83 } 84 return ret; 85 } 86 87 private: 88 Json::CharReaderBuilder reader_builder; 89 }; 90 91 } // namespace cuttlefish 92