1 /*
2  * Copyright (c) 2021 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 
16 #ifndef CLIENT_TRANS_UDP_STREAM_ADAPTOR_H_
17 #define CLIENT_TRANS_UDP_STREAM_ADAPTOR_H_
18 
19 #include <atomic>
20 #include <sys/types.h>
21 #include <utility>
22 
23 #include "client_trans_udp_stream_interface.h"
24 #include "i_stream_manager.h"
25 #include "securec.h"
26 #include "softbus_adapter_crypto.h"
27 #include "stream_common.h"
28 
29 namespace OHOS {
30 class StreamAdaptor : public std::enable_shared_from_this<StreamAdaptor> {
31 public:
32     StreamAdaptor() = delete;
33     explicit StreamAdaptor(const std::string &pkgName);
~StreamAdaptor()34     ~StreamAdaptor()
35     {
36         if (sessionKey_.first != nullptr) {
37             (void)memset_s(sessionKey_.first, sessionKey_.second, 0, sessionKey_.second);
38             delete [] sessionKey_.first;
39         }
40         sessionKey_.first = nullptr;
41     }
42 
43     static ssize_t Encrypt(const void *in, ssize_t inLen, void *out, ssize_t outLen,
44         std::pair<uint8_t*, uint32_t> sessionKey);
45     static ssize_t Decrypt(const void *in, ssize_t inLen, void *out, ssize_t outLen,
46         std::pair<uint8_t*, uint32_t> sessionKey);
47     static ssize_t GetEncryptOverhead();
48     int GetStreamType();
49     const std::pair<uint8_t*, uint32_t> GetSessionKey();
50     int64_t GetChannelId();
51     const IStreamListener *GetListenerCallback();
52     std::shared_ptr<Communication::SoftBus::IStreamManager> GetStreamManager();
53     void SetAliveState(bool state);
54     void InitAdaptor(int32_t channelId, const VtpStreamOpenParam *param, bool isServerSide,
55         const IStreamListener *callback);
56     void ReleaseAdaptor();
57     bool GetAliveState();
58     bool IsEncryptedRawStream();
59 
60 private:
61     int64_t channelId_ = -1;
62     std::atomic<bool> aliveState_ = {false};
63     std::shared_ptr<Communication::SoftBus::IStreamManager> streamManager_ = nullptr;
64     int streamType_ = StreamType::INVALID;
65     bool serverSide_;
66     std::string pkgName_ {};
67     std::pair<uint8_t*, uint32_t> sessionKey_ = std::make_pair(nullptr, 0);
68     const IStreamListener *callback_ = nullptr;
69     std::atomic<bool> enableState_ = {false};
70     bool isRawStreamEncrypt_ = {false};
71 };
72 } // namespace OHOS
73 
74 #endif // !defined(CLIENT_TRANS_UDP_STREAM_ADAPTOR_H_