1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#ifndef COMMUNICATION_NETSTACK_TLV_UTILS_H
16#define COMMUNICATION_NETSTACK_TLV_UTILS_H
17
18#include <cstdint>
19#include <string>
20
21#ifdef __cplusplus
22extern "C" {
23#endif
24
25namespace OHOS::NetStack {
26
27#define TLV_OK 0
28#define TLV_ERR 1001
29#define TLV_ERR_INVALID_PARA 1002
30#define TLV_ERR_PARSE_PAYLOAD_ERR 1003
31#define TLV_ERR_BUFF_NO_ENOUGH 1004
32
33struct DfxMessage {
34    uint64_t requestBeginTime_ = 0;
35    uint64_t dnsEndTime_ = 0;
36    uint64_t tcpConnectEndTime_ = 0;
37    uint64_t tlsHandshakeEndTime_ = 0;
38    uint64_t firstSendTime_ = 0;
39    uint64_t firstRecvTime_ = 0;
40    uint64_t requestEndTime_ = 0;
41    std::string requestId_;
42    std::string requestUrl_;
43    std::string requestMethod_;
44    std::string requestHeader_;
45    uint32_t responseStatusCode_ = 0;
46    std::string responseHeader_;
47    std::string responseEffectiveUrl_;
48    std::string responseIpAddress_;
49    std::string responseHttpVersion_;
50    std::string responseReasonPhrase_;
51    std::string responseBody_;
52};
53
54enum Type : int32_t {
55    INVALID = 0,
56    U64 = 1,
57    U32,
58    STRING,
59};
60
61typedef struct TlvCommon {
62    uint32_t tag_;
63    uint32_t len_;
64    void *value_;
65} TlvCommon;
66
67class TlvUtils {
68public:
69    static uint32_t Encode(DfxMessage &msg, void *data, uint32_t &dataSize);
70    static uint32_t Decode(DfxMessage &msg, void *data, uint32_t dataSize);
71
72private:
73    static uint8_t *GetNextTlv(const uint8_t *buffer);
74    static uint8_t *ParseTlv(const uint8_t *buffer, TlvCommon *tlv, const uint8_t *boundary, uint32_t *retCode);
75    static uint8_t *AppendTlv(uint8_t *buffer, const TlvCommon *tlv, const uint8_t *boundary, uint32_t *retCode);
76    static uint32_t Serialize(const TlvCommon *tlv, uint32_t tlvCount, uint8_t *buff, uint32_t maxBuffSize,
77                              uint32_t *buffSize);
78    static uint32_t Deserialize(const uint8_t *buff, uint32_t buffSize, TlvCommon *tlv, uint32_t maxTlvCount,
79                                uint32_t *tlvCount);
80    static uint32_t GenerateTlv(DfxMessage &msg, TlvCommon *tlv, uint32_t *tlvCount);
81    static uint32_t Parse(DfxMessage &msg, TlvCommon *tlvs, uint32_t tlvCount);
82};
83}
84
85#ifdef __cplusplus
86}
87#endif
88
89#endif //COMMUNICATION_NETSTACK_TLV_UTILS_H