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 #include <testutil.hpp>
14 
15 #include <gtest/gtest.h>
16 
17 namespace phosphor
18 {
19 
20 namespace network
21 {
22 sdbusplus::bus_t bus(sdbusplus::bus::new_default());
23 extern std::unique_ptr<MockManager> manager;
24 extern std::unique_ptr<Timer> refreshObjectTimer;
25 EventPtr eventPtr = nullptr;
26 
27 class TestRtNetlink : public TestWithTmp
28 {
29 
30   public:
31     phosphor::Descriptor smartSock;
32 
33     TestRtNetlink()
34     {
35         manager = std::make_unique<MockManager>(bus, "/xyz/openbmc_test/bcd",
36                                                 CaseTmpDir());
37         sd_event* events;
38         sd_event_default(&events);
39         eventPtr.reset(events);
40         events = nullptr;
41         initializeTimers();
42         createNetLinkSocket();
43         bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL);
44         rtnetlink::Server svr(eventPtr, smartSock);
45     }
46     void createNetLinkSocket()
47     {
48         // RtnetLink socket
49         auto fd = socket(PF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE);
50         smartSock.set(fd);
51     }
52 };
53 
54 TEST_F(TestRtNetlink, WithSingleInterface)
55 {
56     using namespace std::chrono;
57     mock_clear();
58     // Adds the following ip in the getifaddrs list.
59     mock_addIF("igb5", 6);
60     mock_addIP("igb5", "127.0.0.1", "255.255.255.128", IFF_UP | IFF_RUNNING);
61     constexpr auto BUFSIZE = 4096;
62     std::array<char, BUFSIZE> msgBuf = {0};
63 
64     // point the header and the msg structure pointers into the buffer.
65     auto nlMsg = reinterpret_cast<nlmsghdr*>(msgBuf.data());
66     // Length of message
67     nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg));
68     nlMsg->nlmsg_type = RTM_GETADDR;
69     nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
70     nlMsg->nlmsg_seq = 0;
71     nlMsg->nlmsg_pid = getpid();
72 
73     EXPECT_EQ(false, manager->hasInterface("igb5"));
74     // Send the request
75     send(smartSock(), nlMsg, nlMsg->nlmsg_len, 0);
76 
77     int i = 3;
78     while (i--)
79     {
80         // wait for timer to expire
81         std::this_thread::sleep_for(std::chrono::milliseconds(refreshTimeout));
82         sd_event_run(eventPtr.get(), 10);
83     };
84 
85     EXPECT_EQ(true, manager->hasInterface("igb5"));
86 }
87 
88 } // namespace network
89 } // namespace phosphor
90