1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #ifndef COMMON_LIBS_NET_NETWORK_INTERFACE_MANAGER_H_
17 #define COMMON_LIBS_NET_NETWORK_INTERFACE_MANAGER_H_
18 
19 #include <memory>
20 #include <string>
21 
22 #include "common/libs/net/netlink_client.h"
23 #include "common/libs/net/network_interface.h"
24 
25 namespace cuttlefish {
26 
27 // Network interface manager class.
28 // - Provides access for existing network interfaces,
29 // - provides means to create new virtual interfaces.
30 //
31 // Example usage:
32 //
33 //   std::unique_ptr<NetlinkClient> client(NetlinkClient::GetDefault());
34 //   NetworkInterfaceManager manager(client.get());
35 //   std::unique_ptr<NetworkInterface> iface(manager.Open("eth0", "em0"));
36 //
37 class NetworkInterfaceManager {
38  public:
39   // Open existing network interface.
40   //
41   // NOTE: this method does not fill in any NetworkInterface details yet.
42   std::unique_ptr<NetworkInterface> Open(const std::string& if_name,
43                                          const std::string& if_name_alt);
44 
45   // Apply changes made to existing network interface.
46   // This method cannot be used to instantiate new network interfaces.
47   bool ApplyChanges(const NetworkInterface& interface);
48 
49   // Create new connected pair of virtual (veth) interfaces.
50   // Supplied pair of interfaces describe both endpoints' properties.
51   bool CreateVethPair(const NetworkInterface& first,
52                       const NetworkInterface& second);
53 
54   // Creates new NetworkInterfaceManager.
55   static std::unique_ptr<NetworkInterfaceManager> New(
56       NetlinkClientFactory* factory);
57 
58  private:
59   NetworkInterfaceManager(std::unique_ptr<NetlinkClient> nl_client);
60 
61   // Build (partial) netlink request.
62   bool BuildRequest(NetlinkRequest* request, const NetworkInterface& interface);
63 
64   std::unique_ptr<NetlinkClient> nl_client_;
65 
66   NetworkInterfaceManager(const NetworkInterfaceManager&);
67   NetworkInterfaceManager& operator= (const NetworkInterfaceManager&);
68 };
69 
70 }  // namespace cuttlefish
71 
72 #endif  // COMMON_LIBS_NET_NETWORK_INTERFACE_MANAGER_H_
73