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 
16 #ifndef COMMUNICATIONNETSTACK_EPOLL_MULTI_DRIVER_H
17 #define COMMUNICATIONNETSTACK_EPOLL_MULTI_DRIVER_H
18 
19 #include <map>
20 #include <memory>
21 
22 #include "curl/curl.h"
23 
24 #include "epoller.h"
25 #include "thread_safe_storage.h"
26 #include "timeout_timer.h"
27 
28 namespace OHOS::NetStack::HttpOverCurl {
29 
30 struct RequestInfo;
31 
32 class EpollMultiDriver {
33 public:
34     EpollMultiDriver() = delete;
35     explicit EpollMultiDriver(const std::shared_ptr<HttpOverCurl::ThreadSafeStorage<RequestInfo *>> &incomingQueue);
36     ~EpollMultiDriver();
37 
38     void Step(int waitEventsTimeoutMs);
39 
40 private:
41     class CurlSocketContext {
42     public:
43         CurlSocketContext(HttpOverCurl::Epoller &poller, curl_socket_t socket, int action);
44         void Reassign(curl_socket_t socket, int action);
45         ~CurlSocketContext();
46 
47     private:
48         HttpOverCurl::Epoller &poller_;
49         curl_socket_t socketDescriptor_;
50     };
51 
52     int MultiTimeoutCallback(long timeoutMs);
53     int MultiSocketCallback(curl_socket_t s, int action, CurlSocketContext *socketContext);
54 
55     void EpollTimerCallback();
56     void EpollSocketCallback(int fd);
57 
58     void CheckMultiInfo();
59 
60     void Initialize();
61     void IncomingRequestCallback();
62 
63     std::shared_ptr<HttpOverCurl::ThreadSafeStorage<RequestInfo *>> incomingQueue_;
64 
65     HttpOverCurl::Epoller poller_;
66     HttpOverCurl::TimeoutTimer timeoutTimer_;
67 
68     CURLM *multi_ = nullptr;
69     // Number of running handles
70     int stillRunning = 0;
71 
72     std::map<CURL *, RequestInfo *> ongoingRequests_;
73 };
74 
75 } // namespace OHOS::NetStack::HttpOverCurl
76 
77 #endif // COMMUNICATIONNETSTACK_EPOLL_MULTI_DRIVER_H
78