1 #include "mock_network_manager.hpp"
2 #include "mock_syscall.hpp"
3 #include "rtnetlink_server.hpp"
4 #include "types.hpp"
5 
6 #include <linux/rtnetlink.h>
7 #include <net/if.h>
8 
9 #include <chrono>
10 #include <functional>
11 #include <sdbusplus/bus.hpp>
12 #include <sdeventplus/event.hpp>
13 
14 #include <gtest/gtest.h>
15 
16 namespace phosphor
17 {
18 
19 namespace network
20 {
21 sdbusplus::bus::bus bus(sdbusplus::bus::new_default());
22 extern std::unique_ptr<MockManager> manager;
23 extern std::unique_ptr<Timer> refreshObjectTimer;
24 EventPtr eventPtr = nullptr;
25 
26 class TestRtNetlink : public testing::Test
27 {
28 
29   public:
30     std::string confDir;
31     phosphor::Descriptor smartSock;
32 
33     TestRtNetlink()
34     {
35         manager =
36             std::make_unique<MockManager>(bus, "/xyz/openbmc_test/bcd", "/tmp");
37         sd_event* events;
38         sd_event_default(&events);
39         eventPtr.reset(events);
40         events = nullptr;
41         setConfDir();
42         initializeTimers();
43         createNetLinkSocket();
44         bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL);
45         rtnetlink::Server svr(eventPtr, smartSock);
46     }
47 
48     ~TestRtNetlink()
49     {
50         if (confDir.empty())
51         {
52             fs::remove_all(confDir);
53         }
54     }
55 
56     void setConfDir()
57     {
58         char tmp[] = "/tmp/NetworkManager.XXXXXX";
59         confDir = mkdtemp(tmp);
60         manager->setConfDir(confDir);
61     }
62 
63     void createNetLinkSocket()
64     {
65         // RtnetLink socket
66         auto fd = socket(PF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE);
67         smartSock.set(fd);
68     }
69 };
70 
71 TEST_F(TestRtNetlink, WithSingleInterface)
72 {
73     using namespace std::chrono;
74     mock_clear();
75     // Adds the following ip in the getifaddrs list.
76     mock_addIF("igb5", 6);
77     mock_addIP("igb5", "127.0.0.1", "255.255.255.128", IFF_UP | IFF_RUNNING);
78     constexpr auto BUFSIZE = 4096;
79     std::array<char, BUFSIZE> msgBuf = {0};
80 
81     // point the header and the msg structure pointers into the buffer.
82     auto nlMsg = reinterpret_cast<nlmsghdr*>(msgBuf.data());
83     // Length of message
84     nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg));
85     nlMsg->nlmsg_type = RTM_GETADDR;
86     nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
87     nlMsg->nlmsg_seq = 0;
88     nlMsg->nlmsg_pid = getpid();
89 
90     EXPECT_EQ(false, manager->hasInterface("igb5"));
91     // Send the request
92     send(smartSock(), nlMsg, nlMsg->nlmsg_len, 0);
93 
94     int i = 3;
95     while (i--)
96     {
97         // wait for timer to expire
98         std::this_thread::sleep_for(std::chrono::milliseconds(refreshTimeout));
99         sd_event_run(eventPtr.get(), 10);
100     };
101 
102     EXPECT_EQ(true, manager->hasInterface("igb5"));
103 }
104 
105 } // namespace network
106 } // namespace phosphor
107