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 MDNS_SOCKET_LISTENER_H
17 #define MDNS_SOCKET_LISTENER_H
18 
19 #include <atomic>
20 #include <cstddef>
21 #include <functional>
22 #include <mutex>
23 #include <string_view>
24 #include <sys/socket.h>
25 #include <thread>
26 
27 #include <ifaddrs.h>
28 
29 #include "mdns_common.h"
30 
31 namespace OHOS {
32 namespace NetManagerStandard {
33 
34 // This class create and manage udp socket for mDNS transmission
35 // In multi-interface device, we should create socket for each iface for multicast
36 class MDnsSocketListener {
37 public:
38     using ReceiveHandler = std::function<void(int, const MDnsPayload &)>;
39     using FinishedHandler = std::function<void(int)>;
40 
41     MDnsSocketListener();
42     ~MDnsSocketListener();
43 
44     void OpenSocketForEachIface(bool ipv6Support, bool lo);
45     void OpenSocketForDefault(bool ipv6Support);
46     void CloseAllSocket();
47     void Start();
48     void Stop();
49     ssize_t MulticastAll(const MDnsPayload &payload);
50     void SetReceiveHandler(const ReceiveHandler &callback);
51     void SetFinishedHandler(const FinishedHandler &callback);
52     ssize_t Multicast(int sock, const MDnsPayload &);
53     ssize_t Unicast(int sock, sockaddr *saddr, const MDnsPayload &);
54     const std::vector<int> &GetSockets() const;
55     std::string_view GetIface(int sock) const;
56     const sockaddr *GetSockAddr(int sock) const;
57     void TriggerRefresh();
58 
59 private:
60     void Run();
61     bool CanRefresh();
62     void ReceiveInSock(int sock);
63     uint32_t OpenSocketV4(ifaddrs *ifa);
64     uint32_t OpenSocketV6(ifaddrs *ifa, bool ipv6Support);
65     bool Ifaceverification(ifaddrs *ifa, ifaddrs *loaddr);
66 
67     std::vector<int> socks_;
68     std::map<int, std::string> iface_;
69     std::map<int, sockaddr_storage> saddr_;
70     std::atomic_bool runningFlag_ = false;
71     int ctrlPair_[2] = {-1, -1};
72     std::thread thread_;
73     std::mutex mutex_;
74     ReceiveHandler recv_;
75     FinishedHandler finished_;
76 };
77 
78 } // namespace NetManagerStandard
79 } // namespace OHOS
80 #endif /* MDNS_SOCKET_LISTENER_H */
81