1 //
2 // Copyright (C) 2012 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 
17 // This file provides tests for individual messages.  It tests
18 // NetlinkMessageFactory's ability to create specific message types and it
19 // tests the various NetlinkMessage types' ability to parse those
20 // messages.
21 
22 // This file tests the public interface to NetlinkManager.
23 #include "shill/net/netlink_manager.h"
24 
25 #include <errno.h>
26 
27 #include <map>
28 #include <string>
29 #include <vector>
30 
31 #include <base/strings/stringprintf.h>
32 #include <base/message_loop/message_loop.h>
33 #include <gmock/gmock.h>
34 #include <gtest/gtest.h>
35 
36 #include "shill/net/io_handler.h"
37 #include "shill/net/mock_io_handler_factory.h"
38 #include "shill/net/mock_netlink_socket.h"
39 #include "shill/net/mock_sockets.h"
40 #include "shill/net/mock_time.h"
41 #include "shill/net/netlink_attribute.h"
42 #include "shill/net/netlink_packet.h"
43 #include "shill/net/nl80211_message.h"
44 
45 using base::Bind;
46 using base::StringPrintf;
47 using base::Unretained;
48 using std::map;
49 using std::string;
50 using std::vector;
51 using testing::_;
52 using testing::AnyNumber;
53 using testing::EndsWith;
54 using testing::Invoke;
55 using testing::Mock;
56 using testing::Return;
57 using testing::SetArgPointee;
58 using testing::StrictMock;
59 using testing::Test;
60 
61 namespace shill {
62 
63 namespace {
64 
65 // These data blocks have been collected by shill using NetlinkManager while,
66 // simultaneously (and manually) comparing shill output with that of the 'iw'
67 // code from which it was derived.  The test strings represent the raw packet
68 // data coming from the kernel.  The comments above each of these strings is
69 // the markup that "iw" outputs for ech of these packets.
70 
71 // These constants are consistent throughout the packets, below.
72 
73 const uint16_t kNl80211FamilyId = 0x13;
74 
75 // Family and group Ids.
76 const char kFamilyStoogesString[] = "stooges";  // Not saved as a legal family.
77 const char kGroupMoeString[] = "moe";  // Not saved as a legal group.
78 const char kFamilyMarxString[] = "marx";
79 const uint16_t kFamilyMarxNumber = 20;
80 const char kGroupGrouchoString[] = "groucho";
81 const uint32_t kGroupGrouchoNumber = 21;
82 const char kGroupHarpoString[] = "harpo";
83 const uint32_t kGroupHarpoNumber = 22;
84 const char kGroupChicoString[] = "chico";
85 const uint32_t kGroupChicoNumber = 23;
86 const char kGroupZeppoString[] = "zeppo";
87 const uint32_t kGroupZeppoNumber = 24;
88 const char kGroupGummoString[] = "gummo";
89 const uint32_t kGroupGummoNumber = 25;
90 
91 // wlan0 (phy #0): disconnected (by AP) reason: 2: Previous authentication no
92 // longer valid
93 
94 const unsigned char kNL80211_CMD_DISCONNECT[] = {
95     0x30, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
96     0x00, 0x00, 0x00, 0x00, 0x30, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
97     0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00,
98     0x06, 0x00, 0x36, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x47, 0x00};
99 
100 const unsigned char kNLMSG_ACK[] = {
101     0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,
102     0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
103     0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
104 
105 // Error code 1.
106 const unsigned char kNLMSG_Error[] = {
107     0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,
108     0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
109     0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
110 
111 const char kGetFamilyCommandString[] = "CTRL_CMD_GETFAMILY";
112 
113 }  // namespace
114 
115 class NetlinkManagerTest : public Test {
116  public:
NetlinkManagerTest()117   NetlinkManagerTest()
118       : netlink_manager_(NetlinkManager::GetInstance()),
119         netlink_socket_(new MockNetlinkSocket()),
120         sockets_(new MockSockets),
121         saved_sequence_number_(0) {
122     EXPECT_NE(nullptr, netlink_manager_);
123     netlink_manager_->message_types_[Nl80211Message::kMessageTypeString].
124        family_id = kNl80211FamilyId;
125     netlink_manager_->message_types_[kFamilyMarxString].family_id =
126         kFamilyMarxNumber;
127     netlink_manager_->message_types_[kFamilyMarxString].groups =
128       map<string, uint32_t> {{kGroupGrouchoString, kGroupGrouchoNumber},
129                              {kGroupHarpoString, kGroupHarpoNumber},
130                              {kGroupChicoString, kGroupChicoNumber},
131                              {kGroupZeppoString, kGroupZeppoNumber},
132                              {kGroupGummoString, kGroupGummoNumber}};
133     netlink_manager_->message_factory_.AddFactoryMethod(
134         kNl80211FamilyId, Bind(&Nl80211Message::CreateMessage));
135     Nl80211Message::SetMessageType(kNl80211FamilyId);
136     netlink_socket_->sockets_.reset(sockets_);  // Passes ownership.
137     netlink_manager_->sock_.reset(netlink_socket_);  // Passes ownership.
138     netlink_manager_->io_handler_factory_ = &io_handler_factory_;
139     EXPECT_TRUE(netlink_manager_->Init());
140   }
141 
~NetlinkManagerTest()142   ~NetlinkManagerTest() {
143     // NetlinkManager is a singleton, so reset its state for the next test.
144     netlink_manager_->Reset(true);
145   }
146 
147   // |SaveReply|, |SendMessage|, and |ReplyToSentMessage| work together to
148   // enable a test to get a response to a sent message.  They must be called
149   // in the order, above, so that a) a reply message is available to b) have
150   // its sequence number replaced, and then c) sent back to the code.
SaveReply(const ByteString & message)151   void SaveReply(const ByteString& message) {
152     saved_message_ = message;
153   }
154 
155   // Replaces the |saved_message_|'s sequence number with the sent value.
SendMessage(const ByteString & outgoing_message)156   bool SendMessage(const ByteString& outgoing_message) {
157     if (outgoing_message.GetLength() < sizeof(nlmsghdr)) {
158       LOG(ERROR) << "Outgoing message is too short";
159       return false;
160     }
161     const nlmsghdr* outgoing_header =
162         reinterpret_cast<const nlmsghdr*>(outgoing_message.GetConstData());
163 
164     if (saved_message_.GetLength() < sizeof(nlmsghdr)) {
165       LOG(ERROR) << "Saved message is too short; have you called |SaveReply|?";
166       return false;
167     }
168     nlmsghdr* reply_header =
169         reinterpret_cast<nlmsghdr*>(saved_message_.GetData());
170 
171     reply_header->nlmsg_seq = outgoing_header->nlmsg_seq;
172     saved_sequence_number_ = reply_header->nlmsg_seq;
173     return true;
174   }
175 
ReplyToSentMessage(ByteString * message)176   bool ReplyToSentMessage(ByteString* message) {
177     if (!message) {
178       return false;
179     }
180     *message = saved_message_;
181     return true;
182   }
183 
ReplyWithRandomMessage(ByteString * message)184   bool ReplyWithRandomMessage(ByteString* message) {
185     GetFamilyMessage get_family_message;
186     // Any number that's not 0 or 1 is acceptable, here.  Zero is bad because
187     // we want to make sure that this message is different than the main
188     // send/receive pair.  One is bad because the default for
189     // |saved_sequence_number_| is zero and the likely default value for the
190     // first sequence number generated from the code is 1.
191     const uint32_t kRandomOffset = 1003;
192     if (!message) {
193       return false;
194     }
195     *message = get_family_message.Encode(saved_sequence_number_ +
196                                          kRandomOffset);
197     return true;
198   }
199 
200  protected:
201   class MockHandlerNetlink {
202    public:
MockHandlerNetlink()203     MockHandlerNetlink() :
204       on_netlink_message_(base::Bind(&MockHandlerNetlink::OnNetlinkMessage,
205                                      base::Unretained(this))) {}
206     MOCK_METHOD1(OnNetlinkMessage, void(const NetlinkMessage& msg));
on_netlink_message() const207     const NetlinkManager::NetlinkMessageHandler& on_netlink_message() const {
208       return on_netlink_message_;
209     }
210    private:
211     NetlinkManager::NetlinkMessageHandler on_netlink_message_;
212     DISALLOW_COPY_AND_ASSIGN(MockHandlerNetlink);
213   };
214 
215   class MockHandlerNetlinkAuxilliary {
216    public:
MockHandlerNetlinkAuxilliary()217     MockHandlerNetlinkAuxilliary() :
218       on_netlink_message_(
219           base::Bind(&MockHandlerNetlinkAuxilliary::OnErrorHandler,
220                      base::Unretained(this))) {}
221     MOCK_METHOD2(OnErrorHandler,
222                  void(NetlinkManager::AuxilliaryMessageType type,
223                       const NetlinkMessage* msg));
on_netlink_message() const224     const NetlinkManager::NetlinkAuxilliaryMessageHandler& on_netlink_message()
225         const {
226       return on_netlink_message_;
227     }
228    private:
229     NetlinkManager::NetlinkAuxilliaryMessageHandler on_netlink_message_;
230     DISALLOW_COPY_AND_ASSIGN(MockHandlerNetlinkAuxilliary);
231   };
232 
233   class MockHandler80211 {
234    public:
MockHandler80211()235     MockHandler80211() :
236       on_netlink_message_(base::Bind(&MockHandler80211::OnNetlinkMessage,
237                                      base::Unretained(this))) {}
238     MOCK_METHOD1(OnNetlinkMessage, void(const Nl80211Message& msg));
on_netlink_message() const239     const NetlinkManager::Nl80211MessageHandler& on_netlink_message() const {
240       return on_netlink_message_;
241     }
242    private:
243     NetlinkManager::Nl80211MessageHandler on_netlink_message_;
244     DISALLOW_COPY_AND_ASSIGN(MockHandler80211);
245   };
246 
247   class MockHandlerNetlinkAck {
248    public:
MockHandlerNetlinkAck()249     MockHandlerNetlinkAck()
250         : on_netlink_message_(base::Bind(&MockHandlerNetlinkAck::OnAckHandler,
251                                          base::Unretained(this))) {}
252     MOCK_METHOD1(OnAckHandler, void(bool* remove_callbacks));
on_netlink_message() const253     const NetlinkManager::NetlinkAckHandler& on_netlink_message() const {
254       return on_netlink_message_;
255     }
256    private:
257     NetlinkManager::NetlinkAckHandler on_netlink_message_;
258     DISALLOW_COPY_AND_ASSIGN(MockHandlerNetlinkAck);
259   };
260 
Reset()261   void Reset() {
262     netlink_manager_->Reset(false);
263   }
264 
265   NetlinkManager* netlink_manager_;
266   MockNetlinkSocket* netlink_socket_;  // Owned by |netlink_manager_|.
267   MockSockets* sockets_;  // Owned by |netlink_socket_|.
268   StrictMock<MockIOHandlerFactory> io_handler_factory_;
269   ByteString saved_message_;
270   uint32_t saved_sequence_number_;
271   base::MessageLoop message_loop_;
272 };
273 
274 namespace {
275 
276 class TimeFunctor {
277  public:
TimeFunctor(time_t tv_sec,suseconds_t tv_usec)278   TimeFunctor(time_t tv_sec, suseconds_t tv_usec) {
279     return_value_.tv_sec = tv_sec;
280     return_value_.tv_usec = tv_usec;
281   }
282 
TimeFunctor()283   TimeFunctor() {
284     return_value_.tv_sec = 0;
285     return_value_.tv_usec = 0;
286   }
287 
TimeFunctor(const TimeFunctor & other)288   TimeFunctor(const TimeFunctor& other) {
289     return_value_.tv_sec = other.return_value_.tv_sec;
290     return_value_.tv_usec = other.return_value_.tv_usec;
291   }
292 
operator =(const TimeFunctor & rhs)293   TimeFunctor& operator=(const TimeFunctor& rhs) {
294     return_value_.tv_sec = rhs.return_value_.tv_sec;
295     return_value_.tv_usec = rhs.return_value_.tv_usec;
296     return *this;
297   }
298 
299   // Replaces GetTimeMonotonic.
operator ()(struct timeval * answer)300   int operator()(struct timeval* answer) {
301     if (answer) {
302       *answer = return_value_;
303     }
304     return 0;
305   }
306 
307  private:
308   struct timeval return_value_;
309 
310   // No DISALLOW_COPY_AND_ASSIGN since testing::Invoke uses copy.
311 };
312 
313 }  // namespace
314 
TEST_F(NetlinkManagerTest,Start)315 TEST_F(NetlinkManagerTest, Start) {
316   EXPECT_CALL(io_handler_factory_, CreateIOInputHandler(_, _, _));
317   netlink_manager_->Start();
318 }
319 
TEST_F(NetlinkManagerTest,SubscribeToEvents)320 TEST_F(NetlinkManagerTest, SubscribeToEvents) {
321   // Family not registered.
322   EXPECT_CALL(*netlink_socket_, SubscribeToEvents(_)).Times(0);
323   EXPECT_FALSE(netlink_manager_->SubscribeToEvents(kFamilyStoogesString,
324                                                    kGroupMoeString));
325 
326   // Group not part of family
327   EXPECT_CALL(*netlink_socket_, SubscribeToEvents(_)).Times(0);
328   EXPECT_FALSE(netlink_manager_->SubscribeToEvents(kFamilyMarxString,
329                                                    kGroupMoeString));
330 
331   // Family registered and group part of family.
332   EXPECT_CALL(*netlink_socket_, SubscribeToEvents(kGroupHarpoNumber)).
333       WillOnce(Return(true));
334   EXPECT_TRUE(netlink_manager_->SubscribeToEvents(kFamilyMarxString,
335                                                   kGroupHarpoString));
336 }
337 
TEST_F(NetlinkManagerTest,GetFamily)338 TEST_F(NetlinkManagerTest, GetFamily) {
339   const uint16_t kSampleMessageType = 42;
340   const string kSampleMessageName("SampleMessageName");
341   const uint32_t kRandomSequenceNumber = 3;
342 
343   NewFamilyMessage new_family_message;
344   new_family_message.attributes()->CreateControlAttribute(
345       CTRL_ATTR_FAMILY_ID);
346   new_family_message.attributes()->SetU16AttributeValue(
347       CTRL_ATTR_FAMILY_ID, kSampleMessageType);
348   new_family_message.attributes()->CreateControlAttribute(
349       CTRL_ATTR_FAMILY_NAME);
350   new_family_message.attributes()->SetStringAttributeValue(
351       CTRL_ATTR_FAMILY_NAME, kSampleMessageName);
352 
353   // The sequence number is immaterial since it'll be overwritten.
354   SaveReply(new_family_message.Encode(kRandomSequenceNumber));
355   EXPECT_CALL(*netlink_socket_, SendMessage(_)).
356       WillOnce(Invoke(this, &NetlinkManagerTest::SendMessage));
357   EXPECT_CALL(*netlink_socket_, file_descriptor()).WillRepeatedly(Return(0));
358   EXPECT_CALL(*sockets_, Select(_, _, _, _, _)).WillOnce(Return(1));
359   EXPECT_CALL(*netlink_socket_, RecvMessage(_)).
360       WillOnce(Invoke(this, &NetlinkManagerTest::ReplyToSentMessage));
361   NetlinkMessageFactory::FactoryMethod null_factory;
362   EXPECT_EQ(kSampleMessageType, netlink_manager_->GetFamily(kSampleMessageName,
363                                                             null_factory));
364 }
365 
TEST_F(NetlinkManagerTest,GetFamilyOneInterstitialMessage)366 TEST_F(NetlinkManagerTest, GetFamilyOneInterstitialMessage) {
367   Reset();
368 
369   const uint16_t kSampleMessageType = 42;
370   const string kSampleMessageName("SampleMessageName");
371   const uint32_t kRandomSequenceNumber = 3;
372 
373   NewFamilyMessage new_family_message;
374   new_family_message.attributes()->CreateControlAttribute(
375       CTRL_ATTR_FAMILY_ID);
376   new_family_message.attributes()->SetU16AttributeValue(
377       CTRL_ATTR_FAMILY_ID, kSampleMessageType);
378   new_family_message.attributes()->CreateControlAttribute(
379       CTRL_ATTR_FAMILY_NAME);
380   new_family_message.attributes()->SetStringAttributeValue(
381       CTRL_ATTR_FAMILY_NAME, kSampleMessageName);
382 
383   // The sequence number is immaterial since it'll be overwritten.
384   SaveReply(new_family_message.Encode(kRandomSequenceNumber));
385   EXPECT_CALL(*netlink_socket_, SendMessage(_)).
386       WillOnce(Invoke(this, &NetlinkManagerTest::SendMessage));
387   EXPECT_CALL(*netlink_socket_, file_descriptor()).WillRepeatedly(Return(0));
388   EXPECT_CALL(*sockets_, Select(_, _, _, _, _)).WillRepeatedly(Return(1));
389   EXPECT_CALL(*netlink_socket_, RecvMessage(_)).
390       WillOnce(Invoke(this, &NetlinkManagerTest::ReplyWithRandomMessage)).
391       WillOnce(Invoke(this, &NetlinkManagerTest::ReplyToSentMessage));
392   NetlinkMessageFactory::FactoryMethod null_factory;
393   EXPECT_EQ(kSampleMessageType, netlink_manager_->GetFamily(kSampleMessageName,
394                                                             null_factory));
395 }
396 
TEST_F(NetlinkManagerTest,GetFamilyTimeout)397 TEST_F(NetlinkManagerTest, GetFamilyTimeout) {
398   Reset();
399   MockTime time;
400   Time* old_time = netlink_manager_->time_;
401   netlink_manager_->time_ = &time;
402 
403   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
404   time_t kStartSeconds = 1234;  // Arbitrary.
405   suseconds_t kSmallUsec = 100;
406   EXPECT_CALL(time, GetTimeMonotonic(_)).
407       WillOnce(Invoke(TimeFunctor(kStartSeconds, 0))).  // Initial time.
408       WillOnce(Invoke(TimeFunctor(kStartSeconds, kSmallUsec))).
409       WillOnce(Invoke(TimeFunctor(kStartSeconds, 2 * kSmallUsec))).
410       WillOnce(Invoke(TimeFunctor(
411           kStartSeconds + NetlinkManager::kMaximumNewFamilyWaitSeconds + 1,
412           NetlinkManager::kMaximumNewFamilyWaitMicroSeconds)));
413   EXPECT_CALL(*netlink_socket_, file_descriptor()).WillRepeatedly(Return(0));
414   EXPECT_CALL(*sockets_, Select(_, _, _, _, _)).WillRepeatedly(Return(1));
415   EXPECT_CALL(*netlink_socket_, RecvMessage(_)).
416       WillRepeatedly(Invoke(this, &NetlinkManagerTest::ReplyWithRandomMessage));
417   NetlinkMessageFactory::FactoryMethod null_factory;
418 
419   const string kSampleMessageName("SampleMessageName");
420   EXPECT_EQ(NetlinkMessage::kIllegalMessageType,
421             netlink_manager_->GetFamily(kSampleMessageName, null_factory));
422   netlink_manager_->time_ = old_time;
423 }
424 
TEST_F(NetlinkManagerTest,BroadcastHandler)425 TEST_F(NetlinkManagerTest, BroadcastHandler) {
426   Reset();
427   MutableNetlinkPacket packet(
428       kNL80211_CMD_DISCONNECT, sizeof(kNL80211_CMD_DISCONNECT));
429 
430   MockHandlerNetlink handler1;
431   MockHandlerNetlink handler2;
432 
433   // Simple, 1 handler, case.
434   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(1);
435   EXPECT_FALSE(
436       netlink_manager_->FindBroadcastHandler(handler1.on_netlink_message()));
437   netlink_manager_->AddBroadcastHandler(handler1.on_netlink_message());
438   EXPECT_TRUE(
439       netlink_manager_->FindBroadcastHandler(handler1.on_netlink_message()));
440   netlink_manager_->OnNlMessageReceived(&packet);
441   packet.ResetConsumedBytes();
442 
443   // Add a second handler.
444   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(1);
445   EXPECT_CALL(handler2, OnNetlinkMessage(_)).Times(1);
446   netlink_manager_->AddBroadcastHandler(handler2.on_netlink_message());
447   netlink_manager_->OnNlMessageReceived(&packet);
448   packet.ResetConsumedBytes();
449 
450   // Verify that a handler can't be added twice.
451   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(1);
452   EXPECT_CALL(handler2, OnNetlinkMessage(_)).Times(1);
453   netlink_manager_->AddBroadcastHandler(handler1.on_netlink_message());
454   netlink_manager_->OnNlMessageReceived(&packet);
455   packet.ResetConsumedBytes();
456 
457   // Check that we can remove a handler.
458   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(0);
459   EXPECT_CALL(handler2, OnNetlinkMessage(_)).Times(1);
460   EXPECT_TRUE(netlink_manager_->RemoveBroadcastHandler(
461       handler1.on_netlink_message()));
462   netlink_manager_->OnNlMessageReceived(&packet);
463   packet.ResetConsumedBytes();
464 
465   // Check that re-adding the handler goes smoothly.
466   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(1);
467   EXPECT_CALL(handler2, OnNetlinkMessage(_)).Times(1);
468   netlink_manager_->AddBroadcastHandler(handler1.on_netlink_message());
469   netlink_manager_->OnNlMessageReceived(&packet);
470   packet.ResetConsumedBytes();
471 
472   // Check that ClearBroadcastHandlers works.
473   netlink_manager_->ClearBroadcastHandlers();
474   EXPECT_CALL(handler1, OnNetlinkMessage(_)).Times(0);
475   EXPECT_CALL(handler2, OnNetlinkMessage(_)).Times(0);
476   netlink_manager_->OnNlMessageReceived(&packet);
477 }
478 
TEST_F(NetlinkManagerTest,MessageHandler)479 TEST_F(NetlinkManagerTest, MessageHandler) {
480   Reset();
481   MockHandlerNetlink handler_broadcast;
482   EXPECT_TRUE(netlink_manager_->AddBroadcastHandler(
483       handler_broadcast.on_netlink_message()));
484 
485   Nl80211Message sent_message_1(CTRL_CMD_GETFAMILY, kGetFamilyCommandString);
486   MockHandler80211 handler_sent_1;
487 
488   Nl80211Message sent_message_2(CTRL_CMD_GETFAMILY, kGetFamilyCommandString);
489   MockHandler80211 handler_sent_2;
490 
491   // Set up the received message as a response to sent_message_1.
492   MutableNetlinkPacket received_message(
493       kNL80211_CMD_DISCONNECT, sizeof(kNL80211_CMD_DISCONNECT));
494 
495   // Verify that generic handler gets called for a message when no
496   // message-specific handler has been installed.
497   EXPECT_CALL(handler_broadcast, OnNetlinkMessage(_)).Times(1);
498   netlink_manager_->OnNlMessageReceived(&received_message);
499   received_message.ResetConsumedBytes();
500 
501   // Send the message and give our handler.  Verify that we get called back.
502   NetlinkManager::NetlinkAuxilliaryMessageHandler null_error_handler;
503   NetlinkManager::NetlinkAckHandler null_ack_handler;
504   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillRepeatedly(Return(true));
505   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
506       &sent_message_1, handler_sent_1.on_netlink_message(),
507       null_ack_handler, null_error_handler));
508   // Make it appear that this message is in response to our sent message.
509   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
510   EXPECT_CALL(handler_sent_1, OnNetlinkMessage(_)).Times(1);
511   netlink_manager_->OnNlMessageReceived(&received_message);
512   received_message.ResetConsumedBytes();
513 
514   // Verify that broadcast handler is called for the message after the
515   // message-specific handler is called once.
516   EXPECT_CALL(handler_broadcast, OnNetlinkMessage(_)).Times(1);
517   netlink_manager_->OnNlMessageReceived(&received_message);
518   received_message.ResetConsumedBytes();
519 
520   // Install and then uninstall message-specific handler; verify broadcast
521   // handler is called on message receipt.
522   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
523       &sent_message_1, handler_sent_1.on_netlink_message(),
524       null_ack_handler, null_error_handler));
525   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
526   EXPECT_TRUE(netlink_manager_->RemoveMessageHandler(sent_message_1));
527   EXPECT_CALL(handler_broadcast, OnNetlinkMessage(_)).Times(1);
528   netlink_manager_->OnNlMessageReceived(&received_message);
529   received_message.ResetConsumedBytes();
530 
531   // Install handler for different message; verify that broadcast handler is
532   // called for _this_ message.
533   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
534       &sent_message_2, handler_sent_2.on_netlink_message(),
535       null_ack_handler, null_error_handler));
536   EXPECT_CALL(handler_broadcast, OnNetlinkMessage(_)).Times(1);
537   netlink_manager_->OnNlMessageReceived(&received_message);
538   received_message.ResetConsumedBytes();
539 
540   // Change the ID for the message to that of the second handler; verify that
541   // the appropriate handler is called for _that_ message.
542   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
543   EXPECT_CALL(handler_sent_2, OnNetlinkMessage(_)).Times(1);
544   netlink_manager_->OnNlMessageReceived(&received_message);
545 }
546 
TEST_F(NetlinkManagerTest,AckHandler)547 TEST_F(NetlinkManagerTest, AckHandler) {
548   Reset();
549 
550   Nl80211Message sent_message(CTRL_CMD_GETFAMILY, kGetFamilyCommandString);
551   MockHandler80211 handler_sent_1;
552   MockHandlerNetlinkAck handler_sent_2;
553 
554   // Send the message and give a Nl80211 response handlerand an Ack
555   // handler that does not remove other callbacks after execution.
556   // Receive an Ack message and verify that the Ack handler is invoked.
557   NetlinkManager::NetlinkAuxilliaryMessageHandler null_error_handler;
558   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillRepeatedly(Return(true));
559   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
560       &sent_message, handler_sent_1.on_netlink_message(),
561       handler_sent_2.on_netlink_message(), null_error_handler));
562   // Set up message as an ack in response to sent_message.
563   MutableNetlinkPacket received_ack_message(kNLMSG_ACK, sizeof(kNLMSG_ACK));
564 
565   // Make it appear that this message is in response to our sent message.
566   received_ack_message.SetMessageSequence(
567       netlink_socket_->GetLastSequenceNumber());
568   EXPECT_CALL(handler_sent_2, OnAckHandler(_))
569       .Times(1)
570           .WillOnce(SetArgPointee<0>(false));  // Do not remove callbacks
571   netlink_manager_->OnNlMessageReceived(&received_ack_message);
572 
573   // Receive an Nl80211 response message after handling the Ack and verify
574   // that the Nl80211 response handler is invoked to ensure that it was not
575   // deleted after the Ack handler was executed.
576   MutableNetlinkPacket received_response_message(
577       kNL80211_CMD_DISCONNECT, sizeof(kNL80211_CMD_DISCONNECT));
578 
579   // Make it appear that this message is in response to our sent message.
580   received_response_message.SetMessageSequence(
581       netlink_socket_->GetLastSequenceNumber());
582   EXPECT_CALL(handler_sent_1, OnNetlinkMessage(_)).Times(1);
583   netlink_manager_->OnNlMessageReceived(&received_response_message);
584   received_response_message.ResetConsumedBytes();
585 
586   // Send the message and give a Nl80211 response handler and Ack handler again,
587   // but remove other callbacks after executing the Ack handler.
588   // Receive an Ack message and verify the Ack handler is invoked.
589   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
590       &sent_message, handler_sent_1.on_netlink_message(),
591       handler_sent_2.on_netlink_message(), null_error_handler));
592   received_ack_message.ResetConsumedBytes();
593   received_ack_message.SetMessageSequence(
594       netlink_socket_->GetLastSequenceNumber());
595   EXPECT_CALL(handler_sent_2, OnAckHandler(_))
596       .Times(1)
597           .WillOnce(SetArgPointee<0>(true));  // Remove callbacks
598   netlink_manager_->OnNlMessageReceived(&received_ack_message);
599 
600   // Receive an Nl80211 response message after handling the Ack and verify
601   // that the Nl80211 response handler is not invoked this time, since it should
602   // have been deleted after calling the Ack handler.
603   received_response_message.SetMessageSequence(
604       received_ack_message.GetNlMsgHeader().nlmsg_seq);
605   EXPECT_CALL(handler_sent_1, OnNetlinkMessage(_)).Times(0);
606   netlink_manager_->OnNlMessageReceived(&received_response_message);
607 }
608 
TEST_F(NetlinkManagerTest,ErrorHandler)609 TEST_F(NetlinkManagerTest, ErrorHandler) {
610   Nl80211Message sent_message(CTRL_CMD_GETFAMILY, kGetFamilyCommandString);
611   MockHandler80211 handler_sent_1;
612   MockHandlerNetlinkAck handler_sent_2;
613   MockHandlerNetlinkAuxilliary handler_sent_3;
614 
615   // Send the message and receive a netlink reply.
616   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillRepeatedly(Return(true));
617   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
618       &sent_message, handler_sent_1.on_netlink_message(),
619       handler_sent_2.on_netlink_message(),
620       handler_sent_3.on_netlink_message()));
621   MutableNetlinkPacket received_response_message(
622       kNL80211_CMD_DISCONNECT, sizeof(kNL80211_CMD_DISCONNECT));
623   received_response_message.SetMessageSequence(
624       netlink_socket_->GetLastSequenceNumber());
625   EXPECT_CALL(handler_sent_1, OnNetlinkMessage(_)).Times(1);
626   netlink_manager_->OnNlMessageReceived(&received_response_message);
627 
628   // Send the message again, but receive an error response.
629   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
630       &sent_message, handler_sent_1.on_netlink_message(),
631       handler_sent_2.on_netlink_message(),
632       handler_sent_3.on_netlink_message()));
633   MutableNetlinkPacket received_error_message(
634       kNLMSG_Error, sizeof(kNLMSG_Error));
635   received_error_message.SetMessageSequence(
636       netlink_socket_->GetLastSequenceNumber());
637   EXPECT_CALL(handler_sent_3,
638               OnErrorHandler(NetlinkManager::kErrorFromKernel, _))
639       .Times(1);
640   netlink_manager_->OnNlMessageReceived(&received_error_message);
641 
642   // Put the state of the singleton back where it was.
643   Reset();
644 }
645 
TEST_F(NetlinkManagerTest,MultipartMessageHandler)646 TEST_F(NetlinkManagerTest, MultipartMessageHandler) {
647   Reset();
648 
649   // Install a broadcast handler.
650   MockHandlerNetlink broadcast_handler;
651   EXPECT_TRUE(netlink_manager_->AddBroadcastHandler(
652       broadcast_handler.on_netlink_message()));
653 
654   // Build a message and send it in order to install a response handler.
655   TriggerScanMessage trigger_scan_message;
656   MockHandler80211 response_handler;
657   MockHandlerNetlinkAuxilliary auxilliary_handler;
658   MockHandlerNetlinkAck ack_handler;
659   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
660   NetlinkManager::NetlinkAuxilliaryMessageHandler null_error_handler;
661   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
662       &trigger_scan_message, response_handler.on_netlink_message(),
663       ack_handler.on_netlink_message(),
664       auxilliary_handler.on_netlink_message()));
665 
666   // Build a multi-part response (well, it's just one message but it'll be
667   // received multiple times).
668   const uint32_t kSequenceNumber = 32;  // Arbitrary (replaced, later).
669   NewScanResultsMessage new_scan_results;
670   new_scan_results.AddFlag(NLM_F_MULTI);
671   ByteString new_scan_results_bytes(new_scan_results.Encode(kSequenceNumber));
672   MutableNetlinkPacket received_message(
673       new_scan_results_bytes.GetData(), new_scan_results_bytes.GetLength());
674   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
675 
676   // Verify that the message-specific handler is called.
677   EXPECT_CALL(response_handler, OnNetlinkMessage(_));
678   netlink_manager_->OnNlMessageReceived(&received_message);
679 
680   // Verify that the message-specific handler is still called.
681   EXPECT_CALL(response_handler, OnNetlinkMessage(_));
682   received_message.ResetConsumedBytes();
683   netlink_manager_->OnNlMessageReceived(&received_message);
684 
685   // Build a Done message with the sent-message sequence number.
686   DoneMessage done_message;
687   done_message.AddFlag(NLM_F_MULTI);
688   ByteString done_message_bytes(
689       done_message.Encode(netlink_socket_->GetLastSequenceNumber()));
690   NetlinkPacket done_packet(
691       done_message_bytes.GetData(), done_message_bytes.GetLength());
692 
693   // Verify that the message-specific auxilliary handler is called for the done
694   // message, with the correct message type.
695   EXPECT_CALL(auxilliary_handler, OnErrorHandler(NetlinkManager::kDone, _));
696 
697   netlink_manager_->OnNlMessageReceived(&done_packet);
698 
699   // Verify that broadcast handler is called now that the done message has
700   // been seen.
701   EXPECT_CALL(response_handler, OnNetlinkMessage(_)).Times(0);
702   EXPECT_CALL(auxilliary_handler, OnErrorHandler(_, _)).Times(0);
703   EXPECT_CALL(ack_handler, OnAckHandler(_)).Times(0);
704   EXPECT_CALL(broadcast_handler, OnNetlinkMessage(_)).Times(1);
705   received_message.ResetConsumedBytes();
706   netlink_manager_->OnNlMessageReceived(&received_message);
707 }
708 
TEST_F(NetlinkManagerTest,TimeoutResponseHandlers)709 TEST_F(NetlinkManagerTest, TimeoutResponseHandlers) {
710   Reset();
711   MockHandlerNetlink broadcast_handler;
712   EXPECT_TRUE(netlink_manager_->AddBroadcastHandler(
713       broadcast_handler.on_netlink_message()));
714 
715   // Set up the received message as a response to the get_wiphy_message
716   // we're going to send.
717   NewWiphyMessage new_wiphy_message;
718   const uint32_t kRandomSequenceNumber = 3;
719   ByteString new_wiphy_message_bytes =
720       new_wiphy_message.Encode(kRandomSequenceNumber);
721   MutableNetlinkPacket received_message(
722       new_wiphy_message_bytes.GetData(), new_wiphy_message_bytes.GetLength());
723 
724   // Setup a random received message to trigger wiping out old messages.
725   NewScanResultsMessage new_scan_results;
726   ByteString new_scan_results_bytes =
727       new_scan_results.Encode(kRandomSequenceNumber);
728 
729   // Setup the timestamps of various messages
730   MockTime time;
731   Time* old_time = netlink_manager_->time_;
732   netlink_manager_->time_ = &time;
733 
734   time_t kStartSeconds = 1234;  // Arbitrary.
735   suseconds_t kSmallUsec = 100;
736   EXPECT_CALL(time, GetTimeMonotonic(_)).
737       WillOnce(Invoke(TimeFunctor(kStartSeconds, 0))).  // Initial time.
738       WillOnce(Invoke(TimeFunctor(kStartSeconds, kSmallUsec))).
739 
740       WillOnce(Invoke(TimeFunctor(kStartSeconds, 0))).  // Initial time.
741       WillOnce(Invoke(TimeFunctor(
742           kStartSeconds + NetlinkManager::kResponseTimeoutSeconds + 1,
743           NetlinkManager::kResponseTimeoutMicroSeconds)));
744   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillRepeatedly(Return(true));
745 
746   GetWiphyMessage get_wiphy_message;
747   MockHandler80211 response_handler;
748   MockHandlerNetlinkAuxilliary auxilliary_handler;
749   MockHandlerNetlinkAck ack_handler;
750 
751   GetRegMessage get_reg_message;  // Just a message to trigger timeout.
752   NetlinkManager::Nl80211MessageHandler null_message_handler;
753   NetlinkManager::NetlinkAuxilliaryMessageHandler null_error_handler;
754   NetlinkManager::NetlinkAckHandler null_ack_handler;
755 
756   // Send two messages within the message handler timeout; verify that we
757   // get called back (i.e., that the first handler isn't discarded).
758   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
759       &get_wiphy_message, response_handler.on_netlink_message(),
760       ack_handler.on_netlink_message(),
761       auxilliary_handler.on_netlink_message()));
762   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
763   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
764       &get_reg_message, null_message_handler, null_ack_handler,
765       null_error_handler));
766   EXPECT_CALL(response_handler, OnNetlinkMessage(_));
767   netlink_manager_->OnNlMessageReceived(&received_message);
768 
769   // Send two messages at an interval greater than the message handler timeout
770   // before the response to the first arrives.  Verify that the error handler
771   // for the first message is called (with a timeout flag) and that the
772   // broadcast handler gets called, instead of the message's handler.
773   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
774       &get_wiphy_message, response_handler.on_netlink_message(),
775       ack_handler.on_netlink_message(),
776       auxilliary_handler.on_netlink_message()));
777   received_message.ResetConsumedBytes();
778   received_message.SetMessageSequence(netlink_socket_->GetLastSequenceNumber());
779   EXPECT_CALL(
780       auxilliary_handler,
781       OnErrorHandler(NetlinkManager::kTimeoutWaitingForResponse, nullptr));
782   EXPECT_TRUE(netlink_manager_->SendNl80211Message(&get_reg_message,
783                                                    null_message_handler,
784                                                    null_ack_handler,
785                                                    null_error_handler));
786   EXPECT_CALL(response_handler, OnNetlinkMessage(_)).Times(0);
787   EXPECT_CALL(broadcast_handler, OnNetlinkMessage(_));
788   netlink_manager_->OnNlMessageReceived(&received_message);
789 
790   // Put the state of the singleton back where it was.
791   netlink_manager_->time_ = old_time;
792 }
793 
TEST_F(NetlinkManagerTest,PendingDump)794 TEST_F(NetlinkManagerTest, PendingDump) {
795   // Set up the responses to the two get station messages  we're going to send.
796   // The response to then first message is a 2-message multi-part response,
797   // while the response to the second is a single response.
798   NewStationMessage new_station_message_1_pt1;
799   NewStationMessage new_station_message_1_pt2;
800   NewStationMessage new_station_message_2;
801   const uint32_t kRandomSequenceNumber = 3;
802   new_station_message_1_pt1.AddFlag(NLM_F_MULTI);
803   new_station_message_1_pt2.AddFlag(NLM_F_MULTI);
804   ByteString new_station_message_1_pt1_bytes =
805       new_station_message_1_pt1.Encode(kRandomSequenceNumber);
806   ByteString new_station_message_1_pt2_bytes =
807       new_station_message_1_pt2.Encode(kRandomSequenceNumber);
808   ByteString new_station_message_2_bytes =
809       new_station_message_2.Encode(kRandomSequenceNumber);
810   MutableNetlinkPacket received_message_1_pt1(
811       new_station_message_1_pt1_bytes.GetData(),
812       new_station_message_1_pt1_bytes.GetLength());
813   MutableNetlinkPacket received_message_1_pt2(
814       new_station_message_1_pt2_bytes.GetData(),
815       new_station_message_1_pt2_bytes.GetLength());
816   received_message_1_pt2.SetMessageType(NLMSG_DONE);
817   MutableNetlinkPacket received_message_2(
818       new_station_message_2_bytes.GetData(),
819       new_station_message_2_bytes.GetLength());
820 
821   // The two get station messages (with the dump flag set) will be sent one
822   // after another. The second message can only be sent once all replies to the
823   // first have been received. The get wiphy message will be sent while waiting
824   // for replies from the first get station message.
825   GetStationMessage get_station_message_1;
826   get_station_message_1.AddFlag(NLM_F_DUMP);
827   GetStationMessage get_station_message_2;
828   get_station_message_2.AddFlag(NLM_F_DUMP);
829   GetWiphyMessage get_wiphy_message;
830   MockHandler80211 response_handler;
831   MockHandlerNetlinkAuxilliary auxilliary_handler;
832   MockHandlerNetlinkAck ack_handler;
833 
834   // Send the first get station message, which should be sent immediately and
835   // trigger a pending dump.
836   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
837   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
838       &get_station_message_1, response_handler.on_netlink_message(),
839       ack_handler.on_netlink_message(),
840       auxilliary_handler.on_netlink_message()));
841   uint16_t get_station_message_1_seq_num =
842       netlink_socket_->GetLastSequenceNumber();
843   EXPECT_TRUE(netlink_manager_->IsDumpPending());
844   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
845   EXPECT_EQ(get_station_message_1_seq_num,
846             netlink_manager_->PendingDumpSequenceNumber());
847 
848   // Send the second get station message before the replies to the first
849   // get station message have been received. This should cause the message
850   // to be enqueued for later sending.
851   EXPECT_CALL(*netlink_socket_, SendMessage(_)).Times(0);
852   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
853       &get_station_message_2, response_handler.on_netlink_message(),
854       ack_handler.on_netlink_message(),
855       auxilliary_handler.on_netlink_message()));
856   uint16_t get_station_message_2_seq_num =
857       netlink_socket_->GetLastSequenceNumber();
858   EXPECT_TRUE(netlink_manager_->IsDumpPending());
859   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
860   EXPECT_EQ(get_station_message_1_seq_num,
861             netlink_manager_->PendingDumpSequenceNumber());
862 
863   // Send the get wiphy message before the replies to the first
864   // get station message have been received. Since this message does not have
865   // the NLM_F_DUMP flag set, it will not be enqueued and sent immediately.
866   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
867   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
868       &get_wiphy_message, response_handler.on_netlink_message(),
869       ack_handler.on_netlink_message(),
870       auxilliary_handler.on_netlink_message()));
871   EXPECT_TRUE(netlink_manager_->IsDumpPending());
872   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
873   EXPECT_EQ(get_station_message_1_seq_num,
874             netlink_manager_->PendingDumpSequenceNumber());
875 
876   // Now we receive the two-part response to the first message.
877   // On receiving the first part, keep waiting for second part.
878   received_message_1_pt1.SetMessageSequence(get_station_message_1_seq_num);
879   EXPECT_CALL(response_handler, OnNetlinkMessage(_));
880   netlink_manager_->OnNlMessageReceived(&received_message_1_pt1);
881   EXPECT_TRUE(netlink_manager_->IsDumpPending());
882   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
883   EXPECT_EQ(get_station_message_1_seq_num,
884             netlink_manager_->PendingDumpSequenceNumber());
885 
886   // On receiving second part of the message, report done to the error handler,
887   // and dispatch the next message in the queue.
888   received_message_1_pt2.SetMessageSequence(get_station_message_1_seq_num);
889   EXPECT_CALL(auxilliary_handler, OnErrorHandler(NetlinkManager::kDone, _));
890   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
891   netlink_manager_->OnNlMessageReceived(&received_message_1_pt2);
892   EXPECT_TRUE(netlink_manager_->IsDumpPending());
893   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
894   EXPECT_EQ(get_station_message_2_seq_num,
895             netlink_manager_->PendingDumpSequenceNumber());
896 
897   // Receive response to second dump message, and stop waiting for dump replies.
898   received_message_2.SetMessageSequence(get_station_message_2_seq_num);
899   EXPECT_CALL(response_handler, OnNetlinkMessage(_));
900   EXPECT_CALL(*netlink_socket_, SendMessage(_)).Times(0);
901   netlink_manager_->OnNlMessageReceived(&received_message_2);
902   EXPECT_FALSE(netlink_manager_->IsDumpPending());
903   EXPECT_TRUE(netlink_manager_->pending_messages_.empty());
904   EXPECT_EQ(0, netlink_manager_->PendingDumpSequenceNumber());
905 
906   // Put the state of the singleton back where it was.
907   Reset();
908 }
909 
TEST_F(NetlinkManagerTest,PendingDump_Timeout)910 TEST_F(NetlinkManagerTest, PendingDump_Timeout) {
911   // These two messages will be sent one after another.
912   GetStationMessage get_station_message_1;
913   get_station_message_1.AddFlag(NLM_F_DUMP);
914   GetStationMessage get_station_message_2;
915   get_station_message_2.AddFlag(NLM_F_DUMP);
916   MockHandler80211 response_handler;
917   MockHandlerNetlinkAuxilliary auxilliary_handler;
918   MockHandlerNetlinkAck ack_handler;
919 
920   // Send the first get station message, which should be sent immediately and
921   // trigger a pending dump.
922   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
923   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
924       &get_station_message_1, response_handler.on_netlink_message(),
925       ack_handler.on_netlink_message(),
926       auxilliary_handler.on_netlink_message()));
927   uint16_t get_station_message_1_seq_num =
928       netlink_socket_->GetLastSequenceNumber();
929   EXPECT_TRUE(netlink_manager_->IsDumpPending());
930   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
931   EXPECT_EQ(get_station_message_1_seq_num,
932             netlink_manager_->PendingDumpSequenceNumber());
933 
934   // Send the second get station message before the replies to the first
935   // get station message have been received. This should cause the message
936   // to be enqueued for later sending.
937   EXPECT_CALL(*netlink_socket_, SendMessage(_)).Times(0);
938   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
939       &get_station_message_2, response_handler.on_netlink_message(),
940       ack_handler.on_netlink_message(),
941       auxilliary_handler.on_netlink_message()));
942   uint16_t get_station_message_2_seq_num =
943       netlink_socket_->GetLastSequenceNumber();
944   EXPECT_TRUE(netlink_manager_->IsDumpPending());
945   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
946   EXPECT_EQ(get_station_message_1_seq_num,
947             netlink_manager_->PendingDumpSequenceNumber());
948 
949   // Timeout waiting for responses to the first get station message. This
950   // should cause the second get station message to be sent.
951   EXPECT_CALL(auxilliary_handler,
952               OnErrorHandler(NetlinkManager::kTimeoutWaitingForResponse, _));
953   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
954   netlink_manager_->OnPendingDumpTimeout();
955   EXPECT_TRUE(netlink_manager_->IsDumpPending());
956   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
957   EXPECT_EQ(get_station_message_2_seq_num,
958             netlink_manager_->PendingDumpSequenceNumber());
959 
960   // Put the state of the singleton back where it was.
961   Reset();
962 }
963 
TEST_F(NetlinkManagerTest,PendingDump_Retry)964 TEST_F(NetlinkManagerTest, PendingDump_Retry) {
965   const int kNumRetries = 1;
966   // Create EBUSY netlink error response. Do this manually because
967   // ErrorAckMessage does not implement NetlinkMessage::Encode.
968   MutableNetlinkPacket received_ebusy_message(kNLMSG_ACK, sizeof(kNLMSG_ACK));
969   *received_ebusy_message.GetMutablePayload() =
970       ByteString::CreateFromCPUUInt32(EBUSY);
971 
972   // The two get station messages (with the dump flag set) will be sent one
973   // after another. The second message can only be sent once all replies to the
974   // first have been received.
975   GetStationMessage get_station_message_1;
976   get_station_message_1.AddFlag(NLM_F_DUMP);
977   GetStationMessage get_station_message_2;
978   get_station_message_2.AddFlag(NLM_F_DUMP);
979   MockHandler80211 response_handler;
980   MockHandlerNetlinkAuxilliary auxilliary_handler;
981   MockHandlerNetlinkAck ack_handler;
982 
983   // Send the first get station message, which should be sent immediately and
984   // trigger a pending dump.
985   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
986   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
987       &get_station_message_1, response_handler.on_netlink_message(),
988       ack_handler.on_netlink_message(),
989       auxilliary_handler.on_netlink_message()));
990   uint16_t get_station_message_1_seq_num =
991       netlink_socket_->GetLastSequenceNumber();
992   EXPECT_TRUE(netlink_manager_->IsDumpPending());
993   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
994   EXPECT_EQ(get_station_message_1_seq_num,
995             netlink_manager_->PendingDumpSequenceNumber());
996 
997   // Send the second get station message before the replies to the first
998   // get station message have been received. This should cause the message
999   // to be enqueued for later sending.
1000   EXPECT_CALL(*netlink_socket_, SendMessage(_)).Times(0);
1001   EXPECT_TRUE(netlink_manager_->SendNl80211Message(
1002       &get_station_message_2, response_handler.on_netlink_message(),
1003       ack_handler.on_netlink_message(),
1004       auxilliary_handler.on_netlink_message()));
1005   uint16_t get_station_message_2_seq_num =
1006       netlink_socket_->GetLastSequenceNumber();
1007   EXPECT_TRUE(netlink_manager_->IsDumpPending());
1008   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
1009   EXPECT_EQ(get_station_message_1_seq_num,
1010             netlink_manager_->PendingDumpSequenceNumber());
1011 
1012   // Now we receive an EBUSY error response, which should trigger a retry and
1013   // not invoke the error handler.
1014   netlink_manager_->pending_messages_.front().retries_left = kNumRetries;
1015   received_ebusy_message.SetMessageSequence(get_station_message_1_seq_num);
1016   EXPECT_EQ(kNumRetries,
1017             netlink_manager_->pending_messages_.front().retries_left);
1018   EXPECT_CALL(auxilliary_handler, OnErrorHandler(_, _)).Times(0);
1019   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
1020   netlink_manager_->OnNlMessageReceived(&received_ebusy_message);
1021   // Cancel timeout callback before attempting resend.
1022   EXPECT_TRUE(netlink_manager_->pending_dump_timeout_callback_.IsCancelled());
1023   EXPECT_FALSE(netlink_manager_->resend_dump_message_callback_.IsCancelled());
1024   // Trigger this manually instead of via message loop since it is posted as a
1025   // delayed task, which base::RunLoop().RunUntilIdle() will not dispatch.
1026   netlink_manager_->ResendPendingDumpMessage();
1027   EXPECT_EQ(kNumRetries - 1,
1028             netlink_manager_->pending_messages_.front().retries_left);
1029   EXPECT_TRUE(netlink_manager_->IsDumpPending());
1030   EXPECT_EQ(2, netlink_manager_->pending_messages_.size());
1031   EXPECT_EQ(get_station_message_1_seq_num,
1032             netlink_manager_->PendingDumpSequenceNumber());
1033 
1034   // We receive an EBUSY error response again. Since we have no retries left for
1035   // this message, the error handler should be invoked, and the next pending
1036   // message sent.
1037   received_ebusy_message.ResetConsumedBytes();
1038   received_ebusy_message.SetMessageSequence(get_station_message_1_seq_num);
1039   EXPECT_EQ(0, netlink_manager_->pending_messages_.front().retries_left);
1040   EXPECT_CALL(auxilliary_handler,
1041               OnErrorHandler(NetlinkManager::kErrorFromKernel, _));
1042   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(true));
1043   netlink_manager_->OnNlMessageReceived(&received_ebusy_message);
1044   EXPECT_TRUE(netlink_manager_->IsDumpPending());
1045   EXPECT_EQ(1, netlink_manager_->pending_messages_.size());
1046   EXPECT_EQ(get_station_message_2_seq_num,
1047             netlink_manager_->PendingDumpSequenceNumber());
1048 
1049   // Now we receive an EBUSY error response to the second get station message,
1050   // which should trigger a retry. However, we fail on sending this second retry
1051   // out on the netlink socket. Since we expended our one retry on this attempt,
1052   // we should invoke the error handler and declare the dump complete.
1053   received_ebusy_message.ResetConsumedBytes();
1054   received_ebusy_message.SetMessageSequence(get_station_message_2_seq_num);
1055   EXPECT_EQ(1, netlink_manager_->pending_messages_.front().retries_left);
1056   EXPECT_CALL(auxilliary_handler,
1057               OnErrorHandler(NetlinkManager::kErrorFromKernel, _));
1058   EXPECT_CALL(*netlink_socket_, SendMessage(_)).WillOnce(Return(false));
1059   netlink_manager_->OnNlMessageReceived(&received_ebusy_message);
1060   // Cancel timeout callback before attempting resend.
1061   EXPECT_TRUE(netlink_manager_->pending_dump_timeout_callback_.IsCancelled());
1062   EXPECT_FALSE(netlink_manager_->resend_dump_message_callback_.IsCancelled());
1063   // Trigger this manually instead of via message loop since it is posted as a
1064   // delayed task, which base::RunLoop().RunUntilIdle() will not dispatch.
1065   netlink_manager_->ResendPendingDumpMessage();
1066   EXPECT_FALSE(netlink_manager_->IsDumpPending());
1067   EXPECT_TRUE(netlink_manager_->pending_dump_timeout_callback_.IsCancelled());
1068   EXPECT_TRUE(netlink_manager_->resend_dump_message_callback_.IsCancelled());
1069   EXPECT_TRUE(netlink_manager_->pending_messages_.empty());
1070 
1071   // Put the state of the singleton back where it was.
1072   Reset();
1073 }
1074 
1075 // Not strictly part of the "public" interface, but part of the
1076 // external interface.
TEST_F(NetlinkManagerTest,OnInvalidRawNlMessageReceived)1077 TEST_F(NetlinkManagerTest, OnInvalidRawNlMessageReceived) {
1078   MockHandlerNetlink message_handler;
1079   netlink_manager_->AddBroadcastHandler(message_handler.on_netlink_message());
1080 
1081   vector<unsigned char> bad_len_message{ 0x01 };  // len should be 32-bits
1082   vector<unsigned char> bad_hdr_message{ 0x04, 0x00, 0x00, 0x00 };  // only len
1083   vector<unsigned char> bad_body_message{
1084     0x30, 0x00, 0x00, 0x00,  // length
1085     0x00, 0x00,  // type
1086     0x00, 0x00,  // flags
1087     0x00, 0x00, 0x00, 0x00,  // sequence number
1088     0x00, 0x00, 0x00, 0x00,  // sender port
1089     // Body is empty, but should be 32 bytes.
1090   };
1091 
1092   for (auto message : {bad_len_message, bad_hdr_message, bad_body_message}) {
1093     EXPECT_CALL(message_handler, OnNetlinkMessage(_)).Times(0);
1094     InputData data(message.data(), message.size());
1095     netlink_manager_->OnRawNlMessageReceived(&data);
1096     Mock::VerifyAndClearExpectations(&message_handler);
1097   }
1098 
1099   vector<unsigned char> good_message{
1100     0x14, 0x00, 0x00, 0x00,  // length
1101     0x00, 0x00,  // type
1102     0x00, 0x00,  // flags
1103     0x00, 0x00, 0x00, 0x00,  // sequence number
1104     0x00, 0x00, 0x00, 0x00,  // sender port
1105     0x00, 0x00, 0x00, 0x00,  // body
1106   };
1107 
1108   for (auto bad_msg : {bad_len_message, bad_hdr_message, bad_body_message}) {
1109     // A good message followed by a bad message. This should yield one call
1110     // to |message_handler|, and one error message.
1111     vector<unsigned char> two_messages(
1112         good_message.begin(), good_message.end());
1113     two_messages.insert(two_messages.end(), bad_msg.begin(), bad_msg.end());
1114     EXPECT_CALL(message_handler, OnNetlinkMessage(_)).Times(1);
1115     InputData data(two_messages.data(), two_messages.size());
1116     netlink_manager_->OnRawNlMessageReceived(&data);
1117     Mock::VerifyAndClearExpectations(&message_handler);
1118   }
1119 
1120   EXPECT_CALL(message_handler, OnNetlinkMessage(_)).Times(0);
1121   netlink_manager_->OnRawNlMessageReceived(nullptr);
1122 }
1123 
1124 }  // namespace shill
1125