1 /*
2 * Copyright (c) 2023 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 SOCKET_SESSION_MANAGER_H
17 #define SOCKET_SESSION_MANAGER_H
18
19 #include <functional>
20 #include <map>
21
22 #include "nocopyable.h"
23
24 #include "epoll_manager.h"
25 #include "i_epoll_event_source.h"
26 #include "i_socket_session_manager.h"
27 #include "socket_session.h"
28
29 namespace OHOS {
30 namespace Msdp {
31 namespace DeviceStatus {
32 class SocketSessionManager final : public ISocketSessionManager, public IEpollEventSource {
33 public:
34 SocketSessionManager() = default;
35 ~SocketSessionManager() = default;
36 DISALLOW_COPY_AND_MOVE(SocketSessionManager);
37
38 int32_t Init();
39
40 void AddSessionDeletedCallback(int32_t pid, std::function<void(SocketSessionPtr)> callback) override;
41 int32_t AllocSocketFd(const std::string& programName, int32_t moduleType, int32_t tokenType,
42 int32_t uid, int32_t pid, int32_t& clientFd) override;
43 SocketSessionPtr FindSessionByPid(int32_t pid) const override;
44
45 int32_t GetFd() const override;
46 void Dispatch(const struct epoll_event &ev) override;
47
48 private:
49 bool SetBufferSize(int32_t sockFd, int32_t bufSize);
50 void DispatchOne();
51 void ReleaseSession(int32_t fd);
52 std::shared_ptr<SocketSession> FindSession(int32_t fd) const;
53 bool AddSession(std::shared_ptr<SocketSession> session);
54 void DumpSession(const std::string& title) const;
55 void NotifySessionDeleted(std::shared_ptr<SocketSession> sessionPtr);
56
57 EpollManager epollMgr_;
58 std::map<int32_t, std::shared_ptr<SocketSession>> sessions_;
59 std::map<int32_t, std::function<void(SocketSessionPtr)>> callbacks_;
60 };
61
GetFd()62 inline int32_t SocketSessionManager::GetFd() const
63 {
64 return epollMgr_.GetFd();
65 }
66 } // namespace DeviceStatus
67 } // namespace Msdp
68 } // namespace OHOS
69 #endif // SOCKET_SESSION_MANAGER_H