1 // Copyright 2021 Google LLC
2 //
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 #pragma once
16 #include "nemora_types.hpp"
17 #include "serializer.hpp"
18 
19 #include <memory>
20 #include <mutex>
21 #include <string>
22 #include <unordered_set>
23 
24 class SocketManager
25 {
26   public:
27     SocketManager() = default;
28     ~SocketManager();
29 
30     /**
31      * Sends a UDP packet to the address named in bcast object.
32      */
33     void SendDatagram(const NemoraDatagram* bcast);
34 
35     /**
36      * Checks content of open_sockets_ and closes the socket if it is contained
37      * in the list. Closing a socket which is already closed causes problems.
38      */
39     void CloseSocketSafely(int fd);
40 
41   private:
42     /**
43      * Adds a socket fd to open_sockets_ to allow tracking of which sockets are
44      * open or not.  Closing a socket which is already closed causes problems.
45      */
46     void TrackSocket(int fd);
47     std::unordered_set<int> open_sockets_;
48     std::mutex open_sockets_lock_;
49 };
50