1*14fe6698SNan Zhou // Copyright 2021 Google LLC
2*14fe6698SNan Zhou //
3*14fe6698SNan Zhou // Licensed under the Apache License, Version 2.0 (the "License");
4*14fe6698SNan Zhou // you may not use this file except in compliance with the License.
5*14fe6698SNan Zhou // You may obtain a copy of the License at
6*14fe6698SNan Zhou //
7*14fe6698SNan Zhou //      http://www.apache.org/licenses/LICENSE-2.0
8*14fe6698SNan Zhou //
9*14fe6698SNan Zhou // Unless required by applicable law or agreed to in writing, software
10*14fe6698SNan Zhou // distributed under the License is distributed on an "AS IS" BASIS,
11*14fe6698SNan Zhou // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*14fe6698SNan Zhou // See the License for the specific language governing permissions and
13*14fe6698SNan Zhou // limitations under the License.
14*14fe6698SNan Zhou 
15*14fe6698SNan Zhou #pragma once
16*14fe6698SNan Zhou #include "nemora_types.hpp"
17*14fe6698SNan Zhou #include "serializer.hpp"
18*14fe6698SNan Zhou 
19*14fe6698SNan Zhou #include <memory>
20*14fe6698SNan Zhou #include <mutex>
21*14fe6698SNan Zhou #include <string>
22*14fe6698SNan Zhou #include <unordered_set>
23*14fe6698SNan Zhou 
24*14fe6698SNan Zhou class SocketManager
25*14fe6698SNan Zhou {
26*14fe6698SNan Zhou   public:
27*14fe6698SNan Zhou     SocketManager() = default;
28*14fe6698SNan Zhou     ~SocketManager();
29*14fe6698SNan Zhou 
30*14fe6698SNan Zhou     /**
31*14fe6698SNan Zhou      * Sends a UDP packet to the address named in bcast object.
32*14fe6698SNan Zhou      */
33*14fe6698SNan Zhou     void SendDatagram(const NemoraDatagram* bcast);
34*14fe6698SNan Zhou 
35*14fe6698SNan Zhou     /**
36*14fe6698SNan Zhou      * Checks content of open_sockets_ and closes the socket if it is contained
37*14fe6698SNan Zhou      * in the list. Closing a socket which is already closed causes problems.
38*14fe6698SNan Zhou      */
39*14fe6698SNan Zhou     void CloseSocketSafely(int fd);
40*14fe6698SNan Zhou 
41*14fe6698SNan Zhou   private:
42*14fe6698SNan Zhou     /**
43*14fe6698SNan Zhou      * Adds a socket fd to open_sockets_ to allow tracking of which sockets are
44*14fe6698SNan Zhou      * open or not.  Closing a socket which is already closed causes problems.
45*14fe6698SNan Zhou      */
46*14fe6698SNan Zhou     void TrackSocket(int fd);
47*14fe6698SNan Zhou     std::unordered_set<int> open_sockets_;
48*14fe6698SNan Zhou     std::mutex open_sockets_lock_;
49*14fe6698SNan Zhou };
50