1 /* 2 * Copyright 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 17 #pragma once 18 19 #include <cstdint> 20 #include <memory> 21 #include <string> 22 #include <vector> 23 24 #include <cn-cbor/cn-cbor.h> 25 26 namespace cuttlefish { 27 namespace confui { 28 29 /** take prompt_text_, extra_data 30 * returns CBOR map, created with the two 31 * 32 * Usage: 33 * if (IsOk()) GetMessage() 34 * 35 * The CBOR map is used to create signed confirmation 36 */ 37 class Cbor { 38 enum class Error : uint32_t { 39 OK = 0, 40 OUT_OF_DATA = 1, 41 MALFORMED = 2, 42 MALFORMED_UTF8 = 3, 43 }; 44 45 enum class MessageSize : uint32_t { MAX = 6144u }; 46 47 enum class Type : uint8_t { 48 NUMBER = 0, 49 NEGATIVE = 1, 50 BYTE_STRING = 2, 51 TEXT_STRING = 3, 52 ARRAY = 4, 53 MAP = 5, 54 TAG = 6, 55 FLOAT = 7, 56 }; 57 58 public: Cbor(const std::string & prompt_text,const std::vector<std::uint8_t> & extra_data)59 Cbor(const std::string& prompt_text, 60 const std::vector<std::uint8_t>& extra_data) 61 : prompt_text_(prompt_text), 62 extra_data_(extra_data), 63 buffer_status_{Error::OK}, 64 buffer_(kMax + 1) { 65 Init(); 66 } 67 IsOk()68 bool IsOk() const { return buffer_status_ == Error::OK; } GetErrorCode()69 Error GetErrorCode() const { return buffer_status_; } IsMessageTooLong()70 bool IsMessageTooLong() const { return buffer_status_ == Error::OUT_OF_DATA; } IsMalformedUtf8()71 bool IsMalformedUtf8() const { 72 return buffer_status_ == Error::MALFORMED_UTF8; 73 } 74 // call this only when IsOk() returns true 75 std::vector<std::uint8_t>&& GetMessage(); 76 77 /** When encoded, the Cbor object should not exceed this limit in terms of 78 * size in bytes 79 */ 80 const std::uint32_t kMax = static_cast<std::uint32_t>(MessageSize::MAX); 81 82 private: 83 class CborDeleter { 84 public: operator()85 void operator()(cn_cbor* ptr) { cn_cbor_free(ptr); } 86 }; 87 88 std::unique_ptr<cn_cbor, CborDeleter> cb_map_; 89 std::string prompt_text_; 90 std::vector<std::uint8_t> extra_data_; 91 Error buffer_status_; 92 std::vector<std::uint8_t> buffer_; 93 94 void Init(); 95 Error CheckUTF8Copy(const std::string& text); 96 }; 97 98 } // namespace confui 99 } // end of namespace cuttlefish 100