1 /*
2  * Copyright (c) 2022 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 COMMUNICATIONNETSTACK_FETCH_EXEC_H
17 #define COMMUNICATIONNETSTACK_FETCH_EXEC_H
18 
19 #include <mutex>
20 #include <vector>
21 
22 #include "curl/curl.h"
23 #include "fetch_context.h"
24 #include "napi/native_api.h"
25 #include "nocopyable.h"
26 
27 namespace OHOS::NetStack::Fetch {
28 class FetchExec final {
29 public:
30     DISALLOW_COPY_AND_MOVE(FetchExec);
31 
32     FetchExec() = default;
33 
34     ~FetchExec() = default;
35 
36     static bool ExecFetch(FetchContext *context);
37 
38     static napi_value FetchCallback(FetchContext *context);
39 
40     static std::string MakeUrl(const std::string &url, std::string param, const std::string &extraParam);
41 
42     static bool MethodForGet(const std::string &method);
43 
44     static bool MethodForPost(const std::string &method);
45 
46     static bool EncodeUrlParam(std::string &str);
47 
48     static bool Initialize();
49 
50 private:
51     static bool SetOption(CURL *curl, FetchContext *context, struct curl_slist *requestHeader);
52 
53     static size_t OnWritingMemoryBody(const void *data, size_t size, size_t memBytes, void *userData);
54 
55     static size_t OnWritingMemoryHeader(const void *data, size_t size, size_t memBytes, void *userData);
56 
57     static struct curl_slist *MakeHeaders(const std::vector<std::string> &vec);
58 
59     static napi_value MakeResponseHeader(FetchContext *context);
60 
61     static bool IsUnReserved(unsigned char in);
62 
63     static napi_value MakeResponse(FetchContext *context);
64 
65 private:
66     static std::mutex mutex_;
67 
68     static bool initialized_;
69 };
70 } // namespace OHOS::NetStack::Fetch
71 
72 #endif /* COMMUNICATIONNETSTACK_FETCH_EXEC_H */
73