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 software provides an abstracted interface to the netlink socket
18 // interface.  In its current implementation it is used, primarily, to
19 // communicate with the cfg80211 kernel module and mac80211 drivers:
20 //
21 //         [shill]--[nl80211 library]
22 //            |
23 //     (netlink socket)
24 //            |
25 // [cfg80211 kernel module]
26 //            |
27 //    [mac80211 drivers]
28 //
29 // In order to send a message and handle it's response, do the following:
30 // - Create a handler (it'll want to verify that it's the kind of message you
31 //   want, cast it to the appropriate type, and get attributes from the cast
32 //   message):
33 //
34 //    #include "nl80211_message.h"
35 //    class SomeClass {
36 //      static void MyMessageHandler(const NetlinkMessage& raw) {
37 //        if (raw.message_type() != ControlNetlinkMessage::kMessageType)
38 //          return;
39 //        const ControlNetlinkMessage* message =
40 //          reinterpret_cast<const ControlNetlinkMessage*>(&raw);
41 //        if (message.command() != NewFamilyMessage::kCommand)
42 //          return;
43 //        uint16_t my_attribute;
44 //        message->const_attributes()->GetU16AttributeValue(
45 //          CTRL_ATTR_FAMILY_ID, &my_attribute);
46 //      }  // MyMessageHandler.
47 //    }  // class SomeClass.
48 //
49 // - Instantiate a message:
50 //
51 //    #include "nl80211_message.h"
52 //    GetFamilyMessage msg;
53 //
54 // - And set attributes:
55 //
56 //    msg.attributes()->SetStringAttributeValue(CTRL_ATTR_FAMILY_NAME, "foo");
57 //
58 // - Then send the message, passing-in a closure to the handler you created:
59 //
60 //    NetlinkManager* netlink_manager = NetlinkManager::GetInstance();
61 //    netlink_manager->SendMessage(&msg, Bind(&SomeClass::MyMessageHandler));
62 //
63 // NetlinkManager will then save your handler and send your message.  When a
64 // response to your message arrives, it'll call your handler.
65 //
66 
67 #ifndef SHILL_NET_NETLINK_MANAGER_H_
68 #define SHILL_NET_NETLINK_MANAGER_H_
69 
70 #include <list>
71 #include <map>
72 #include <memory>
73 #include <queue>
74 #include <set>
75 #include <string>
76 
77 #include <base/bind.h>
78 #include <base/cancelable_callback.h>
79 #include <base/lazy_instance.h>
80 #include <base/macros.h>
81 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
82 
83 #include "shill/net/generic_netlink_message.h"
84 #include "shill/net/io_handler_factory_container.h"
85 #include "shill/net/netlink_message.h"
86 #include "shill/net/netlink_socket.h"
87 #include "shill/net/shill_export.h"
88 #include "shill/net/shill_time.h"
89 
90 namespace shill {
91 
92 class ControlNetlinkMessage;
93 struct InputData;
94 class NetlinkPacket;
95 class Nl80211Message;
96 
97 // NetlinkManager is a singleton that coordinates sending netlink messages to,
98 // and receiving netlink messages from, the kernel.  The first use of this is
99 // to communicate between user-space and the cfg80211 module that manages wifi
100 // drivers.  Bring NetlinkManager up as follows:
101 //  NetlinkManager* netlink_manager_ = NetlinkManager::GetInstance();
102 //  netlink_manager_->Init();  // Initialize the socket.
103 //  // Get message types for all dynamic message types.
104 //  Nl80211Message::SetMessageType(
105 //      netlink_manager_->GetFamily(Nl80211Message::kMessageTypeString,
106 //                              Bind(&Nl80211Message::CreateMessage)));
107 //  netlink_manager_->Start();
108 class SHILL_EXPORT NetlinkManager {
109  public:
110   enum AuxilliaryMessageType {
111     kDone,
112     kErrorFromKernel,
113     kTimeoutWaitingForResponse,
114     kUnexpectedResponseType
115   };
116   typedef base::Callback<void(const NetlinkMessage&)> NetlinkMessageHandler;
117   typedef base::Callback<void(const ControlNetlinkMessage&)>
118       ControlNetlinkMessageHandler;
119   typedef base::Callback<void(const Nl80211Message&)> Nl80211MessageHandler;
120   // NetlinkAuxilliaryMessageHandler handles netlink error messages, things
121   // like the DoneMessage at the end of a multi-part message, and any errors
122   // discovered by |NetlinkManager| (which are passed as NULL pointers because
123   // there is no way to reserve a part of the ErrorAckMessage space for
124   // non-netlink errors).
125   typedef base::Callback<void(AuxilliaryMessageType type,
126                               const NetlinkMessage*)>
127       NetlinkAuxilliaryMessageHandler;
128   // NetlinkAckHandler handles netlink Ack messages, which are a special type
129   // of netlink error message carrying an error code of 0. Since Ack messages
130   // contain no useful data (other than the error code of 0 to differentiate
131   // it from an actual error message), the handler is not passed a message.
132   // as an argument. The boolean value filled in by the handler (via the
133   // pointer) indicates whether or not the callbacks registered for the message
134   // (identified by sequence number) that this handler was invoked for should be
135   // removed after this callback is executed. This allows a sender of an NL80211
136   // message to handle both an Ack and another response message, rather than
137   // handle only the first response received.
138   typedef base::Callback<void(bool*)> NetlinkAckHandler;
139 
140   // ResponseHandlers provide a polymorphic context for the base::Callback
141   // message handlers so that handlers for different types of messages can be
142   // kept in the same container (namely, |message_handlers_|).
143   class NetlinkResponseHandler :
144     public base::RefCounted<NetlinkResponseHandler> {
145    public:
146     explicit NetlinkResponseHandler(
147         const NetlinkAckHandler& ack_handler,
148         const NetlinkAuxilliaryMessageHandler& error_handler);
149     virtual ~NetlinkResponseHandler();
150     // Calls wrapper-type-specific callback for |netlink_message|.  Returns
151     // false if |netlink_message| is not the correct type.  Calls callback
152     // (which is declared in the private area of derived classes) with
153     // properly cast version of |netlink_message|.
154     virtual bool HandleMessage(const NetlinkMessage& netlink_message) const = 0;
155     void HandleError(AuxilliaryMessageType type,
156                      const NetlinkMessage* netlink_message) const;
157     virtual bool HandleAck() const;
set_delete_after(const timeval & time)158     void set_delete_after(const timeval& time) { delete_after_ = time; }
delete_after()159     const struct timeval& delete_after() const { return delete_after_; }
160 
161    protected:
162     NetlinkResponseHandler();
163     NetlinkAckHandler ack_handler_;
164 
165    private:
166     NetlinkAuxilliaryMessageHandler error_handler_;
167     struct timeval delete_after_;
168 
169     DISALLOW_COPY_AND_ASSIGN(NetlinkResponseHandler);
170   };
171 
172   // Encapsulates all the different things we know about a specific message
173   // type like its name, and its id.
174   struct MessageType {
175     MessageType();
176 
177     uint16_t family_id;
178 
179     // Multicast groups supported by the family.  The string and mapping to
180     // a group id are extracted from the CTRL_CMD_NEWFAMILY message.
181     std::map<std::string, uint32_t> groups;
182   };
183 
184   // Various kinds of events to which we can subscribe (and receive) from
185   // cfg80211.
186   static const char kEventTypeConfig[];
187   static const char kEventTypeScan[];
188   static const char kEventTypeRegulatory[];
189   static const char kEventTypeMlme[];
190 
191   // NetlinkManager is a singleton and this is the way to access it.
192   static NetlinkManager* GetInstance();
193 
194   virtual ~NetlinkManager();
195 
196   // Performs non-trivial object initialization of the NetlinkManager singleton.
197   virtual bool Init();
198 
199   // Passes the job of waiting for, and the subsequent reading from, the
200   // netlink socket to the current message loop.
201   virtual void Start();
202 
203   // The following methods deal with the network family table.  This table
204   // associates netlink family names with family_ids (also called message
205   // types).  Note that some families have static ids assigned to them but
206   // others require the kernel to resolve a string describing the family into
207   // a dynamically-determined id.
208 
209   // Returns the family_id (message type) associated with |family_name|,
210   // calling the kernel if needed.  Returns
211   // |NetlinkMessage::kIllegalMessageType| if the message type could not be
212   // determined.  May block so |GetFamily| should be called before entering the
213   // event loop.
214   virtual uint16_t GetFamily(const std::string& family_name,
215       const NetlinkMessageFactory::FactoryMethod& message_factory);
216 
217   // Install a NetlinkManager NetlinkMessageHandler.  The handler is a
218   // user-supplied object to be called by the system for user-bound messages
219   // that do not have a corresponding messaage-specific callback.
220   // |AddBroadcastHandler| should be called before |SubscribeToEvents| since
221   // the result of this call are used for that call.
222   virtual bool AddBroadcastHandler(
223       const NetlinkMessageHandler& message_handler);
224 
225   // Uninstall a NetlinkMessage Handler.
226   virtual bool RemoveBroadcastHandler(
227       const NetlinkMessageHandler& message_handler);
228 
229   // Determines whether a handler is in the list of broadcast handlers.
230   bool FindBroadcastHandler(const NetlinkMessageHandler& message_handler) const;
231 
232   // Uninstall all broadcast netlink message handlers.
233   void ClearBroadcastHandlers();
234 
235   // Sends a netlink message to the kernel using the NetlinkManager socket after
236   // installing a handler to deal with the kernel's response to the message.
237   // TODO(wdg): Eventually, this should also include a timeout and a callback
238   // to call in case of timeout.
239   virtual bool SendControlMessage(
240       ControlNetlinkMessage* message,
241       const ControlNetlinkMessageHandler& message_handler,
242       const NetlinkAckHandler& ack_handler,
243       const NetlinkAuxilliaryMessageHandler& error_handler);
244   virtual bool SendNl80211Message(
245       Nl80211Message* message,
246       const Nl80211MessageHandler& message_handler,
247       const NetlinkAckHandler& ack_handler,
248       const NetlinkAuxilliaryMessageHandler& error_handler);
249 
250   // Generic erroneous message handler everyone can use.
251   static void OnNetlinkMessageError(AuxilliaryMessageType type,
252                                     const NetlinkMessage* raw_message);
253 
254   // Generic Ack handler that does nothing. Other callbacks registered for the
255   // message are not deleted after this function is executed.
OnAckDoNothing(bool * remove_callbacks)256   static void OnAckDoNothing(bool* remove_callbacks) {
257     *remove_callbacks = false;
258   }
259 
260   // Uninstall the handler for a specific netlink message.
261   bool RemoveMessageHandler(const NetlinkMessage& message);
262 
263   // Sign-up to receive and log multicast events of a specific type (once wifi
264   // is up).
265   virtual bool SubscribeToEvents(const std::string& family,
266                                  const std::string& group);
267 
268   // Gets the next sequence number for a NetlinkMessage to be sent over
269   // NetlinkManager's netlink socket.
270   uint32_t GetSequenceNumber();
271 
272  protected:
273   friend struct base::DefaultLazyInstanceTraits<NetlinkManager>;
274 
275   NetlinkManager();
276 
277  private:
278   friend class NetlinkManagerTest;
279   friend class NetlinkMessageTest;
280   friend class ShillDaemonTest;
281   friend class ChromeosDaemonTest;
282   FRIEND_TEST(NetlinkManagerTest, AddLinkTest);
283   FRIEND_TEST(NetlinkManagerTest, BroadcastHandler);
284   FRIEND_TEST(NetlinkManagerTest, GetFamilyOneInterstitialMessage);
285   FRIEND_TEST(NetlinkManagerTest, GetFamilyTimeout);
286   FRIEND_TEST(NetlinkManagerTest, MessageHandler);
287   FRIEND_TEST(NetlinkManagerTest, AckHandler);
288   FRIEND_TEST(NetlinkManagerTest, ErrorHandler);
289   FRIEND_TEST(NetlinkManagerTest, MultipartMessageHandler);
290   FRIEND_TEST(NetlinkManagerTest, OnInvalidRawNlMessageReceived);
291   FRIEND_TEST(NetlinkManagerTest, TimeoutResponseHandlers);
292   FRIEND_TEST(NetlinkManagerTest, PendingDump);
293   FRIEND_TEST(NetlinkManagerTest, PendingDump_Timeout);
294   FRIEND_TEST(NetlinkManagerTest, PendingDump_Retry);
295   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_ASSOCIATE);
296   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_AUTHENTICATE);
297   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_CONNECT);
298   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_DEAUTHENTICATE);
299   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_DISASSOCIATE);
300   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_DISCONNECT);
301   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_NEW_SCAN_RESULTS);
302   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_NEW_STATION);
303   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_NOTIFY_CQM);
304   FRIEND_TEST(NetlinkMessageTest, Parse_NL80211_CMD_TRIGGER_SCAN);
305 
306   typedef scoped_refptr<NetlinkResponseHandler> NetlinkResponseHandlerRefPtr;
307 
308   // Container for information we need to send a netlink message out on a
309   // netlink socket.
310   struct NetlinkPendingMessage {
311     NetlinkPendingMessage(uint32_t sequence_number_arg,
312                           bool is_dump_request_arg,
313                           ByteString message_string_arg,
314                           NetlinkResponseHandlerRefPtr handler_arg)
315         : retries_left(kMaxNlMessageRetries),
316           sequence_number(sequence_number_arg),
317           is_dump_request(is_dump_request_arg),
318           message_string(message_string_arg),
319           handler(handler_arg) {}
320 
321     int retries_left;
322     uint32_t sequence_number;
323     bool is_dump_request;
324     ByteString message_string;
325     NetlinkResponseHandlerRefPtr handler;
326     uint32_t last_received_error;
327   };
328 
329   // These need to be member variables, even though they're only used once in
330   // the code, since they're needed for unittests.
331   static const long kMaximumNewFamilyWaitSeconds;  // NOLINT
332   static const long kMaximumNewFamilyWaitMicroSeconds;  // NOLINT
333   static const long kResponseTimeoutSeconds;  // NOLINT
334   static const long kResponseTimeoutMicroSeconds;  // NOLINT
335   static const long kPendingDumpTimeoutMilliseconds;  // NOLINT
336   static const long kNlMessageRetryDelayMilliseconds;  // NOLINT
337   static const int kMaxNlMessageRetries;  // NOLINT
338 
339   // Returns the file descriptor of socket used to read wifi data.
340   int file_descriptor() const;
341 
342   // MessageLoop calls this when data is available on our socket.  This
343   // method passes each, individual, message in the input to
344   // |OnNlMessageReceived|.  Each part of a multipart message gets handled,
345   // individually, by this method.
346   void OnRawNlMessageReceived(InputData* data);
347 
348   // This method processes a message from |OnRawNlMessageReceived| by passing
349   // the message to either the NetlinkManager callback that matches the sequence
350   // number of the message or, if there isn't one, to all of the default
351   // NetlinkManager callbacks in |broadcast_handlers_|.
352   void OnNlMessageReceived(NetlinkPacket* packet);
353 
354   // Sends the pending dump message, and decrement the message's retry count if
355   // it was resent successfully.
356   void ResendPendingDumpMessage();
357 
358   // If a NetlinkResponseHandler registered for the message identified by
359   // |sequence_number| exists, calls the error handler with the arguments |type|
360   // and |netlink_message|, then erases the NetlinkResponseHandler from
361   // |message_handlers_|.
362   void CallErrorHandler(uint32_t sequence_number, AuxilliaryMessageType type,
363                         const NetlinkMessage* netlink_message);
364 
365   // Called by InputHandler on exceptional events.
366   void OnReadError(const std::string& error_msg);
367 
368   // Utility function that posts a task to the message loop to call
369   // NetlinkManager::ResendPendingDumpMessage kNlMessageRetryDelayMilliseconds
370   // from now.
371   void ResendPendingDumpMessageAfterDelay();
372 
373   // Just for tests, this method turns off WiFi and clears the subscribed
374   // events list. If |full| is true, also clears state set by Init.
375   void Reset(bool full);
376 
377   // Handles a CTRL_CMD_NEWFAMILY message from the kernel.
378   void OnNewFamilyMessage(const ControlNetlinkMessage& message);
379 
380   // Sends a netlink message if |pending_dump_| is false. Otherwise, post
381   // a message to |pending_messages_| to be sent later.
382   bool SendOrPostMessage(
383       NetlinkMessage* message,
384       NetlinkResponseHandler* message_wrapper);  // Passes ownership.
385 
386   // Install a handler to deal with kernel's response to the message contained
387   // in |pending_message|, then sends the message by calling
388   // NetlinkManager::SendMessageInternal.
389   bool RegisterHandlersAndSendMessage(
390       const NetlinkPendingMessage& pending_message);
391 
392   // Sends the netlink message whose bytes are contained in |pending_message| to
393   // the kernel using the NetlinkManager socket. If |pending_message| is a dump
394   // request and the message is sent successfully, a timeout timer is started to
395   // limit the amount of time we wait for responses to that message. Adds a
396   // serial number to |message| before it is sent.
397   bool SendMessageInternal(const NetlinkPendingMessage& pending_message);
398 
399   // Given a netlink packet |packet|, infers the context of this netlink
400   // message (for message parsing purposes) and returns a MessageContext
401   // describing this context.
402   NetlinkMessage::MessageContext InferMessageContext(
403       const NetlinkPacket& packet);
404 
405   // Called when we time out waiting for a response to a netlink dump message.
406   // Invokes the error handler with kTimeoutWaitingForResponse, deletes the
407   // error handler, then calls NetlinkManager::OnPendingDumpComplete.
408   void OnPendingDumpTimeout();
409 
410   // Cancels |pending_dump_timeout_callback_|, deletes the currently pending
411   // dump request message from the front of |pending_messages_| since we have
412   // finished waiting for replies, then sends the next message in
413   // |pending_messages_| (if any).
414   void OnPendingDumpComplete();
415 
416   // Returns true iff there we are waiting for replies to a netlink dump
417   // message, false otherwise.
418   bool IsDumpPending();
419 
420   // Returns the sequence number of the pending netlink dump request message iff
421   // there is a pending dump. Otherwise, returns 0.
422   uint32_t PendingDumpSequenceNumber();
423 
424   // NetlinkManager Handlers, OnRawNlMessageReceived invokes each of these
425   // User-supplied callback object when _it_ gets called to read netlink data.
426   std::list<NetlinkMessageHandler> broadcast_handlers_;
427 
428   // Message-specific callbacks, mapped by message ID.
429   std::map<uint32_t, NetlinkResponseHandlerRefPtr> message_handlers_;
430 
431   // Netlink messages due to be sent to the kernel. If a dump is pending,
432   // the first element in this queue will contain the netlink dump request
433   // message that we are waiting on replies for.
434   std::queue<NetlinkPendingMessage> pending_messages_;
435 
436   base::WeakPtrFactory<NetlinkManager> weak_ptr_factory_;
437   base::CancelableClosure pending_dump_timeout_callback_;
438   base::CancelableClosure resend_dump_message_callback_;
439   base::Callback<void(InputData*)> dispatcher_callback_;
440   std::unique_ptr<IOHandler> dispatcher_handler_;
441 
442   std::unique_ptr<NetlinkSocket> sock_;
443   std::map<const std::string, MessageType> message_types_;
444   NetlinkMessageFactory message_factory_;
445   Time* time_;
446   IOHandlerFactory* io_handler_factory_;
447   bool dump_pending_;
448 
449   DISALLOW_COPY_AND_ASSIGN(NetlinkManager);
450 };
451 
452 }  // namespace shill
453 
454 #endif  // SHILL_NET_NETLINK_MANAGER_H_
455