Shill: Incorporating the functionality of 'iw event' into shill.

'iw event' has been ported into shill and there are unit tests.
It still needs a facility to send individual messages to the
kernel (and there are comments in the code to show where this is
intended) but this will wait for a later commit.

BUG=None.
TEST=Enclosed unit tests verified against manual test. Ran all WiFi
autotests and output matched 'iw event'.

Change-Id: Ia5f5e8b440d0a657ce7fdb3e2b8b5fc6c95323fe
Reviewed-on: https://gerrit.chromium.org/gerrit/24508
Commit-Ready: Wade Guthrie <wdg@chromium.org>
Reviewed-by: Wade Guthrie <wdg@chromium.org>
Tested-by: Wade Guthrie <wdg@chromium.org>
diff --git a/Makefile b/Makefile
index fe6597f..c41101c 100644
--- a/Makefile
+++ b/Makefile
@@ -17,11 +17,12 @@
 LIBDIR = /usr/lib
 SCRIPTDIR = $(LIBDIR)/flimflam/scripts
 CPPFLAGS += -DSCRIPTDIR=\"$(SCRIPTDIR)\"
-BASE_LIBS = -lbootstat -lcares -lmobile-provider -lmetrics -lminijail
+BASE_LIBS = -lbootstat -lcares -lmobile-provider -lmetrics -lminijail -lnl
 BASE_INCLUDE_DIRS = -iquote.. -iquote $(BUILDDIR)
 BASE_LIB_DIRS =
 
 LIBS = $(BASE_LIBS)
+
 BASE_VER = 125070
 PC_DEPS = dbus-c++-1 glib-2.0 gio-2.0 libchrome-$(BASE_VER) \
 	libchromeos-$(BASE_VER)
@@ -117,6 +118,7 @@
 	cellular_capability_universal.o \
 	cellular_error.o \
 	cellular_service.o \
+	config80211.o \
 	connection.o \
 	crypto_des_cbc.o \
 	crypto_provider.o \
@@ -152,6 +154,7 @@
 	ip_address.o \
 	ipconfig.o \
 	ipconfig_dbus_adaptor.o \
+	kernel_bound_nlmessage.o \
 	key_file_store.o \
 	key_value_store.o \
 	link_monitor.o \
@@ -177,6 +180,8 @@
 	modem_manager_proxy.o \
 	modem_proxy.o \
 	modem_simple_proxy.o \
+	netlink_socket.o \
+	nl80211_socket.o \
 	nss.o \
 	openvpn_driver.o \
 	openvpn_management_server.o \
@@ -210,6 +215,7 @@
 	supplicant_interface_proxy.o \
 	supplicant_process_proxy.o \
 	technology.o \
+	user_bound_nlmessage.o \
 	virtio_ethernet.o \
 	vpn.o \
 	vpn_driver.o \
@@ -247,6 +253,7 @@
 	crypto_des_cbc_unittest.o \
 	crypto_provider_unittest.o \
 	crypto_rot47_unittest.o \
+	config80211_unittest.o \
 	connection_unittest.o \
 	dbus_adaptor_unittest.o \
 	dbus_manager_unittest.o \
diff --git a/config80211.cc b/config80211.cc
new file mode 100644
index 0000000..6faf422
--- /dev/null
+++ b/config80211.cc
@@ -0,0 +1,227 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "shill/config80211.h"
+
+#include <ctype.h>
+
+#include <netlink/msg.h>
+
+#include <map>
+#include <sstream>
+#include <string>
+
+#include <base/memory/weak_ptr.h>
+#include <base/stringprintf.h>
+
+#include "shill/io_handler.h"
+#include "shill/logging.h"
+#include "shill/nl80211_socket.h"
+#include "shill/scope_logger.h"
+#include "shill/user_bound_nlmessage.h"
+
+using base::Bind;
+using base::LazyInstance;
+using base::StringAppendF;
+using base::StringPrintf;
+using std::map;
+using std::string;
+
+namespace shill {
+
+namespace {
+LazyInstance<Config80211> g_config80211 = LAZY_INSTANCE_INITIALIZER;
+LazyInstance<Callback80211Object> g_callback80211 = LAZY_INSTANCE_INITIALIZER;
+}  // namespace
+
+map<Config80211::EventType, std::string> *Config80211::event_types_ = NULL;
+
+Config80211::Config80211()
+    : dispatcher_(NULL),
+      weak_ptr_factory_(this),
+      dispatcher_callback_(Bind(&Config80211::HandleIncomingEvents,
+                              weak_ptr_factory_.GetWeakPtr())),
+      sock_(NULL) {
+}
+
+Config80211::~Config80211() {
+  // Since Config80211 is a singleton, it should be safe to delete a static
+  // member.
+  delete event_types_;
+  event_types_ = NULL;
+}
+
+Config80211 *Config80211::GetInstance() {
+  return g_config80211.Pointer();
+}
+
+bool Config80211::Init(EventDispatcher *dispatcher) {
+  if (!sock_) {
+    sock_ = new Nl80211Socket;
+    if (!sock_) {
+      LOG(ERROR) << "No memory";
+      return false;
+    }
+
+    if (!sock_->Init()) {
+      return false;
+    }
+  }
+
+  if (!event_types_) {
+    event_types_ = new std::map<EventType, std::string>;
+    (*event_types_)[Config80211::kEventTypeConfig] = "config";
+    (*event_types_)[Config80211::kEventTypeScan] = "scan";
+    (*event_types_)[Config80211::kEventTypeRegulatory] = "regulatory";
+    (*event_types_)[Config80211::kEventTypeMlme] = "mlme";
+  }
+
+  // Install ourselves in the shill mainloop so we receive messages on the
+  // nl80211 socket.
+  dispatcher_ = dispatcher;
+  if (dispatcher_) {
+    dispatcher_handler_.reset(
+      dispatcher_->CreateReadyHandler(GetFd(),
+                                      IOHandler::kModeInput,
+                                      dispatcher_callback_));
+  }
+  return true;
+}
+
+// static
+bool Config80211::GetEventTypeString(EventType type, string *value) {
+  if (!value) {
+    LOG(ERROR) << "NULL |value|";
+    return false;
+  }
+  if (!event_types_) {
+    LOG(ERROR) << "NULL |event_types_|";
+    return false;
+  }
+
+  map<EventType, string>::iterator match = (*event_types_).find(type);
+  if (match == (*event_types_).end()) {
+    LOG(ERROR) << "Event type " << type << " not found";
+    return false;
+  }
+  *value = match->second;
+  return true;
+}
+
+bool Config80211::SubscribeToEvents(EventType type) {
+  string group_name;
+
+  if (!GetEventTypeString(type, &group_name)) {
+    return false;
+  }
+  if (!sock_->AddGroupMembership(group_name)) {
+    return false;
+  }
+
+  // No sequence checking for multicast messages.
+  if (!sock_->DisableSequenceChecking()) {
+    return false;
+  }
+
+  // Install the global NetLink Callback for messages along with a parameter.
+  // The Netlink Callback's parameter is passed to 'C' as a 'void *'.
+  if (!sock_->SetNetlinkCallback(OnNlMessageReceived,
+                                static_cast<void *>(
+                                    const_cast<Config80211::Callback *>(
+                                        &default_callback_)))) {
+    return false;
+  }
+  return true;
+}
+
+void Config80211::HandleIncomingEvents(int unused_fd) {
+  sock_->GetMessages();
+}
+
+// NOTE: the "struct nl_msg" declaration, below, is a complete fabrication
+// (but one consistent with the nl_socket_modify_cb call to which
+// |OnNlMessageReceived| is a parameter).  |raw_message| is actually a
+// "struct sk_buff" but that data type is only visible in the kernel.  We'll
+// scrub this erroneous datatype with the "nlmsg_hdr" call, below, which
+// extracts an nlmsghdr pointer from |raw_message|.
+int Config80211::OnNlMessageReceived(struct nl_msg *raw_message,
+                                     void *user_callback_object) {
+  SLOG(WiFi, 6) << "\t  Entering " << __func__
+                << "( msg:" << raw_message
+                << ", cb:" << user_callback_object << ")";
+
+  string output("@");
+
+  nlmsghdr *msg = nlmsg_hdr(raw_message);
+
+  scoped_ptr<UserBoundNlMessage> message(
+      UserBoundNlMessageFactory::CreateMessage(msg));
+  if (message == NULL) {
+    output.append("unknown event");
+  } else {
+    if (user_callback_object) {
+      Config80211::Callback *bound_object =
+          static_cast<Config80211::Callback *> (user_callback_object);
+      if (!bound_object->is_null()) {
+        bound_object->Run(*message);
+      }
+    }
+    StringAppendF(&output, "%s", message->ToString().c_str());
+  }
+
+  SLOG(WiFi, 5) << output;
+
+  return NL_SKIP;  // Skip current message, continue parsing buffer.
+}
+
+// Callback80211Object
+
+Callback80211Object::Callback80211Object() :
+    config80211_(NULL),
+    weak_ptr_factory_(this) {
+}
+
+Callback80211Object::~Callback80211Object() {
+  DeinstallAsCallback();
+}
+
+void Callback80211Object::Config80211MessageCallback(
+    const UserBoundNlMessage &msg) {
+  SLOG(WiFi, 2) << "Received " << msg.GetMessageTypeString()
+                << " (" << + msg.GetMessageType() << ")";
+  scoped_ptr<UserBoundNlMessage::AttributeNameIterator> i;
+
+  for (i.reset(msg.GetAttributeNameIterator()); !i->AtEnd(); i->Advance()) {
+    string value = "<unknown>";
+    msg.GetAttributeString(i->GetName(), &value);
+    SLOG(WiFi, 2) << "   Attr:" << msg.StringFromAttributeName(i->GetName())
+                  << "=" << value
+                  << " Type:" << msg.GetAttributeTypeString(i->GetName());
+  }
+}
+
+bool Callback80211Object::InstallAsCallback() {
+  if (config80211_) {
+    Config80211::Callback callback =
+        Bind(&Callback80211Object::Config80211MessageCallback,
+             weak_ptr_factory_.GetWeakPtr());
+    config80211_->SetDefaultCallback(callback);
+    return true;
+  }
+  return false;
+}
+
+bool Callback80211Object::DeinstallAsCallback() {
+  if (config80211_) {
+    config80211_->UnsetDefaultCallback();
+    return true;
+  }
+  return false;
+}
+
+Callback80211Object *Callback80211Object::GetInstance() {
+  return g_callback80211.Pointer();
+}
+
+}  // namespace shill.
diff --git a/config80211.h b/config80211.h
new file mode 100644
index 0000000..ce4d2fa
--- /dev/null
+++ b/config80211.h
@@ -0,0 +1,209 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This library provides an abstracted interface to the cfg80211 kernel module
+// and mac80211 drivers.  These are accessed via a netlink socket using the
+// following software stack:
+//
+//    [shill]
+//       |
+// [nl80211 library]
+//       |
+// [libnl_genl/libnl libraries]
+//       |
+//   (netlink socket)
+//       |
+// [cfg80211 kernel module]
+//       |
+// [mac80211 drivers]
+//
+// Messages go from user-space to kernel-space (i.e., Kernel-Bound) or in the
+// other direction (i.e., User-Bound).
+//
+// For the love of Pete, there are a lot of different types of callbacks,
+// here.  I'll try to differentiate:
+//
+// Config80211 Callback -
+//    This is a base::Callback object installed by the user and called by
+//    Config80211 for each message it receives.  More specifically, when the
+//    user calls Config80211::SubscribeToEvents, Config80211 installs
+//    OnNlMessageReceived as a netlink callback function (described below).
+//    OnNlMessageReceived, in turn, parses the message from cfg80211 and calls
+//    Config80211::Callback with the resultant UserBoundNlMessage.
+//
+// Netlink Callback -
+//    Netlink callbacks are mechanisms installed by the user (well, by
+//    Config80211 -- none of these are intended for use by users of
+//    Config80211) for the libnl layer to communicate back to the user.  Some
+//    callbacks are installed for global use (i.e., the default callback used
+//    for all messages) or as an override for a specific message.  Netlink
+//    callbacks come in three levels.
+//
+//    The lowest level (nl_recvmsg_msg_cb_t) is a function installed by
+//    Config80211.  These are called by libnl when messages are received from
+//    the kernel.
+//
+//    The medium level (nl_cb) is also used by Config80211.  This, the 'netlink
+//    callback structure', encapsualtes a number of netlink callback functions
+//    (nl_recvmsg_msg_cb_t, one each for different types of messages).
+//
+//    The highest level is the NetlinkSocket::Callback object.
+//
+// Dispatcher Callback -
+//    This base::Callback is a private method of Config80211 created and
+//    installed behind the scenes.  This is not the callback you're looking
+//    for; move along.  This is called by shill's EventDispatcher when there's
+//    data waiting for user space code on the netlink socket.  This callback
+//    then calls NetlinkSocket::GetMessages which calls nl_recvmsgs_default
+//    which, in turn, calls the installed netlink callback function.
+
+#ifndef SHILL_CONFIG80211_H_
+#define SHILL_CONFIG80211_H_
+
+#include <iomanip>
+#include <map>
+#include <string>
+
+#include <base/basictypes.h>
+#include <base/bind.h>
+#include <base/lazy_instance.h>
+
+#include "shill/event_dispatcher.h"
+#include "shill/io_handler.h"
+#include "shill/nl80211_socket.h"
+
+namespace shill {
+
+class KernelBoundNlMessage;
+class UserBoundNlMessage;
+
+// Provides a transport-independent ability to receive status from the wifi
+// configuration.  In its current implementation, it uses the netlink socket
+// interface to interface with the wifi system.
+//
+// Config80211 is a singleton and, as such, coordinates access to libnl.
+class Config80211 {
+ public:
+  typedef base::Callback<void(const UserBoundNlMessage &)> Callback;
+
+  // The different kinds of events to which we can subscribe (and receive)
+  // from cfg80211.
+  enum EventType {
+    kEventTypeConfig,
+    kEventTypeScan,
+    kEventTypeRegulatory,
+    kEventTypeMlme,
+    kEventTypeCount
+  };
+
+  virtual ~Config80211();
+
+  // This is a singleton -- use Config80211::GetInstance()->Foo()
+  static Config80211 *GetInstance();
+
+  // Performs non-trivial object initialization of the Config80211 singleton.
+  bool Init(EventDispatcher *dispatcher);
+
+  // Returns the file descriptor of socket used to read wifi data.
+  int GetFd() const { return (sock_ ? sock_->GetFd() : -1); }
+
+  // Install default Config80211 Callback.  The callback is a user-supplied
+  // object to be called by the system for user-bound messages that do not
+  // have a corresponding messaage-specific callback.  |SetDefaultCallback|
+  // should be called before |SubscribeToEvents| since the result of this call
+  // are used for that call.
+  void SetDefaultCallback(const Callback &callback) {
+    default_callback_ = callback; }
+
+  // Uninstall default Config80211 Callback.
+  void UnsetDefaultCallback() { default_callback_.Reset(); }
+
+  // TODO(wdg): Add 'SendMessage(KernelBoundNlMessage *message,
+  //                             Config80211::Callback *callback);
+  // Config80211 needs to handle out-of-order responses using a
+  // map <sequence_number, callback> to match callback with message.
+
+  // Return a string corresponding to the passed-in EventType.
+  static bool GetEventTypeString(EventType type, std::string *value);
+
+  // Sign-up to receive and log multicast events of a specific type.
+  bool SubscribeToEvents(EventType type);
+
+ protected:
+  friend struct base::DefaultLazyInstanceTraits<Config80211>;
+
+  explicit Config80211();
+
+ private:
+  friend class Config80211Test;
+
+  // EventDispatcher calls this when data is available on our socket.  This
+  // callback reads data from the driver, parses that data, and logs it.
+  void HandleIncomingEvents(int fd);
+
+  // This is a Netlink Callback.  libnl-80211 calls this method when it
+  // receives data from cfg80211.  This method parses those messages and logs
+  // them.
+  static int OnNlMessageReceived(struct nl_msg *msg, void *arg);
+
+  // Config80211 Callback, OnNlMessageReceived invokes this User-supplied
+  // callback object when _it_ gets called to read libnl data.
+  Callback default_callback_;
+
+  // TODO(wdg): implement the following.
+  // std::map<uint32_t, Callback> message_callback_;
+
+  static std::map<EventType, std::string> *event_types_;
+
+  // Hooks needed to be called by shill's EventDispatcher.
+  EventDispatcher *dispatcher_;
+  base::WeakPtrFactory<Config80211> weak_ptr_factory_;
+  base::Callback<void(int)> dispatcher_callback_;
+  scoped_ptr<IOHandler> dispatcher_handler_;
+
+  Nl80211Socket *sock_;
+
+  DISALLOW_COPY_AND_ASSIGN(Config80211);
+};
+
+
+// Example Config80211 callback object; the callback prints a description of
+// each message with its attributes.  You want to make it a singleton so that
+// its life isn't dependent on any other object (plus, since this handles
+// global events from msg80211, you only want/need one).
+class Callback80211Object {
+ public:
+  Callback80211Object();
+  virtual ~Callback80211Object();
+
+  // Get a pointer to the singleton Callback80211Object.
+  static Callback80211Object *GetInstance();
+
+  // Install ourselves as a callback.  Done automatically by constructor.
+  bool InstallAsCallback();
+
+  // Deinstall ourselves as a callback.  Done automatically by destructor.
+  bool DeinstallAsCallback();
+
+  // Simple accessor.
+  void set_config80211(Config80211 *config80211) { config80211_ = config80211; }
+
+ protected:
+  friend struct base::DefaultLazyInstanceTraits<Callback80211Object>;
+
+ private:
+  // When installed, this is the method Config80211 will call when it gets a
+  // message from the mac80211 drivers.
+  void Config80211MessageCallback(const UserBoundNlMessage &msg);
+
+  Config80211 *config80211_;
+
+  // Config80211MessageCallback method bound to this object to install as a
+  // callback.
+  base::WeakPtrFactory<Callback80211Object> weak_ptr_factory_;
+};
+
+}  // namespace shill
+
+#endif  // SHILL_CONFIG80211_H_
diff --git a/config80211_unittest.cc b/config80211_unittest.cc
new file mode 100644
index 0000000..39922e0
--- /dev/null
+++ b/config80211_unittest.cc
@@ -0,0 +1,799 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file provides tests for individual messages.  It tests
+// UserBoundNlMessageFactory's ability to create specific message types and it
+// tests the various UserBoundNlMessage types' ability to parse those
+// messages.
+
+// This file tests the public interface to Config80211.
+
+#include "shill/config80211.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <netlink/attr.h>
+#include <netlink/netlink.h>
+
+#include <string>
+#include <vector>
+
+#include <base/bind.h>
+
+#include "shill/mock_nl80211_socket.h"
+#include "shill/nl80211_socket.h"
+#include "shill/user_bound_nlmessage.h"
+
+using base::Bind;
+using base::Unretained;
+using std::string;
+using std::vector;
+using testing::_;
+using testing::Return;
+using testing::Test;
+
+namespace shill {
+
+namespace {
+
+// These data blocks have been collected by shill using Config80211 while,
+// simultaneously (and manually) comparing shill output with that of the 'iw'
+// code from which it was derived.  The test strings represent the raw packet
+// data coming from the kernel.  The comments above each of these strings is
+// the markup that "iw" outputs for ech of these packets.
+
+// These constants are consistent throughout the packets, below.
+
+const uint32_t kExpectedIfIndex = 4;
+const uint8_t kExpectedWifi = 0;
+const char kExpectedMacAddress[] = "c0:3f:0e:77:e8:7f";
+
+
+// wlan0 (phy #0): scan started
+
+const uint32_t kScanFrequencyTrigger[] = {
+  2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447,
+  2452, 2457, 2462, 2467, 2472, 2484, 5180, 5200,
+  5220, 5240, 5260, 5280, 5300, 5320, 5500, 5520,
+  5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680,
+  5700, 5745, 5765, 5785, 5805, 5825
+};
+
+const unsigned char kNL80211_CMD_TRIGGER_SCAN[] = {
+  0x68, 0x01, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x21, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x2d, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x34, 0x01, 0x2c, 0x00,
+  0x08, 0x00, 0x00, 0x00, 0x6c, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x01, 0x00, 0x71, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x02, 0x00, 0x76, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x03, 0x00, 0x7b, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x04, 0x00, 0x80, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x05, 0x00, 0x85, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x06, 0x00, 0x8a, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x07, 0x00, 0x8f, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x08, 0x00, 0x94, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x09, 0x00, 0x99, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0a, 0x00, 0x9e, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0b, 0x00, 0xa3, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0c, 0x00, 0xa8, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0d, 0x00, 0xb4, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0e, 0x00, 0x3c, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x0f, 0x00, 0x50, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x10, 0x00, 0x64, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x11, 0x00, 0x78, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x12, 0x00, 0x8c, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x13, 0x00, 0xa0, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x14, 0x00, 0xb4, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x15, 0x00, 0xc8, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x16, 0x00, 0x7c, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x17, 0x00, 0x90, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x18, 0x00, 0xa4, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x19, 0x00, 0xb8, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1a, 0x00, 0xcc, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1b, 0x00, 0xe0, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1c, 0x00, 0xf4, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1d, 0x00, 0x08, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x1e, 0x00, 0x1c, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x1f, 0x00, 0x30, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x20, 0x00, 0x44, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x21, 0x00, 0x71, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x22, 0x00, 0x85, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x23, 0x00, 0x99, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x24, 0x00, 0xad, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x25, 0x00, 0xc1, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+
+
+// wlan0 (phy #0): scan finished: 2412 2417 2422 2427 2432 2437 2442 2447 2452
+// 2457 2462 2467 2472 2484 5180 5200 5220 5240 5260 5280 5300 5320 5500 5520
+// 5540 5560 5580 5600 5620 5640 5660 5680 5700 5745 5765 5785 5805 5825, ""
+
+const uint32_t kScanFrequencyResults[] = {
+  2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447,
+  2452, 2457, 2462, 2467, 2472, 2484, 5180, 5200,
+  5220, 5240, 5260, 5280, 5300, 5320, 5500, 5520,
+  5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680,
+  5700, 5745, 5765, 5785, 5805, 5825
+};
+
+const unsigned char kNL80211_CMD_NEW_SCAN_RESULTS[] = {
+  0x68, 0x01, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x22, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x2d, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x34, 0x01, 0x2c, 0x00,
+  0x08, 0x00, 0x00, 0x00, 0x6c, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x01, 0x00, 0x71, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x02, 0x00, 0x76, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x03, 0x00, 0x7b, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x04, 0x00, 0x80, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x05, 0x00, 0x85, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x06, 0x00, 0x8a, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x07, 0x00, 0x8f, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x08, 0x00, 0x94, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x09, 0x00, 0x99, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0a, 0x00, 0x9e, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0b, 0x00, 0xa3, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0c, 0x00, 0xa8, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0d, 0x00, 0xb4, 0x09, 0x00, 0x00,
+  0x08, 0x00, 0x0e, 0x00, 0x3c, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x0f, 0x00, 0x50, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x10, 0x00, 0x64, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x11, 0x00, 0x78, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x12, 0x00, 0x8c, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x13, 0x00, 0xa0, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x14, 0x00, 0xb4, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x15, 0x00, 0xc8, 0x14, 0x00, 0x00,
+  0x08, 0x00, 0x16, 0x00, 0x7c, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x17, 0x00, 0x90, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x18, 0x00, 0xa4, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x19, 0x00, 0xb8, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1a, 0x00, 0xcc, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1b, 0x00, 0xe0, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1c, 0x00, 0xf4, 0x15, 0x00, 0x00,
+  0x08, 0x00, 0x1d, 0x00, 0x08, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x1e, 0x00, 0x1c, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x1f, 0x00, 0x30, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x20, 0x00, 0x44, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x21, 0x00, 0x71, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x22, 0x00, 0x85, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x23, 0x00, 0x99, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x24, 0x00, 0xad, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x25, 0x00, 0xc1, 0x16, 0x00, 0x00,
+  0x08, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+
+
+// wlan0: new station c0:3f:0e:77:e8:7f
+
+const uint32_t kNewStationExpectedGeneration = 275;
+
+const unsigned char kNL80211_CMD_NEW_STATION[] = {
+  0x34, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x13, 0x01, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x06, 0x00,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x00, 0x00,
+  0x08, 0x00, 0x2e, 0x00, 0x13, 0x01, 0x00, 0x00,
+  0x04, 0x00, 0x15, 0x00,
+};
+
+
+// wlan0 (phy #0): auth c0:3f:0e:77:e8:7f -> 48:5d:60:77:2d:cf status: 0:
+// Successful [frame: b0 00 3a 01 48 5d 60 77 2d cf c0 3f 0e 77 e8 7f c0
+// 3f 0e 77 e8 7f 30 07 00 00 02 00 00 00]
+
+const unsigned char kAuthenticateFrame[] = {
+  0xb0, 0x00, 0x3a, 0x01, 0x48, 0x5d, 0x60, 0x77,
+  0x2d, 0xcf, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x30, 0x07,
+  0x00, 0x00, 0x02, 0x00, 0x00, 0x00
+};
+
+const unsigned char kNL80211_CMD_AUTHENTICATE[] = {
+  0x48, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x25, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x22, 0x00, 0x33, 0x00,
+  0xb0, 0x00, 0x3a, 0x01, 0x48, 0x5d, 0x60, 0x77,
+  0x2d, 0xcf, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x30, 0x07,
+  0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
+};
+
+
+// wlan0 (phy #0): assoc c0:3f:0e:77:e8:7f -> 48:5d:60:77:2d:cf status: 0:
+// Successful [frame: 10 00 3a 01 48 5d 60 77 2d cf c0 3f 0e 77 e8 7f c0 3f 0e
+// 77 e8 7f 40 07 01 04 00 00 01 c0 01 08 82 84 8b 96 0c 12 18 24 32 04 30 48
+// 60 6c]
+
+const unsigned char kAssociateFrame[] = {
+  0x10, 0x00, 0x3a, 0x01, 0x48, 0x5d, 0x60, 0x77,
+  0x2d, 0xcf, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x40, 0x07,
+  0x01, 0x04, 0x00, 0x00, 0x01, 0xc0, 0x01, 0x08,
+  0x82, 0x84, 0x8b, 0x96, 0x0c, 0x12, 0x18, 0x24,
+  0x32, 0x04, 0x30, 0x48, 0x60, 0x6c
+};
+
+const unsigned char kNL80211_CMD_ASSOCIATE[] = {
+  0x58, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x26, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x32, 0x00, 0x33, 0x00,
+  0x10, 0x00, 0x3a, 0x01, 0x48, 0x5d, 0x60, 0x77,
+  0x2d, 0xcf, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x40, 0x07,
+  0x01, 0x04, 0x00, 0x00, 0x01, 0xc0, 0x01, 0x08,
+  0x82, 0x84, 0x8b, 0x96, 0x0c, 0x12, 0x18, 0x24,
+  0x32, 0x04, 0x30, 0x48, 0x60, 0x6c, 0x00, 0x00,
+};
+
+
+// wlan0 (phy #0): connected to c0:3f:0e:77:e8:7f
+
+const uint16_t kExpectedConnectStatus = 0;
+
+const unsigned char kNL80211_CMD_CONNECT[] = {
+  0x4c, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x2e, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x06, 0x00,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x00, 0x00,
+  0x06, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x14, 0x00, 0x4e, 0x00, 0x01, 0x08, 0x82, 0x84,
+  0x8b, 0x96, 0x0c, 0x12, 0x18, 0x24, 0x32, 0x04,
+  0x30, 0x48, 0x60, 0x6c,
+};
+
+
+// wlan0 (phy #0): deauth c0:3f:0e:77:e8:7f -> ff:ff:ff:ff:ff:ff reason 2:
+// Previous authentication no longer valid [frame: c0 00 00 00 ff ff ff ff
+// ff ff c0 3f 0e 77 e8 7f c0 3f 0e 77 e8 7f c0 0e 02 00]
+
+const unsigned char kDeauthenticateFrame[] = {
+ 0xc0, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+ 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0xc0, 0x0e,
+ 0x02, 0x00
+};
+
+const unsigned char kNL80211_CMD_DEAUTHENTICATE[] = {
+  0x44, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x27, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x33, 0x00,
+  0xc0, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
+  0xff, 0xff, 0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0xc0, 0x0e,
+  0x02, 0x00, 0x00, 0x00,
+};
+
+
+// wlan0 (phy #0): disconnected (by AP) reason: 2: Previous authentication no
+// longer valid
+
+const uint16_t kExpectedDisconnectReason = 2;
+
+const unsigned char kNL80211_CMD_DISCONNECT[] = {
+  0x30, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x30, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x06, 0x00, 0x36, 0x00,
+  0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x47, 0x00,
+};
+
+
+// wlan0 (phy #0): connection quality monitor event: peer c0:3f:0e:77:e8:7f
+// didn't ACK 50 packets
+
+const uint32_t kExpectedCqmNotAcked = 50;
+
+const unsigned char kNL80211_CMD_NOTIFY_CQM[] = {
+  0x3c, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x40, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x06, 0x00,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x00, 0x00,
+  0x0c, 0x00, 0x5e, 0x00, 0x08, 0x00, 0x04, 0x00,
+  0x32, 0x00, 0x00, 0x00,
+};
+
+
+// wlan0 (phy #0): disassoc 48:5d:60:77:2d:cf -> c0:3f:0e:77:e8:7f reason 3:
+// Deauthenticated because sending station is  [frame: a0 00 00 00 c0 3f 0e
+// 77 e8 7f 48 5d 60 77 2d cf c0 3f 0e 77 e8 7f 00 00 03 00]
+
+const unsigned char kDisassociateFrame[] = {
+  0xa0, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x0e, 0x77,
+  0xe8, 0x7f, 0x48, 0x5d, 0x60, 0x77, 0x2d, 0xcf,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x00, 0x00,
+  0x03, 0x00
+};
+
+const unsigned char kNL80211_CMD_DISASSOCIATE[] = {
+  0x44, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x28, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
+  0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x33, 0x00,
+  0xa0, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x0e, 0x77,
+  0xe8, 0x7f, 0x48, 0x5d, 0x60, 0x77, 0x2d, 0xcf,
+  0xc0, 0x3f, 0x0e, 0x77, 0xe8, 0x7f, 0x00, 0x00,
+  0x03, 0x00, 0x00, 0x00,
+};
+
+}  // namespace {}
+
+class Config80211Test : public Test {
+ public:
+  Config80211Test() : config80211_(Config80211::GetInstance()) {}
+  void SetupConfig80211Object() {
+    EXPECT_NE(config80211_, reinterpret_cast<Config80211 *>(NULL));
+    config80211_->sock_ = &socket_;
+    EXPECT_TRUE(config80211_->Init(reinterpret_cast<EventDispatcher *>(NULL)));
+  }
+
+  Config80211 *config80211_;
+  MockNl80211Socket socket_;
+};
+
+class TestCallbackObject {
+ public:
+  TestCallbackObject() : callback_(Bind(&TestCallbackObject::MessageHandler,
+                                        Unretained(this))) { }
+  void MessageHandler(const UserBoundNlMessage &msg) {
+  }
+  const Config80211::Callback &GetCallback() const { return callback_; }
+
+ private:
+  Config80211::Callback callback_;
+};
+
+MATCHER_P(IsEqualToCallback, callback, "") {
+  const Config80211::Callback *arg_cb =
+      reinterpret_cast<const Config80211::Callback *>(arg);
+  const Config80211::Callback *callback_cb =
+      reinterpret_cast<const Config80211::Callback *>(callback);
+  if (arg_cb == callback_cb)
+    return true;
+  if (arg_cb == reinterpret_cast<const Config80211::Callback *>(NULL))
+    return false;
+  if (callback_cb == reinterpret_cast<const Config80211::Callback *>(NULL))
+    return arg_cb->is_null();
+  return arg_cb->Equals(*callback_cb);
+}
+
+TEST_F(Config80211Test, AddLinkTest) {
+  SetupConfig80211Object();
+
+  // Create a default callback.
+  TestCallbackObject callback_object;
+
+  // Install the callback and subscribe to events using it.
+  config80211_->SetDefaultCallback(callback_object.GetCallback());
+  Config80211::EventType event_type = Config80211::kEventTypeScan;
+  string event_type_string;
+  EXPECT_TRUE(Config80211::GetEventTypeString(event_type, &event_type_string));
+  EXPECT_CALL(socket_, AddGroupMembership(event_type_string))
+      .WillOnce(Return(true));
+  EXPECT_CALL(socket_, DisableSequenceChecking())
+      .WillOnce(Return(true));
+  EXPECT_CALL(socket_, SetNetlinkCallback(
+      _, IsEqualToCallback(&callback_object.GetCallback())))
+      .WillOnce(Return(true));
+
+  EXPECT_TRUE(config80211_->SubscribeToEvents(event_type));
+
+  // Deinstall the callback.
+  config80211_->UnsetDefaultCallback();
+  EXPECT_TRUE(Config80211::GetEventTypeString(event_type, &event_type_string));
+  EXPECT_CALL(socket_, AddGroupMembership(event_type_string))
+      .WillOnce(Return(true));
+  EXPECT_CALL(socket_, DisableSequenceChecking()).WillOnce(Return(true));
+  EXPECT_CALL(socket_, SetNetlinkCallback(_,
+                                          IsEqualToCallback(NULL)
+                                          )).WillOnce(Return(true));
+  EXPECT_TRUE(config80211_->SubscribeToEvents(event_type));
+}
+
+TEST_F(Config80211Test, NL80211_CMD_TRIGGER_SCAN) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_TRIGGER_SCAN)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_TRIGGER_SCAN);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  // Make sure the scan frequencies in the attribute are the ones we expect.
+  {
+    vector<uint32_t>list;
+    EXPECT_TRUE(message->GetScanFrequenciesAttribute(
+        NL80211_ATTR_SCAN_FREQUENCIES, &list));
+    EXPECT_EQ(arraysize(kScanFrequencyTrigger), list.size());
+    int i = 0;
+    vector<uint32_t>::const_iterator j = list.begin();
+    while (j != list.end()) {
+      EXPECT_EQ(kScanFrequencyTrigger[i], *j);
+      ++i;
+      ++j;
+    }
+  }
+
+  {
+    vector<string> ssids;
+    EXPECT_TRUE(message->GetScanSsidsAttribute(NL80211_ATTR_SCAN_SSIDS,
+                                               &ssids));
+    EXPECT_EQ(ssids.size(), 1);
+    EXPECT_EQ(ssids[0].compare(""), 0);  // Expect a single, empty SSID.
+  }
+
+  // Significant only in its existence.
+  EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_SUPPORT_MESH_AUTH));
+}
+
+TEST_F(Config80211Test, NL80211_CMD_NEW_SCAN_RESULTS) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_NEW_SCAN_RESULTS)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_NEW_SCAN_RESULTS);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  // Make sure the scan frequencies in the attribute are the ones we expect.
+  {
+    vector<uint32_t>list;
+    EXPECT_TRUE(message->GetScanFrequenciesAttribute(
+        NL80211_ATTR_SCAN_FREQUENCIES, &list));
+    EXPECT_EQ(arraysize(kScanFrequencyResults), list.size());
+    int i = 0;
+    vector<uint32_t>::const_iterator j = list.begin();
+    while (j != list.end()) {
+      EXPECT_EQ(kScanFrequencyResults[i], *j);
+      ++i;
+      ++j;
+    }
+  }
+
+  {
+    vector<string> ssids;
+    EXPECT_TRUE(message->GetScanSsidsAttribute(NL80211_ATTR_SCAN_SSIDS,
+                                               &ssids));
+    EXPECT_EQ(ssids.size(), 1);
+    EXPECT_EQ(ssids[0].compare(""), 0);  // Expect a single, empty SSID.
+  }
+
+  // Significant only in its existence.
+  EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_SUPPORT_MESH_AUTH));
+}
+
+TEST_F(Config80211Test, NL80211_CMD_NEW_STATION) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_NEW_STATION)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_NEW_STATION);
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    string value;
+    EXPECT_TRUE(message->GetMacAttributeString(NL80211_ATTR_MAC, &value));
+    EXPECT_EQ(strncmp(value.c_str(), kExpectedMacAddress, value.length()), 0);
+  }
+
+  // TODO(wdg): Make config80211 handle nested attributes so it can deal
+  // with things like NL80211_ATTR_STA_INFO (without just calling
+  // nla_parse_nested).
+  EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_STA_INFO));
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_GENERATION, &value));
+    EXPECT_EQ(value, kNewStationExpectedGeneration);
+  }
+}
+
+TEST_F(Config80211Test, NL80211_CMD_AUTHENTICATE) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_AUTHENTICATE)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_AUTHENTICATE);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    void *rawdata = NULL;
+    int frame_byte_count = 0;
+    EXPECT_TRUE(message->GetRawAttributeData(NL80211_ATTR_FRAME, &rawdata,
+                                             &frame_byte_count));
+    EXPECT_NE(rawdata, reinterpret_cast<void *>(NULL));
+    const uint8_t *frame_data = reinterpret_cast<const uint8_t *>(rawdata);
+
+    Nl80211Frame frame(frame_data, frame_byte_count);
+    Nl80211Frame expected_frame(kAuthenticateFrame, sizeof(kAuthenticateFrame));
+
+    EXPECT_TRUE(frame.IsEqual(expected_frame));
+  }
+}
+
+TEST_F(Config80211Test, NL80211_CMD_ASSOCIATE) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_ASSOCIATE)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_ASSOCIATE);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    void *rawdata = NULL;
+    int frame_byte_count = 0;
+    EXPECT_TRUE(message->GetRawAttributeData(NL80211_ATTR_FRAME, &rawdata,
+                                             &frame_byte_count));
+    EXPECT_NE(rawdata, reinterpret_cast<void *>(NULL));
+    const uint8_t *frame_data = reinterpret_cast<const uint8_t *>(rawdata);
+
+    Nl80211Frame frame(frame_data, frame_byte_count);
+    Nl80211Frame expected_frame(kAssociateFrame, sizeof(kAssociateFrame));
+
+    EXPECT_TRUE(frame.IsEqual(expected_frame));
+  }
+}
+
+TEST_F(Config80211Test, NL80211_CMD_CONNECT) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_CONNECT)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_CONNECT);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    string value;
+    EXPECT_TRUE(message->GetMacAttributeString(NL80211_ATTR_MAC, &value));
+    EXPECT_EQ(strncmp(value.c_str(), kExpectedMacAddress, value.length()), 0);
+  }
+
+  {
+    uint16_t value;
+    EXPECT_TRUE(message->GetU16Attribute(NL80211_ATTR_STATUS_CODE, &value));
+    EXPECT_EQ(value, kExpectedConnectStatus);
+  }
+
+  // TODO(wdg): Need to check the value of this attribute.
+  EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_RESP_IE));
+}
+
+TEST_F(Config80211Test, NL80211_CMD_DEAUTHENTICATE) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_DEAUTHENTICATE)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_DEAUTHENTICATE);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    void *rawdata = NULL;
+    int frame_byte_count = 0;
+    EXPECT_TRUE(message->GetRawAttributeData(NL80211_ATTR_FRAME, &rawdata,
+                                             &frame_byte_count));
+    EXPECT_NE(rawdata, reinterpret_cast<void *>(NULL));
+    const uint8_t *frame_data = reinterpret_cast<const uint8_t *>(rawdata);
+
+    Nl80211Frame frame(frame_data, frame_byte_count);
+    Nl80211Frame expected_frame(kDeauthenticateFrame,
+                                sizeof(kDeauthenticateFrame));
+
+    EXPECT_TRUE(frame.IsEqual(expected_frame));
+  }
+}
+
+TEST_F(Config80211Test, NL80211_CMD_DISCONNECT) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_DISCONNECT)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_DISCONNECT);
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    uint16_t value;
+    EXPECT_TRUE(message->GetU16Attribute(NL80211_ATTR_REASON_CODE, &value));
+    EXPECT_EQ(value, kExpectedDisconnectReason);
+  }
+
+  // Significant only in its existence.
+  EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_DISCONNECTED_BY_AP));
+}
+
+TEST_F(Config80211Test, NL80211_CMD_NOTIFY_CQM) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_NOTIFY_CQM)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_NOTIFY_CQM);
+
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    string value;
+    EXPECT_TRUE(message->GetMacAttributeString(NL80211_ATTR_MAC, &value));
+    EXPECT_EQ(strncmp(value.c_str(), kExpectedMacAddress, value.length()), 0);
+  }
+
+  // TODO(wdg): Make config80211 handle nested attributes so it can deal
+  // with things like NL80211_ATTR_CQM (without just calling nla_parse_nested).
+  {
+    static const nla_policy kCqmPolicy[NL80211_ATTR_CQM_MAX + 1] = {
+      { NLA_U32, 0, 0 },  // Who Knows?
+      { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_THOLD]
+      { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_HYST]
+      { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]
+    };
+
+    EXPECT_TRUE(message->AttributeExists(NL80211_ATTR_CQM));
+    const nlattr *const_data = message->GetAttribute(NL80211_ATTR_CQM);
+    nlattr *cqm_attr = const_cast<nlattr *>(const_data);
+    EXPECT_NE(cqm_attr, reinterpret_cast<nlattr *>(NULL));
+
+    nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
+    EXPECT_EQ(nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, cqm_attr,
+                     const_cast<nla_policy *>(kCqmPolicy)), 0);
+
+    EXPECT_FALSE(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
+    EXPECT_TRUE(cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]);
+    EXPECT_EQ(nla_get_u32(cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]),
+              kExpectedCqmNotAcked);
+  }
+}
+
+TEST_F(Config80211Test, NL80211_CMD_DISASSOCIATE) {
+  UserBoundNlMessage *message = UserBoundNlMessageFactory::CreateMessage(
+      const_cast<nlmsghdr *>(
+        reinterpret_cast<const nlmsghdr *>(kNL80211_CMD_DISASSOCIATE)));
+
+  EXPECT_NE(message, reinterpret_cast<UserBoundNlMessage *>(NULL));
+  EXPECT_EQ(message->GetMessageType(), NL80211_CMD_DISASSOCIATE);
+
+
+  {
+    uint8_t value;
+    EXPECT_TRUE(message->GetU8Attribute(NL80211_ATTR_WIPHY, &value));
+    EXPECT_EQ(value, kExpectedWifi);
+  }
+
+  {
+    uint32_t value;
+    EXPECT_TRUE(message->GetU32Attribute(NL80211_ATTR_IFINDEX, &value));
+    EXPECT_EQ(value, kExpectedIfIndex);
+  }
+
+  {
+    void *rawdata = NULL;
+    int frame_byte_count = 0;
+    EXPECT_TRUE(message->GetRawAttributeData(NL80211_ATTR_FRAME, &rawdata,
+                                             &frame_byte_count));
+    EXPECT_NE(rawdata, reinterpret_cast<void *>(NULL));
+    const uint8_t *frame_data = reinterpret_cast<const uint8_t *>(rawdata);
+
+    Nl80211Frame frame(frame_data, frame_byte_count);
+    Nl80211Frame expected_frame(kDisassociateFrame, sizeof(kDisassociateFrame));
+
+    EXPECT_TRUE(frame.IsEqual(expected_frame));
+  }
+}
+
+}  // namespace shill
diff --git a/ieee80211.h b/ieee80211.h
index fd0fe26..83f53b2 100644
--- a/ieee80211.h
+++ b/ieee80211.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
@@ -32,8 +32,36 @@
 const uint16_t kWPSElementModelName = 0x1023;
 const uint16_t kWPSElementModelNumber = 0x1024;
 const uint16_t kWPSElementDeviceName = 0x1011;
+
+// This structure is incomplete.  Fields will be added as necessary.
+//
+// NOTE: the uint16_t stuff is in little-endian format so conversions are
+// required.
+struct ieee80211_frame {
+  uint16_t frame_control;
+  uint16_t duration_usec;
+  uint8_t destination_mac[6];
+  uint8_t source_mac[6];
+  uint8_t address[6];
+  uint16_t sequence_control;
+  union {
+    struct {
+      uint16_t reserved_1;
+      uint16_t reserved_2;
+      uint16_t status_code;
+    } authentiate_message;
+    struct {
+      uint16_t reason_code;
+    } deauthentiate_message;
+    struct {
+      uint16_t reserved_1;
+      uint16_t status_code;
+    } associate_response;
+  } u;
 };
 
+}
+
 }  // namespace shill
 
 #endif  // SHILL_IEEE_80211_H
diff --git a/kernel_bound_nlmessage.cc b/kernel_bound_nlmessage.cc
new file mode 100644
index 0000000..9b35ff3
--- /dev/null
+++ b/kernel_bound_nlmessage.cc
@@ -0,0 +1,124 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "shill/kernel_bound_nlmessage.h"
+
+#include <net/if.h>
+#include <netlink/genl/genl.h>
+#include <netlink/msg.h>
+#include <netlink/netlink.h>
+
+#include <base/logging.h>
+
+#include "shill/logging.h"
+#include "shill/netlink_socket.h"
+#include "shill/scope_logger.h"
+
+namespace shill {
+
+const uint32_t KernelBoundNlMessage::kIllegalMessage = 0xFFFFFFFF;
+
+KernelBoundNlMessage::~KernelBoundNlMessage() {
+  if (message_) {
+    nlmsg_free(message_);
+    message_ = NULL;
+  }
+}
+
+bool KernelBoundNlMessage::Init() {
+  message_ = nlmsg_alloc();
+
+  if (!message_) {
+    LOG(ERROR) << "Couldn't allocate |message_|";
+    return false;
+  }
+
+  return true;
+}
+
+uint32_t KernelBoundNlMessage::GetId() const {
+  if (!message_) {
+    LOG(ERROR) << "NULL |message_|";
+    return kIllegalMessage;
+  }
+  struct nlmsghdr *header = nlmsg_hdr(message_);
+  if (!header) {
+    LOG(ERROR) << "Couldn't make header";
+    return kIllegalMessage;
+  }
+  return header->nlmsg_seq;
+}
+
+bool KernelBoundNlMessage::AddNetlinkHeader(uint32_t port, uint32_t seq,
+                                            int family_id, int hdrlen,
+                                            int flags, uint8_t cmd,
+                                            uint8_t version) {
+  if (!message_) {
+    LOG(ERROR) << "NULL |message_|";
+    return false;
+  }
+
+  // Parameters to genlmsg_put:
+  //  @message: struct nl_msg *message_.
+  //  @pid: netlink pid the message is addressed to.
+  //  @seq: sequence number (usually the one of the sender).
+  //  @family: generic netlink family.
+  //  @flags netlink message flags.
+  //  @cmd: netlink command.
+  //  @version: version of communication protocol.
+  // genlmsg_put returns a void * pointing to the header but we don't want to
+  // encourage its use outside of this object.
+
+  if (genlmsg_put(message_, port, seq, family_id, hdrlen, flags, cmd, version)
+      == NULL) {
+    LOG(ERROR) << "genlmsg_put returned a NULL pointer.";
+    return false;
+  }
+
+  return true;
+}
+
+int KernelBoundNlMessage::AddAttribute(int attrtype, int attrlen,
+                                       const void *data) {
+  if (!data) {
+    LOG(ERROR) << "NULL |data| parameter";
+    return -1;
+  }
+  if (!message_) {
+    LOG(ERROR) << "NULL |message_|.";
+    return -1;
+  }
+  return nla_put(message_, attrtype, attrlen, data);
+}
+
+bool KernelBoundNlMessage::Send(NetlinkSocket *socket) {
+  if (!socket) {
+    LOG(ERROR) << "NULL |socket| parameter";
+    return false;
+  }
+  if (!message_) {
+    LOG(ERROR) << "NULL |message_|.";
+    return -1;
+  }
+
+  // Manually set the sequence number -- seems to work.
+  struct nlmsghdr *header = nlmsg_hdr(message_);
+  if (header != 0) {
+    header->nlmsg_seq = socket->GetSequenceNumber();
+  }
+
+  // Complete AND SEND a message.
+  int result = nl_send_auto_complete(
+      const_cast<struct nl_sock *>(socket->GetConstNlSock()), message_);
+
+  SLOG(WiFi, 6) << "NL Message " << GetId() << " ===>";
+
+  if (result < 0) {
+    LOG(ERROR) << "Failed call to 'nl_send_auto_complete': " << result;
+    return false;
+  }
+  return true;
+}
+
+}  // namespace shill.
diff --git a/kernel_bound_nlmessage.h b/kernel_bound_nlmessage.h
new file mode 100644
index 0000000..b303f51
--- /dev/null
+++ b/kernel_bound_nlmessage.h
@@ -0,0 +1,73 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#ifndef SHILL_KERNEL_BOUND_NLMESSAGE_H_
+#define SHILL_KERNEL_BOUND_NLMESSAGE_H_
+
+#include "shill/kernel_bound_nlmessage.h"
+
+#include <base/basictypes.h>
+#include <base/bind.h>
+
+struct nl_msg;
+
+namespace shill {
+struct NetlinkSocket;
+
+// TODO(wdg): eventually, KernelBoundNlMessage and UserBoundNlMessage should
+// be combined into a monolithic NlMessage.
+//
+// Provides a wrapper around a netlink message destined for kernel-space.
+class KernelBoundNlMessage {
+ public:
+  KernelBoundNlMessage() : message_(NULL) {}
+  virtual ~KernelBoundNlMessage();
+
+  // Non-trivial initialization.
+  bool Init();
+
+  // Message ID is equivalent to the message's sequence number.
+  uint32_t GetId() const;
+
+  // Add a netlink header to the message.
+  bool AddNetlinkHeader(uint32_t port, uint32_t seq, int family_id, int hdrlen,
+                        int flags, uint8_t cmd, uint8_t version);
+
+  // Add a netlink attribute to the message.
+  int AddAttribute(int attrtype, int attrlen, const void *data);
+
+  // Sends |this| over the netlink socket.
+  virtual bool Send(NetlinkSocket *socket);
+
+ private:
+  static const uint32_t kIllegalMessage;
+
+  struct nl_msg *message_;
+
+  DISALLOW_COPY_AND_ASSIGN(KernelBoundNlMessage);
+};
+
+}  // namespace shill
+
+#endif  // SHILL_KERNEL_BOUND_NLMESSAGE_H_
diff --git a/mock_nl80211_socket.h b/mock_nl80211_socket.h
new file mode 100644
index 0000000..1da26d1
--- /dev/null
+++ b/mock_nl80211_socket.h
@@ -0,0 +1,38 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef SHILL_MOCK_NL80211_SOCKET_
+#define SHILL_MOCK_NL80211_SOCKET_
+
+#include <gmock/gmock.h>
+
+#include <netlink/attr.h>
+#include <netlink/netlink.h>
+
+#include <string>
+
+#include "shill/nl80211_socket.h"
+
+
+namespace shill {
+
+class MockNl80211Socket : public Nl80211Socket {
+ public:
+  MockNl80211Socket() {}
+  MOCK_METHOD0(Init, bool());
+  MOCK_METHOD1(AddGroupMembership, bool(const std::string &group_name));
+  using Nl80211Socket::DisableSequenceChecking;
+  MOCK_METHOD0(DisableSequenceChecking, bool());
+  using Nl80211Socket::GetMessages;
+  MOCK_METHOD0(GetMessages, bool());
+  using Nl80211Socket::SetNetlinkCallback;
+  MOCK_METHOD2(SetNetlinkCallback, bool(nl_recvmsg_msg_cb_t on_netlink_data,
+                                        void *callback_parameter));
+ private:
+  DISALLOW_COPY_AND_ASSIGN(MockNl80211Socket);
+};
+
+}  // namespace shill
+
+#endif  // SHILL_MOCK_NL80211_SOCKET_
diff --git a/netlink_socket.cc b/netlink_socket.cc
new file mode 100644
index 0000000..7108275
--- /dev/null
+++ b/netlink_socket.cc
@@ -0,0 +1,189 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#include "shill/netlink_socket.h"
+
+#include <ctype.h>
+#include <errno.h>
+
+#include <net/if.h>
+#include <netlink/attr.h>
+#include <netlink/genl/ctrl.h>
+#include <netlink/genl/family.h>
+#include <netlink/genl/genl.h>
+#include <netlink/msg.h>
+#include <netlink/netlink.h>
+
+#include <iomanip>
+
+#include <base/logging.h>
+
+#include "shill/kernel_bound_nlmessage.h"
+#include "shill/scope_logger.h"
+
+namespace shill {
+
+//
+// NetlinkSocket::Callback.
+//
+
+NetlinkSocket::Callback::~Callback() {
+  if (cb_) {
+    nl_cb_put(cb_);
+    cb_ = NULL;
+  }
+}
+
+bool NetlinkSocket::Callback::Init() {
+  cb_ = nl_cb_alloc(NL_CB_DEFAULT);
+  if (!cb_) {
+    LOG(ERROR) << "NULL cb_";
+    return false;
+  }
+  return true;
+}
+
+bool NetlinkSocket::Callback::ErrHandler(enum nl_cb_kind kind,
+                                         nl_recvmsg_err_cb_t func,
+                                         void *arg) {
+  int result = nl_cb_err(cb_, kind, func, arg);
+  if (result) {
+    LOG(ERROR) << "nl_cb_err returned " << result;
+    return false;
+  }
+  return true;
+}
+
+bool NetlinkSocket::Callback::SetHandler(enum nl_cb_type type,
+                                         enum nl_cb_kind kind,
+                                         nl_recvmsg_msg_cb_t func,
+                                         void *arg) {
+  int result = nl_cb_set(cb_, type, kind, func, arg);
+  if (result) {
+    LOG(ERROR) << "nl_cb_set returned " << result;
+    return false;
+  }
+  return true;
+}
+
+//
+// NetlinkSocket.
+//
+
+NetlinkSocket::~NetlinkSocket() {
+  if (nl_sock_) {
+    nl_socket_free(nl_sock_);
+    nl_sock_ = NULL;
+  }
+}
+
+bool NetlinkSocket::Init() {
+  nl_sock_ = nl_socket_alloc();
+  if (!nl_sock_) {
+    LOG(ERROR) << "Failed to allocate netlink socket.";
+    return false;
+  }
+
+  if (genl_connect(nl_sock_)) {
+    LOG(ERROR) << "Failed to connect to generic netlink.";
+    return false;
+  }
+
+  return true;
+}
+
+bool NetlinkSocket::DisableSequenceChecking() {
+  if (!nl_sock_) {
+    LOG(ERROR) << "NULL socket";
+    return false;
+  }
+
+  // NOTE: can't use nl_socket_disable_seq_check(); it's not in this version
+  // of the library.
+  int result = nl_socket_modify_cb(nl_sock_, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
+                                   NetlinkSocket::IgnoreSequenceCheck, NULL);
+  if (result) {
+    LOG(ERROR) << "Failed call to nl_socket_modify_cb: " << result;
+    return false;
+  }
+
+  return true;
+}
+
+int NetlinkSocket::GetFd() const {
+  if (!nl_sock_) {
+    LOG(ERROR) << "NULL socket";
+    return -1;
+  }
+  return nl_socket_get_fd(nl_sock_);
+}
+
+bool NetlinkSocket::GetMessages() {
+  // TODO(wdg): make this non-blocking.
+  // Blocks until a message is available.  When that happens, the message is
+  // read and passed to the default callback (i.e., the one set with
+  // NetlinkSocket::SetNetlinkCallback).
+  int result = nl_recvmsgs_default(nl_sock_);
+  if (result < 0) {
+    LOG(ERROR) << "Failed call to nl_recvmsgs_default: " << result;
+    return false;
+  }
+  return true;
+}
+
+bool NetlinkSocket::GetMessagesUsingCallback(
+    NetlinkSocket::Callback *on_netlink_data) {
+  if (!on_netlink_data || !on_netlink_data->cb_)
+    return GetMessages();  // Default to generic callback.
+
+  int result = nl_recvmsgs(nl_sock_, on_netlink_data->cb_);
+  if (result < 0) {
+    LOG(ERROR) << "Failed call to nl_recvmsgs: " << result;
+    return false;
+  }
+  return true;
+}
+
+bool NetlinkSocket::SetNetlinkCallback(nl_recvmsg_msg_cb_t on_netlink_data,
+                                       void *callback_parameter) {
+  if (!nl_sock_) {
+    LOG(ERROR) << "NULL socket";
+    return false;
+  }
+
+  int result = nl_socket_modify_cb(nl_sock_, NL_CB_VALID, NL_CB_CUSTOM,
+                                   on_netlink_data, callback_parameter);
+  if (result) {
+    LOG(ERROR) << "nl_socket_modify_cb returned " << result;
+    return false;
+  }
+  return true;
+}
+
+int NetlinkSocket::IgnoreSequenceCheck(struct nl_msg *ignored_msg,
+                                       void *ignored_arg) {
+  return NL_OK;  // Proceed.
+}
+
+}  // namespace shill.
diff --git a/netlink_socket.h b/netlink_socket.h
new file mode 100644
index 0000000..0db5c3a
--- /dev/null
+++ b/netlink_socket.h
@@ -0,0 +1,149 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#ifndef SHILL_NETLINK_SOCKET_H_
+#define SHILL_NETLINK_SOCKET_H_
+
+#include <iomanip>
+#include <string>
+
+#include <asm/types.h>
+#include <linux/nl80211.h>
+#include <netlink/handlers.h>
+#include <netlink/netlink.h>
+
+#include <base/basictypes.h>
+#include <base/bind.h>
+#include <base/logging.h>
+
+#include "shill/kernel_bound_nlmessage.h"
+
+enum nl_cb_kind;
+enum nl_cb_type;
+struct nl_msg;
+
+namespace shill {
+
+// libnl 1.x compatibility code -- these functions provide libnl v2.x/v3.x
+// interfaces for systems that only have v1.x libraries.
+#if !defined(CONFIG_LIBNL20) && !defined(CONFIG_LIBNL30)
+#define nl_sock nl_handle
+static inline struct nl_handle *nl_socket_alloc(void) {
+  return nl_handle_alloc();
+}
+
+static inline void nl_socket_free(struct nl_sock *h) {
+  nl_handle_destroy(h);
+}
+#endif /* CONFIG_LIBNL20 && CONFIG_LIBNL30 */
+
+
+// Provides an abstraction to a netlink socket.  See
+// http://www.infradead.org/~tgr/libnl/ for documentation on how netlink
+// sockets work.
+class NetlinkSocket {
+ public:
+  // Provides a wrapper around the netlink callback.
+  class Callback {
+   public:
+    Callback() : cb_(NULL) {}
+    virtual ~Callback();
+
+    // Non-trivial initialization.
+    bool Init();
+
+    // Very thin abstraction of nl_cb_err.  Takes the same parameters used by
+    // 'nl_cb_err' except for the first parameter of 'nl_cb_err' (which is
+    // filled in using the member variable |cb_|).
+    bool ErrHandler(nl_cb_kind kind, nl_recvmsg_err_cb_t func, void *arg);
+
+    // Very thin abstraction of nl_cb_set.  Takes the same parameters used by
+    // 'nl_cb_set' except for the first parameter of 'nl_cb_set' (which is
+    // filled in using the member variable |cb_|).
+    bool SetHandler(nl_cb_type type, nl_cb_kind kind, nl_recvmsg_msg_cb_t func,
+                    void *arg);
+
+   private:
+    friend class NetlinkSocket;  // Because GetMessagesUsingCallback needs cb().
+
+    const struct nl_cb *cb() const { return cb_; }
+
+    struct nl_cb *cb_;
+
+    DISALLOW_COPY_AND_ASSIGN(Callback);
+  };
+
+  NetlinkSocket() : nl_sock_(NULL) {}
+  virtual ~NetlinkSocket();
+
+  // Non-trivial initialization.
+  bool Init();
+
+  // Disables sequence checking on the message stream.
+  virtual bool DisableSequenceChecking();
+
+  // Returns the file descriptor used by the socket.
+  virtual int GetFd() const;
+
+  // Receives one or more messages (perhaps a response to a previously sent
+  // message) over the netlink socket.  The message(s) are handled with the
+  // default callback (configured with 'SetNetlinkCallback').
+  virtual bool GetMessages();
+
+  // Receives one or more messages over the netlink socket.  The message(s)
+  // are handled with the supplied callback (uses socket's default callback
+  // function if NULL).
+  virtual bool GetMessagesUsingCallback(NetlinkSocket::Callback *callback);
+
+  virtual unsigned int GetSequenceNumber() {
+    return nl_socket_use_seq(nl_sock_);
+  }
+
+  // This method is called |callback_function| to differentiate it from the
+  // 'callback' method in KernelBoundNlMessage since they return different
+  // types.
+  virtual bool SetNetlinkCallback(nl_recvmsg_msg_cb_t on_netlink_data,
+                                  void *callback_parameter);
+
+  // Returns the family name of the socket created by this type of object.
+  virtual std::string GetSocketFamilyName() const = 0;
+
+  const struct nl_sock *GetConstNlSock() const { return nl_sock_; }
+
+ protected:
+  struct nl_sock *GetNlSock() { return nl_sock_; }
+
+ private:
+  // Netlink Callback function for nl80211.  Used to disable the sequence
+  // checking on messages received from the netlink module.
+  static int IgnoreSequenceCheck(nl_msg *ignored_msg, void *ignored_arg);
+
+  struct nl_sock *nl_sock_;
+
+  DISALLOW_COPY_AND_ASSIGN(NetlinkSocket);
+};
+
+}  // namespace shill
+
+#endif  // SHILL_NETLINK_SOCKET_H_
diff --git a/nl80211_socket.cc b/nl80211_socket.cc
new file mode 100644
index 0000000..7c3ea34
--- /dev/null
+++ b/nl80211_socket.cc
@@ -0,0 +1,233 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#include "shill/nl80211_socket.h"
+
+#include <ctype.h>
+#include <errno.h>
+
+#include <net/if.h>
+#include <netlink/attr.h>
+#include <netlink/genl/ctrl.h>
+#include <netlink/genl/family.h>
+#include <netlink/genl/genl.h>
+#include <netlink/msg.h>
+#include <netlink/netlink.h>
+
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+#include <base/logging.h>
+
+#include "shill/kernel_bound_nlmessage.h"
+#include "shill/logging.h"
+#include "shill/netlink_socket.h"
+#include "shill/scope_logger.h"
+#include "shill/user_bound_nlmessage.h"
+
+using std::string;
+
+namespace shill {
+
+const char Nl80211Socket::kSocketFamilyName[] = "nl80211";
+
+bool Nl80211Socket::Init() {
+  if (!NetlinkSocket::Init()) {
+    LOG(ERROR) << "NetlinkSocket didn't initialize.";
+    return false;
+  }
+
+  nl80211_id_ = genl_ctrl_resolve(GetNlSock(), "nlctrl");
+  if (nl80211_id_ < 0) {
+    LOG(ERROR) << "nl80211 not found.";
+    return false;
+  }
+
+  return true;
+}
+
+bool Nl80211Socket::AddGroupMembership(const string &group_name) {
+  int id = GetMulticastGroupId(group_name);
+  if (id < 0) {
+    LOG(ERROR) << "No Id for group " << group_name;
+    return false;
+  } else {
+    int result = nl_socket_add_membership(GetNlSock(), id);
+    if (result != 0) {
+      LOG(ERROR) << "Failed call to 'nl_socket_add_membership': " << result;
+      return false;
+    }
+  }
+  return true;
+}
+
+int Nl80211Socket::OnAck(struct nl_msg *unused_msg, void *arg) {
+  if (arg) {
+    int *ret = reinterpret_cast<int *>(arg);
+    *ret = 0;
+  }
+  return NL_STOP;  // Stop parsing and discard remainder of buffer.
+}
+
+int Nl80211Socket::OnError(struct sockaddr_nl *unused_nla, struct nlmsgerr *err,
+                           void *arg) {
+  int *ret = reinterpret_cast<int *>(arg);
+  if (err) {
+    if (ret)
+      *ret = err->error;
+    LOG(ERROR) << "Error(" << err->error << ") " << strerror(err->error);
+  } else {
+    if (ret)
+      *ret = -1;
+    LOG(ERROR) << "Error(<unknown>)";
+  }
+  return NL_STOP;  // Stop parsing and discard remainder of buffer.
+}
+
+int Nl80211Socket::OnFamilyResponse(struct nl_msg *msg, void *arg) {
+  if (!msg) {
+    LOG(ERROR) << "NULL |msg| parameter";
+    return NL_SKIP;  // Skip current message, continue parsing buffer.
+  }
+
+  if (!arg) {
+    LOG(ERROR) << "NULL |arg| parameter";
+    return NL_SKIP;  // Skip current message, continue parsing buffer.
+  }
+
+  struct HandlerArgs *grp = reinterpret_cast<struct HandlerArgs *>(arg);
+  struct nlattr *tb[CTRL_ATTR_MAX + 1];
+  struct genlmsghdr *gnlh = reinterpret_cast<struct genlmsghdr *>(
+      nlmsg_data(nlmsg_hdr(msg)));
+  struct nlattr *mcgrp = NULL;
+  int rem_mcgrp;
+
+  nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
+            genlmsg_attrlen(gnlh, 0), NULL);
+
+  if (!tb[CTRL_ATTR_MCAST_GROUPS])
+    return NL_SKIP;  // Skip current message, continue parsing buffer.
+
+  // nla_for_each_nested(...)
+  mcgrp = reinterpret_cast<nlattr *>(nla_data(tb[CTRL_ATTR_MCAST_GROUPS]));
+  rem_mcgrp = nla_len(tb[CTRL_ATTR_MCAST_GROUPS]);
+  bool found_one = false;
+  for (; nla_ok(mcgrp, rem_mcgrp); mcgrp = nla_next(mcgrp, &(rem_mcgrp))) {
+    struct nlattr *tb_mcgrp[CTRL_ATTR_MCAST_GRP_MAX + 1];
+
+    nla_parse(tb_mcgrp, CTRL_ATTR_MCAST_GRP_MAX,
+        reinterpret_cast<nlattr *>(nla_data(mcgrp)), nla_len(mcgrp), NULL);
+
+    if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]) {
+      LOG(ERROR) << "No group name in 'group' message";
+      continue;
+    } else if (!tb_mcgrp[CTRL_ATTR_MCAST_GRP_ID]) {
+      LOG(ERROR) << "No group id in 'group' message";
+      continue;
+    }
+
+    if (strncmp(reinterpret_cast<char *>(
+        nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME])),
+          grp->group, nla_len(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]))) {
+      continue;
+    }
+    found_one = true;
+    grp->id = nla_get_u32(tb_mcgrp[CTRL_ATTR_MCAST_GRP_ID]);
+    SLOG(WiFi, 6) << "GROUP '"
+                  << reinterpret_cast<char *>(
+                      nla_data(tb_mcgrp[CTRL_ATTR_MCAST_GRP_NAME]))
+                  << "' has ID "
+                  << grp->id;
+    break;
+  }
+  if (!found_one) {
+    LOG(ERROR) << "NO GROUP matched '"
+               << grp->group
+               << "', the one for which we were looking";
+  }
+
+  return NL_SKIP;  // Skip current message, continue parsing buffer.
+}
+
+int Nl80211Socket::GetMulticastGroupId(const string &group) {
+  // Allocate and build the message.
+  KernelBoundNlMessage message;
+  if (!message.Init()) {
+    LOG(ERROR) << "Couldn't initialize message";
+    return -1;
+  }
+
+  if (!message.AddNetlinkHeader(NL_AUTO_PID, NL_AUTO_SEQ, GetFamilyId(), 0, 0,
+                                CTRL_CMD_GETFAMILY, 0))
+    return -1;
+
+  int result = message.AddAttribute(CTRL_ATTR_FAMILY_NAME,
+                                    GetSocketFamilyName().length() + 1,
+                                    GetSocketFamilyName().c_str());
+  if (result < 0) {
+    LOG(ERROR) << "nla_put return error: " << result;
+    return -1;
+  }
+
+  if (!message.Send(this)) {
+    return -1;
+  }
+
+  // Wait for the response.
+
+  NetlinkSocket::Callback netlink_callback;
+  struct HandlerArgs grp(group.c_str(), -ENOENT);
+  int status = 1;
+
+  if (netlink_callback.Init()) {
+    if (!netlink_callback.ErrHandler(NL_CB_CUSTOM, OnError, &status)) {
+      return -1;
+    }
+    if (!netlink_callback.SetHandler(NL_CB_ACK, NL_CB_CUSTOM, OnAck, &status)) {
+      return -1;
+    }
+    if (!netlink_callback.SetHandler(NL_CB_VALID, NL_CB_CUSTOM,
+                                     OnFamilyResponse, &grp)) {
+      return -1;
+    }
+  } else {
+    LOG(ERROR) << "Couldn't initialize callback";
+    return -1;
+  }
+
+  while (status > 0) {  // 'status' is set by the NL_CB_ACK handler.
+    if (!GetMessagesUsingCallback(&netlink_callback)) {
+      return -1;
+    }
+  }
+
+  if (status != 0) {
+    return -1;
+  }
+
+  return grp.id;
+}
+
+}  // namespace shill
diff --git a/nl80211_socket.h b/nl80211_socket.h
new file mode 100644
index 0000000..c0e9cde
--- /dev/null
+++ b/nl80211_socket.h
@@ -0,0 +1,102 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#ifndef SHILL_NL80211_SOCKET_H_
+#define SHILL_NL80211_SOCKET_H_
+
+#include <iomanip>
+#include <string>
+
+#include <linux/nl80211.h>
+
+#include <base/basictypes.h>
+#include <base/bind.h>
+
+#include "shill/netlink_socket.h"
+
+struct nl_msg;
+struct sockaddr_nl;
+struct nlmsgerr;
+
+namespace shill {
+
+// Provides a mechanism to communicate with the cfg80211 and mac80211 modules
+// utilizing a netlink socket.
+class Nl80211Socket : public NetlinkSocket {
+ public:
+  Nl80211Socket() : nl80211_id_(-1) {}
+  virtual ~Nl80211Socket() {}
+
+  // Perform non-trivial initialization.
+  bool Init();
+
+  // Add ourself to the multicast group that gets sent messages of the
+  // specificed type.  Legal |group_name| character strings are defined by
+  // cfg80211 module but they include "config", "scan", "regulatory", and
+  // "mlme".
+  virtual bool AddGroupMembership(const std::string &group_name);
+
+  // Returns the value returned by the 'genl_ctrl_resolve' call.
+  int GetFamilyId() const { return nl80211_id_; }
+
+  // Gets the name of the socket family.
+  std::string GetSocketFamilyName() const {
+    return Nl80211Socket::kSocketFamilyName;
+  }
+
+ private:
+  struct HandlerArgs {
+    HandlerArgs() : group(NULL), id(0) {}
+    HandlerArgs(const char *group_arg, int id_arg) :
+      group(group_arg), id(id_arg) {}
+    const char *group;
+    int id;
+  };
+
+  // Contains 'nl80211', the family name of the netlink socket.
+  static const char kSocketFamilyName[];
+
+  // Method called by cfg80211 to acknowledge messages sent to cfg80211.
+  static int OnAck(nl_msg *unused_msg, void *arg);
+
+  // Method called by cfg80211 for message errors.
+  static int OnError(sockaddr_nl *unused_nla, nlmsgerr *err, void *arg);
+
+  // Netlink Callback for handling response to 'CTRL_CMD_GETFAMILY' message.
+  static int OnFamilyResponse(nl_msg *msg, void *arg);
+
+  // Gets an ID for a specified type of multicast messages sent from the
+  // cfg80211 module.
+  virtual int GetMulticastGroupId(const std::string &group);
+
+  // The id returned by a call to 'genl_ctrl_resolve'.
+  int nl80211_id_;
+
+  DISALLOW_COPY_AND_ASSIGN(Nl80211Socket);
+};
+
+
+}  // namespace shill
+
+#endif  // SHILL_NL80211_SOCKET_H_
diff --git a/shill_daemon.cc b/shill_daemon.cc
index 315e9a4..727d6f6 100644
--- a/shill_daemon.cc
+++ b/shill_daemon.cc
@@ -30,7 +30,7 @@
 
 // TODO(gmorain): 3 seconds may or may not be enough.  Add an UMA stat to see
 // how often the timeout occurs.  crosbug.com/31475.
-const int Daemon::kTerminationActionsTimeout = 3000; // ms
+const int Daemon::kTerminationActionsTimeout = 3000;  // ms
 
 Daemon::Daemon(Config *config, ControlInterface *control)
     : config_(config),
@@ -40,6 +40,8 @@
       rtnl_handler_(RTNLHandler::GetInstance()),
       routing_table_(RoutingTable::GetInstance()),
       dhcp_provider_(DHCPProvider::GetInstance()),
+      config80211_(Config80211::GetInstance()),
+      callback80211_(Callback80211Object::GetInstance()),
       manager_(new Manager(control_,
                            &dispatcher_,
                            &metrics_,
@@ -48,6 +50,7 @@
                            config->GetStorageDirectory(),
                            config->GetUserStorageDirectoryFormat())) {
 }
+
 Daemon::~Daemon() {}
 
 void Daemon::AddDeviceToBlackList(const string &device_name) {
@@ -92,6 +95,25 @@
   rtnl_handler_->Start(&dispatcher_, &sockets_);
   routing_table_->Start();
   dhcp_provider_->Init(control_, &dispatcher_, &glib_);
+
+  if (config80211_) {
+    config80211_->Init(&dispatcher_);
+    // Subscribe to all the events in which we're interested.
+    static const Config80211::EventType kEvents[] = {
+      Config80211::kEventTypeConfig,
+      Config80211::kEventTypeScan,
+      Config80211::kEventTypeRegulatory,
+      Config80211::kEventTypeMlme };
+
+    // Install |callback80211_| in the Config80211 singleton.
+    callback80211_->set_config80211(config80211_);
+    callback80211_->InstallAsCallback();
+
+    for (size_t i = 0; i < arraysize(kEvents); i++) {
+      config80211_->SubscribeToEvents(kEvents[i]);
+    }
+  }
+
   manager_->Start();
 }
 
diff --git a/shill_daemon.h b/shill_daemon.h
index a03bf2c..e027ca6 100644
--- a/shill_daemon.h
+++ b/shill_daemon.h
@@ -9,6 +9,7 @@
 
 #include <base/memory/scoped_ptr.h>
 
+#include "shill/config80211.h"
 #include "shill/event_dispatcher.h"
 #include "shill/glib.h"
 #include "shill/manager.h"
@@ -62,6 +63,8 @@
   RTNLHandler *rtnl_handler_;
   RoutingTable *routing_table_;
   DHCPProvider *dhcp_provider_;
+  Config80211 *config80211_;
+  Callback80211Object *callback80211_;
   scoped_ptr<Manager> manager_;
   EventDispatcher dispatcher_;
   Sockets sockets_;
diff --git a/user_bound_nlmessage.cc b/user_bound_nlmessage.cc
new file mode 100644
index 0000000..c2087ae
--- /dev/null
+++ b/user_bound_nlmessage.cc
@@ -0,0 +1,1881 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+// This code is derived from the 'iw' source code.  The copyright and license
+// of that code is as follows:
+//
+// Copyright (c) 2007, 2008  Johannes Berg
+// Copyright (c) 2007  Andy Lutomirski
+// Copyright (c) 2007  Mike Kershaw
+// Copyright (c) 2008-2009  Luis R. Rodriguez
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#include "shill/user_bound_nlmessage.h"
+
+#include <ctype.h>
+#include <endian.h>
+#include <errno.h>
+
+#include <netinet/in.h>
+#include <linux/nl80211.h>
+#include <net/if.h>
+#include <netlink/attr.h>
+#include <netlink/genl/ctrl.h>
+#include <netlink/genl/family.h>
+#include <netlink/genl/genl.h>
+#include <netlink/msg.h>
+#include <netlink/netlink.h>
+
+#include <iomanip>
+#include <string>
+
+#include <base/format_macros.h>
+#include <base/stl_util.h>
+#include <base/stringprintf.h>
+
+#include "shill/ieee80211.h"
+#include "shill/logging.h"
+#include "shill/scope_logger.h"
+
+using base::LazyInstance;
+using base::StringAppendF;
+using base::StringPrintf;
+using std::map;
+using std::string;
+using std::vector;
+
+namespace shill {
+
+namespace {
+LazyInstance<UserBoundNlMessageDataCollector> g_datacollector =
+    LAZY_INSTANCE_INITIALIZER;
+}  // namespace
+
+const uint8_t UserBoundNlMessage::kCommand = 0xff;
+const char UserBoundNlMessage::kCommandString[] = "<Unknown Message>";
+const char UserBoundNlMessage::kBogusMacAddress[]="XX:XX:XX:XX:XX:XX";
+
+const uint8_t Nl80211Frame::kMinimumFrameByteCount = 26;
+const uint8_t Nl80211Frame::kFrameTypeMask = 0xfc;
+
+const uint32_t UserBoundNlMessage::kIllegalMessage = 0xFFFFFFFF;
+const int UserBoundNlMessage::kEthernetAddressBytes = 6;
+map<uint16_t, string> *UserBoundNlMessage::connect_status_map_ = NULL;
+
+// The nl messages look like this:
+//
+//       XXXXXXXXXXXXXXXXXXX-nlmsg_total_size-XXXXXXXXXXXXXXXXXXX
+//       XXXXXXXXXXXXXXXXXXX-nlmsg_msg_size-XXXXXXXXXXXXXXXXXXX
+//               +-- gnhl                        nlmsg_tail(hdr) --+
+//               |                               nlmsg_next(hdr) --+
+//               v        XXXXXXXXXXXX-nlmsg_len-XXXXXXXXXXXXXX    V
+// -----+-----+-+----------------------------------------------+-++----
+//  ... |     | |                payload                       | ||
+//      |     | +------+-+--------+-+--------------------------+ ||
+//      | nl  | |      | |        | |      attribs             | ||
+//      | msg |p| genl |p| family |p+------+-+-------+-+-------+p|| ...
+//      | hdr |a| msg  |a| header |a| nl   |p| pay   |p|       |a||
+//      |     |d| hdr  |d|        |d| attr |a| load  |a| ...   |d||
+//      |     | |      | |        | |      |d|       |d|       | ||
+// -----+-----+-+----------------------------------------------+-++----
+//       ^       ^                   ^        ^
+//       |       |                   |        XXXXXXX <-- nla_len(nlattr)
+//       |       |                   |        +-- nla_data(nlattr)
+//       |       |                   X-nla_total_size-X
+//       |       |                   XXXXX-nlmsg_attrlen-XXXXXX
+//       |       +-- nlmsg_data(hdr) +-- nlmsg_attrdata()
+//       +-- msg = nlmsg_hdr(raw_message)
+
+//
+// UserBoundNlMessage
+//
+
+UserBoundNlMessage::~UserBoundNlMessage() {
+  map<enum nl80211_attrs, nlattr *>::iterator i;
+  for (i = attributes_.begin(); i != attributes_.end(); ++i) {
+    delete [] reinterpret_cast<uint8_t *>(i->second);
+  }
+}
+
+bool UserBoundNlMessage::Init(nlattr *tb[NL80211_ATTR_MAX + 1],
+                              nlmsghdr *msg) {
+  if (!tb) {
+    LOG(ERROR) << "Null |tb| parameter";
+    return false;
+  }
+
+  message_ = msg;
+
+  SLOG(WiFi, 6) << "NL Message " << GetId() << " <===";
+
+  for (int i = 0; i < NL80211_ATTR_MAX + 1; ++i) {
+    if (tb[i]) {
+      AddAttribute(static_cast<enum nl80211_attrs>(i), tb[i]);
+    }
+  }
+
+  // Convert integer values provided by libnl (for example, from the
+  // NL80211_ATTR_STATUS_CODE or NL80211_ATTR_REASON_CODE attribute) into
+  // strings describing the status.
+  if (!connect_status_map_) {
+    connect_status_map_ = new map<uint16_t, string>;
+    (*connect_status_map_)[0] = "Successful";
+    (*connect_status_map_)[1] = "Unspecified failure";
+    (*connect_status_map_)[2] = "Previous authentication no longer valid";
+    (*connect_status_map_)[3] = "Deauthenticated because sending station is "
+        "leaving (or has left) the IBSS or ESS";
+    (*connect_status_map_)[7] = "Class 3 frame received from non-authenticated "
+        "station";
+    (*connect_status_map_)[10] = "Cannot support all requested capabilities in "
+        "the capability information field";
+    (*connect_status_map_)[11] = "Reassociation denied due to inability to "
+        "confirm that association exists";
+    (*connect_status_map_)[12] = "Association denied due to reason outside the "
+        "scope of this standard";
+    (*connect_status_map_)[13] = "Responding station does not support the "
+        "specified authentication algorithm";
+    (*connect_status_map_)[14] = "Received an authentication frame with "
+        "authentication transaction sequence number out of expected sequence";
+    (*connect_status_map_)[15] = "Authentication rejected because of challenge "
+        "failure";
+    (*connect_status_map_)[16] = "Authentication rejected due to timeout "
+        "waiting for next frame in sequence";
+    (*connect_status_map_)[17] = "Association denied because AP is unable to "
+        "handle additional associated STA";
+    (*connect_status_map_)[18] = "Association denied due to requesting station "
+        "not supporting all of the data rates in the BSSBasicRateSet parameter";
+    (*connect_status_map_)[19] = "Association denied due to requesting station "
+        "not supporting the short preamble option";
+    (*connect_status_map_)[20] = "Association denied due to requesting station "
+        "not supporting the PBCC modulation option";
+    (*connect_status_map_)[21] = "Association denied due to requesting station "
+        "not supporting the channel agility option";
+    (*connect_status_map_)[22] = "Association request rejected because "
+        "Spectrum Management capability is required";
+    (*connect_status_map_)[23] = "Association request rejected because the "
+        "information in the Power Capability element is unacceptable";
+    (*connect_status_map_)[24] = "Association request rejected because the "
+        "information in the Supported Channels element is unacceptable";
+    (*connect_status_map_)[25] = "Association request rejected due to "
+        "requesting station not supporting the short slot time option";
+    (*connect_status_map_)[26] = "Association request rejected due to "
+        "requesting station not supporting the ER-PBCC modulation option";
+    (*connect_status_map_)[27] = "Association denied due to requesting STA not "
+        "supporting HT features";
+    (*connect_status_map_)[28] = "R0KH Unreachable";
+    (*connect_status_map_)[29] = "Association denied because the requesting "
+        "STA does not support the PCO transition required by the AP";
+    (*connect_status_map_)[30] = "Association request rejected temporarily; "
+        "try again later";
+    (*connect_status_map_)[31] = "Robust Management frame policy violation";
+    (*connect_status_map_)[32] = "Unspecified, QoS related failure";
+    (*connect_status_map_)[33] = "Association denied due to QAP having "
+        "insufficient bandwidth to handle another QSTA";
+    (*connect_status_map_)[34] = "Association denied due to poor channel "
+        "conditions";
+    (*connect_status_map_)[35] = "Association (with QBSS) denied due to "
+        "requesting station not supporting the QoS facility";
+    (*connect_status_map_)[37] = "The request has been declined";
+    (*connect_status_map_)[38] = "The request has not been successful as one "
+        "or more parameters have invalid values";
+    (*connect_status_map_)[39] = "The TS has not been created because the "
+        "request cannot be honored. However, a suggested Tspec is provided so "
+        "that the initiating QSTA may attempt to send another TS with the "
+        "suggested changes to the TSpec";
+    (*connect_status_map_)[40] = "Invalid Information Element";
+    (*connect_status_map_)[41] = "Group Cipher is not valid";
+    (*connect_status_map_)[42] = "Pairwise Cipher is not valid";
+    (*connect_status_map_)[43] = "AKMP is not valid";
+    (*connect_status_map_)[44] = "Unsupported RSN IE version";
+    (*connect_status_map_)[45] = "Invalid RSN IE Capabilities";
+    (*connect_status_map_)[46] = "Cipher suite is rejected per security policy";
+    (*connect_status_map_)[47] = "The TS has not been created. However, the HC "
+        "may be capable of creating a TS, in response to a request, after the "
+        "time indicated in the TS Delay element";
+    (*connect_status_map_)[48] = "Direct link is not allowed in the BSS by "
+        "policy";
+    (*connect_status_map_)[49] = "Destination STA is not present within this "
+        "QBSS";
+    (*connect_status_map_)[50] = "The destination STA is not a QSTA";
+    (*connect_status_map_)[51] = "Association denied because Listen Interval "
+        "is too large";
+    (*connect_status_map_)[52] = "Invalid Fast BSS Transition Action Frame "
+        "Count";
+    (*connect_status_map_)[53] = "Invalid PMKID";
+    (*connect_status_map_)[54] = "Invalid MDIE";
+    (*connect_status_map_)[55] = "Invalid FTIE";
+  }
+
+  return true;
+}
+
+UserBoundNlMessage::AttributeNameIterator*
+    UserBoundNlMessage::GetAttributeNameIterator() const {
+  UserBoundNlMessage::AttributeNameIterator *iter =
+      new UserBoundNlMessage::AttributeNameIterator(attributes_);
+  return iter;
+}
+
+// Return true if the attribute is in our map, regardless of the value of
+// the attribute, itself.
+bool UserBoundNlMessage::AttributeExists(enum nl80211_attrs name) const {
+  return ContainsKey(attributes_, name);
+}
+
+uint32_t UserBoundNlMessage::GetId() const {
+  if (!message_) {
+    return kIllegalMessage;
+  }
+  return message_->nlmsg_seq;
+}
+
+enum UserBoundNlMessage::Type
+    UserBoundNlMessage::GetAttributeType(enum nl80211_attrs name) const {
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return kTypeError;
+  }
+
+  switch (nla_type(attr)) {
+    case NLA_UNSPEC: return kTypeUnspecified;
+    case NLA_U8: return kTypeU8;
+    case NLA_U16: return kTypeU16;
+    case NLA_U32: return kTypeU32;
+    case NLA_U64: return kTypeU64;
+    case NLA_STRING: return kTypeString;
+    case NLA_FLAG: return kTypeFlag;
+    case NLA_MSECS: return kTypeMsecs;
+    case NLA_NESTED: return kTypeNested;
+    default: return kTypeError;
+  }
+
+  return kTypeError;
+}
+
+string UserBoundNlMessage::GetAttributeTypeString(enum nl80211_attrs name)
+    const {
+  switch (GetAttributeType(name)) {
+    case kTypeUnspecified: return "Unspecified Type"; break;
+    case kTypeU8: return "uint8_t"; break;
+    case kTypeU16: return "uint16_t"; break;
+    case kTypeU32: return "uint32_t"; break;
+    case kTypeU64: return "uint64_t"; break;
+    case kTypeString: return "String"; break;
+    case kTypeFlag: return "Flag"; break;
+    case kTypeMsecs: return "MSec Type"; break;
+    case kTypeNested: return "Nested Type"; break;
+    case kTypeError: return "ERROR TYPE"; break;
+    default: return "Funky Type"; break;
+  }
+}
+
+// Returns the raw attribute data but not the header.
+bool UserBoundNlMessage::GetRawAttributeData(enum nl80211_attrs name,
+                                             void **value,
+                                             int *length) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    *value = NULL;
+    return false;
+  }
+
+  if (length) {
+    *length = nla_len(attr);
+  }
+  *value = nla_data(attr);
+  return true;
+}
+
+bool UserBoundNlMessage::GetStringAttribute(enum nl80211_attrs name,
+                                            string *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return false;
+  }
+
+  value->assign(nla_get_string(const_cast<nlattr *>(attr)));
+  return true;
+}
+
+bool UserBoundNlMessage::GetU8Attribute(enum nl80211_attrs name,
+                                        uint8_t *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return false;
+  }
+
+  *value = nla_get_u8(const_cast<nlattr *>(attr));
+  return true;
+}
+
+bool UserBoundNlMessage::GetU16Attribute(enum nl80211_attrs name,
+                                         uint16_t *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return false;
+  }
+
+  *value = nla_get_u16(const_cast<nlattr *>(attr));
+  return true;
+}
+
+bool UserBoundNlMessage::GetU32Attribute(enum nl80211_attrs name,
+                                         uint32_t *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return false;
+  }
+
+  *value = nla_get_u32(const_cast<nlattr *>(attr));
+  return true;
+}
+
+bool UserBoundNlMessage::GetU64Attribute(enum nl80211_attrs name,
+                                         uint64_t *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    return false;
+  }
+
+  *value = nla_get_u64(const_cast<nlattr *>(attr));
+  return true;
+}
+
+// Helper function to provide a string for a MAC address.
+bool UserBoundNlMessage::GetMacAttributeString(enum nl80211_attrs name,
+                                               string *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  void *rawdata_void = NULL;
+  if (!GetRawAttributeData(name, &rawdata_void, NULL)) {
+    value->assign(kBogusMacAddress);
+    return false;
+  }
+  const uint8_t *rawdata = reinterpret_cast<const uint8_t *>(rawdata_void);
+  value->assign(StringFromMacAddress(rawdata));
+
+  return true;
+}
+
+// Helper function to provide a string for NL80211_ATTR_SCAN_FREQUENCIES.
+bool UserBoundNlMessage::GetScanFrequenciesAttribute(
+    enum nl80211_attrs name, vector<uint32_t> *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  value->clear();
+  if (AttributeExists(name)) {
+    void *rawdata = NULL;
+    int len = 0;
+    if (GetRawAttributeData(name, &rawdata, &len) && rawdata) {
+      nlattr *nst = NULL;
+      nlattr *attr_data = reinterpret_cast<nlattr *>(rawdata);
+      int rem_nst;
+
+      nla_for_each_attr(nst, attr_data, len, rem_nst) {
+        value->push_back(nla_get_u32(nst));
+      }
+    }
+    return true;
+  }
+
+  return false;
+}
+
+// Helper function to provide a string for NL80211_ATTR_SCAN_SSIDS.
+bool UserBoundNlMessage::GetScanSsidsAttribute(
+    enum nl80211_attrs name, vector<string> *value) const {
+  if (!value) {
+    LOG(ERROR) << "Null |value| parameter";
+    return false;
+  }
+
+  if (AttributeExists(name)) {
+    void *rawdata = NULL;
+    int len = 0;
+    if (GetRawAttributeData(name, &rawdata, &len) && rawdata) {
+      nlattr *nst = NULL;
+      nlattr *data = reinterpret_cast<nlattr *>(rawdata);
+      int rem_nst;
+
+      nla_for_each_attr(nst, data, len, rem_nst) {
+        value->push_back(StringFromSsid(nla_len(nst),
+                                        reinterpret_cast<const uint8_t *>(
+                                          nla_data(nst))).c_str());
+      }
+    }
+    return true;
+  }
+
+  return false;
+}
+
+bool UserBoundNlMessage::GetAttributeString(nl80211_attrs name,
+                                            string *param) const {
+  if (!param) {
+    LOG(ERROR) << "Null |param| parameter";
+    return false;
+  }
+
+  switch (GetAttributeType(name)) {
+    case kTypeU8: {
+      uint8_t value;
+      if (!GetU8Attribute(name, &value))
+        return false;
+      *param = StringPrintf("%u", value);
+      break;
+    }
+    case kTypeU16: {
+      uint16_t value;
+      if (!GetU16Attribute(name, &value))
+        return false;
+      *param = StringPrintf("%u", value);
+      break;
+    }
+    case kTypeU32: {
+      uint32_t value;
+      if (!GetU32Attribute(name, &value))
+        return false;
+      *param = StringPrintf("%" PRIu32, value);
+      break;
+    }
+    case kTypeU64: {
+      uint64_t value;
+      if (!GetU64Attribute(name, &value))
+        return false;
+      *param = StringPrintf("%" PRIu64, value);
+      break;
+    }
+    case kTypeString:
+      if (!GetStringAttribute(name, param))
+        return false;
+      break;
+
+    default:
+      return false;
+  }
+  return true;
+}
+
+string UserBoundNlMessage::RawToString(enum nl80211_attrs name) const {
+  string output = " === RAW: ";
+
+  const nlattr *attr = GetAttribute(name);
+  if (!attr) {
+    output.append("<NULL> ===");
+    return output;
+  }
+
+  const char *typestring = NULL;
+  switch (nla_type(attr)) {
+    case NLA_UNSPEC: typestring = "NLA_UNSPEC"; break;
+    case NLA_U8: typestring = "NLA_U8"; break;
+    case NLA_U16: typestring = "NLA_U16"; break;
+    case NLA_U32: typestring = "NLA_U32"; break;
+    case NLA_U64: typestring = "NLA_U64"; break;
+    case NLA_STRING: typestring = "NLA_STRING"; break;
+    case NLA_FLAG: typestring = "NLA_FLAG"; break;
+    case NLA_MSECS: typestring = "NLA_MSECS"; break;
+    case NLA_NESTED: typestring = "NLA_NESTED"; break;
+    default: typestring = "<UNKNOWN>"; break;
+  }
+
+  uint16_t length = nla_len(attr);
+  uint16_t type = nla_type(attr);
+  StringAppendF(&output, "len=%u type=(%u)=%s", length, type, typestring);
+
+  const uint8_t *const_data
+      = reinterpret_cast<const uint8_t *>(nla_data(attr));
+
+  output.append(" DATA: ");
+  for (int i =0 ; i < length; ++i) {
+    StringAppendF(&output, "[%d]=%02x ",
+                  i, *(reinterpret_cast<const uint8_t *>(const_data)+i));
+  }
+  output.append(" ==== ");
+  return output;
+}
+
+// static
+string UserBoundNlMessage::StringFromAttributeName(enum nl80211_attrs name) {
+  switch (name) {
+    case NL80211_ATTR_UNSPEC:
+      return "NL80211_ATTR_UNSPEC"; break;
+    case NL80211_ATTR_WIPHY:
+      return "NL80211_ATTR_WIPHY"; break;
+    case NL80211_ATTR_WIPHY_NAME:
+      return "NL80211_ATTR_WIPHY_NAME"; break;
+    case NL80211_ATTR_IFINDEX:
+      return "NL80211_ATTR_IFINDEX"; break;
+    case NL80211_ATTR_IFNAME:
+      return "NL80211_ATTR_IFNAME"; break;
+    case NL80211_ATTR_IFTYPE:
+      return "NL80211_ATTR_IFTYPE"; break;
+    case NL80211_ATTR_MAC:
+      return "NL80211_ATTR_MAC"; break;
+    case NL80211_ATTR_KEY_DATA:
+      return "NL80211_ATTR_KEY_DATA"; break;
+    case NL80211_ATTR_KEY_IDX:
+      return "NL80211_ATTR_KEY_IDX"; break;
+    case NL80211_ATTR_KEY_CIPHER:
+      return "NL80211_ATTR_KEY_CIPHER"; break;
+    case NL80211_ATTR_KEY_SEQ:
+      return "NL80211_ATTR_KEY_SEQ"; break;
+    case NL80211_ATTR_KEY_DEFAULT:
+      return "NL80211_ATTR_KEY_DEFAULT"; break;
+    case NL80211_ATTR_BEACON_INTERVAL:
+      return "NL80211_ATTR_BEACON_INTERVAL"; break;
+    case NL80211_ATTR_DTIM_PERIOD:
+      return "NL80211_ATTR_DTIM_PERIOD"; break;
+    case NL80211_ATTR_BEACON_HEAD:
+      return "NL80211_ATTR_BEACON_HEAD"; break;
+    case NL80211_ATTR_BEACON_TAIL:
+      return "NL80211_ATTR_BEACON_TAIL"; break;
+    case NL80211_ATTR_STA_AID:
+      return "NL80211_ATTR_STA_AID"; break;
+    case NL80211_ATTR_STA_FLAGS:
+      return "NL80211_ATTR_STA_FLAGS"; break;
+    case NL80211_ATTR_STA_LISTEN_INTERVAL:
+      return "NL80211_ATTR_STA_LISTEN_INTERVAL"; break;
+    case NL80211_ATTR_STA_SUPPORTED_RATES:
+      return "NL80211_ATTR_STA_SUPPORTED_RATES"; break;
+    case NL80211_ATTR_STA_VLAN:
+      return "NL80211_ATTR_STA_VLAN"; break;
+    case NL80211_ATTR_STA_INFO:
+      return "NL80211_ATTR_STA_INFO"; break;
+    case NL80211_ATTR_WIPHY_BANDS:
+      return "NL80211_ATTR_WIPHY_BANDS"; break;
+    case NL80211_ATTR_MNTR_FLAGS:
+      return "NL80211_ATTR_MNTR_FLAGS"; break;
+    case NL80211_ATTR_MESH_ID:
+      return "NL80211_ATTR_MESH_ID"; break;
+    case NL80211_ATTR_STA_PLINK_ACTION:
+      return "NL80211_ATTR_STA_PLINK_ACTION"; break;
+    case NL80211_ATTR_MPATH_NEXT_HOP:
+      return "NL80211_ATTR_MPATH_NEXT_HOP"; break;
+    case NL80211_ATTR_MPATH_INFO:
+      return "NL80211_ATTR_MPATH_INFO"; break;
+    case NL80211_ATTR_BSS_CTS_PROT:
+      return "NL80211_ATTR_BSS_CTS_PROT"; break;
+    case NL80211_ATTR_BSS_SHORT_PREAMBLE:
+      return "NL80211_ATTR_BSS_SHORT_PREAMBLE"; break;
+    case NL80211_ATTR_BSS_SHORT_SLOT_TIME:
+      return "NL80211_ATTR_BSS_SHORT_SLOT_TIME"; break;
+    case NL80211_ATTR_HT_CAPABILITY:
+      return "NL80211_ATTR_HT_CAPABILITY"; break;
+    case NL80211_ATTR_SUPPORTED_IFTYPES:
+      return "NL80211_ATTR_SUPPORTED_IFTYPES"; break;
+    case NL80211_ATTR_REG_ALPHA2:
+      return "NL80211_ATTR_REG_ALPHA2"; break;
+    case NL80211_ATTR_REG_RULES:
+      return "NL80211_ATTR_REG_RULES"; break;
+    case NL80211_ATTR_MESH_CONFIG:
+      return "NL80211_ATTR_MESH_CONFIG"; break;
+    case NL80211_ATTR_BSS_BASIC_RATES:
+      return "NL80211_ATTR_BSS_BASIC_RATES"; break;
+    case NL80211_ATTR_WIPHY_TXQ_PARAMS:
+      return "NL80211_ATTR_WIPHY_TXQ_PARAMS"; break;
+    case NL80211_ATTR_WIPHY_FREQ:
+      return "NL80211_ATTR_WIPHY_FREQ"; break;
+    case NL80211_ATTR_WIPHY_CHANNEL_TYPE:
+      return "NL80211_ATTR_WIPHY_CHANNEL_TYPE"; break;
+    case NL80211_ATTR_KEY_DEFAULT_MGMT:
+      return "NL80211_ATTR_KEY_DEFAULT_MGMT"; break;
+    case NL80211_ATTR_MGMT_SUBTYPE:
+      return "NL80211_ATTR_MGMT_SUBTYPE"; break;
+    case NL80211_ATTR_IE:
+      return "NL80211_ATTR_IE"; break;
+    case NL80211_ATTR_MAX_NUM_SCAN_SSIDS:
+      return "NL80211_ATTR_MAX_NUM_SCAN_SSIDS"; break;
+    case NL80211_ATTR_SCAN_FREQUENCIES:
+      return "NL80211_ATTR_SCAN_FREQUENCIES"; break;
+    case NL80211_ATTR_SCAN_SSIDS:
+      return "NL80211_ATTR_SCAN_SSIDS"; break;
+    case NL80211_ATTR_GENERATION:
+      return "NL80211_ATTR_GENERATION"; break;
+    case NL80211_ATTR_BSS:
+      return "NL80211_ATTR_BSS"; break;
+    case NL80211_ATTR_REG_INITIATOR:
+      return "NL80211_ATTR_REG_INITIATOR"; break;
+    case NL80211_ATTR_REG_TYPE:
+      return "NL80211_ATTR_REG_TYPE"; break;
+    case NL80211_ATTR_SUPPORTED_COMMANDS:
+      return "NL80211_ATTR_SUPPORTED_COMMANDS"; break;
+    case NL80211_ATTR_FRAME:
+      return "NL80211_ATTR_FRAME"; break;
+    case NL80211_ATTR_SSID:
+      return "NL80211_ATTR_SSID"; break;
+    case NL80211_ATTR_AUTH_TYPE:
+      return "NL80211_ATTR_AUTH_TYPE"; break;
+    case NL80211_ATTR_REASON_CODE:
+      return "NL80211_ATTR_REASON_CODE"; break;
+    case NL80211_ATTR_KEY_TYPE:
+      return "NL80211_ATTR_KEY_TYPE"; break;
+    case NL80211_ATTR_MAX_SCAN_IE_LEN:
+      return "NL80211_ATTR_MAX_SCAN_IE_LEN"; break;
+    case NL80211_ATTR_CIPHER_SUITES:
+      return "NL80211_ATTR_CIPHER_SUITES"; break;
+    case NL80211_ATTR_FREQ_BEFORE:
+      return "NL80211_ATTR_FREQ_BEFORE"; break;
+    case NL80211_ATTR_FREQ_AFTER:
+      return "NL80211_ATTR_FREQ_AFTER"; break;
+    case NL80211_ATTR_FREQ_FIXED:
+      return "NL80211_ATTR_FREQ_FIXED"; break;
+    case NL80211_ATTR_WIPHY_RETRY_SHORT:
+      return "NL80211_ATTR_WIPHY_RETRY_SHORT"; break;
+    case NL80211_ATTR_WIPHY_RETRY_LONG:
+      return "NL80211_ATTR_WIPHY_RETRY_LONG"; break;
+    case NL80211_ATTR_WIPHY_FRAG_THRESHOLD:
+      return "NL80211_ATTR_WIPHY_FRAG_THRESHOLD"; break;
+    case NL80211_ATTR_WIPHY_RTS_THRESHOLD:
+      return "NL80211_ATTR_WIPHY_RTS_THRESHOLD"; break;
+    case NL80211_ATTR_TIMED_OUT:
+      return "NL80211_ATTR_TIMED_OUT"; break;
+    case NL80211_ATTR_USE_MFP:
+      return "NL80211_ATTR_USE_MFP"; break;
+    case NL80211_ATTR_STA_FLAGS2:
+      return "NL80211_ATTR_STA_FLAGS2"; break;
+    case NL80211_ATTR_CONTROL_PORT:
+      return "NL80211_ATTR_CONTROL_PORT"; break;
+    case NL80211_ATTR_TESTDATA:
+      return "NL80211_ATTR_TESTDATA"; break;
+    case NL80211_ATTR_PRIVACY:
+      return "NL80211_ATTR_PRIVACY"; break;
+    case NL80211_ATTR_DISCONNECTED_BY_AP:
+      return "NL80211_ATTR_DISCONNECTED_BY_AP"; break;
+    case NL80211_ATTR_STATUS_CODE:
+      return "NL80211_ATTR_STATUS_CODE"; break;
+    case NL80211_ATTR_CIPHER_SUITES_PAIRWISE:
+      return "NL80211_ATTR_CIPHER_SUITES_PAIRWISE"; break;
+    case NL80211_ATTR_CIPHER_SUITE_GROUP:
+      return "NL80211_ATTR_CIPHER_SUITE_GROUP"; break;
+    case NL80211_ATTR_WPA_VERSIONS:
+      return "NL80211_ATTR_WPA_VERSIONS"; break;
+    case NL80211_ATTR_AKM_SUITES:
+      return "NL80211_ATTR_AKM_SUITES"; break;
+    case NL80211_ATTR_REQ_IE:
+      return "NL80211_ATTR_REQ_IE"; break;
+    case NL80211_ATTR_RESP_IE:
+      return "NL80211_ATTR_RESP_IE"; break;
+    case NL80211_ATTR_PREV_BSSID:
+      return "NL80211_ATTR_PREV_BSSID"; break;
+    case NL80211_ATTR_KEY:
+      return "NL80211_ATTR_KEY"; break;
+    case NL80211_ATTR_KEYS:
+      return "NL80211_ATTR_KEYS"; break;
+    case NL80211_ATTR_PID:
+      return "NL80211_ATTR_PID"; break;
+    case NL80211_ATTR_4ADDR:
+      return "NL80211_ATTR_4ADDR"; break;
+    case NL80211_ATTR_SURVEY_INFO:
+      return "NL80211_ATTR_SURVEY_INFO"; break;
+    case NL80211_ATTR_PMKID:
+      return "NL80211_ATTR_PMKID"; break;
+    case NL80211_ATTR_MAX_NUM_PMKIDS:
+      return "NL80211_ATTR_MAX_NUM_PMKIDS"; break;
+    case NL80211_ATTR_DURATION:
+      return "NL80211_ATTR_DURATION"; break;
+    case NL80211_ATTR_COOKIE:
+      return "NL80211_ATTR_COOKIE"; break;
+    case NL80211_ATTR_WIPHY_COVERAGE_CLASS:
+      return "NL80211_ATTR_WIPHY_COVERAGE_CLASS"; break;
+    case NL80211_ATTR_TX_RATES:
+      return "NL80211_ATTR_TX_RATES"; break;
+    case NL80211_ATTR_FRAME_MATCH:
+      return "NL80211_ATTR_FRAME_MATCH"; break;
+    case NL80211_ATTR_ACK:
+      return "NL80211_ATTR_ACK"; break;
+    case NL80211_ATTR_PS_STATE:
+      return "NL80211_ATTR_PS_STATE"; break;
+    case NL80211_ATTR_CQM:
+      return "NL80211_ATTR_CQM"; break;
+    case NL80211_ATTR_LOCAL_STATE_CHANGE:
+      return "NL80211_ATTR_LOCAL_STATE_CHANGE"; break;
+    case NL80211_ATTR_AP_ISOLATE:
+      return "NL80211_ATTR_AP_ISOLATE"; break;
+    case NL80211_ATTR_WIPHY_TX_POWER_SETTING:
+      return "NL80211_ATTR_WIPHY_TX_POWER_SETTING"; break;
+    case NL80211_ATTR_WIPHY_TX_POWER_LEVEL:
+      return "NL80211_ATTR_WIPHY_TX_POWER_LEVEL"; break;
+    case NL80211_ATTR_TX_FRAME_TYPES:
+      return "NL80211_ATTR_TX_FRAME_TYPES"; break;
+    case NL80211_ATTR_RX_FRAME_TYPES:
+      return "NL80211_ATTR_RX_FRAME_TYPES"; break;
+    case NL80211_ATTR_FRAME_TYPE:
+      return "NL80211_ATTR_FRAME_TYPE"; break;
+    case NL80211_ATTR_CONTROL_PORT_ETHERTYPE:
+      return "NL80211_ATTR_CONTROL_PORT_ETHERTYPE"; break;
+    case NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT:
+      return "NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT"; break;
+    case NL80211_ATTR_SUPPORT_IBSS_RSN:
+      return "NL80211_ATTR_SUPPORT_IBSS_RSN"; break;
+    case NL80211_ATTR_WIPHY_ANTENNA_TX:
+      return "NL80211_ATTR_WIPHY_ANTENNA_TX"; break;
+    case NL80211_ATTR_WIPHY_ANTENNA_RX:
+      return "NL80211_ATTR_WIPHY_ANTENNA_RX"; break;
+    case NL80211_ATTR_MCAST_RATE:
+      return "NL80211_ATTR_MCAST_RATE"; break;
+    case NL80211_ATTR_OFFCHANNEL_TX_OK:
+      return "NL80211_ATTR_OFFCHANNEL_TX_OK"; break;
+    case NL80211_ATTR_BSS_HT_OPMODE:
+      return "NL80211_ATTR_BSS_HT_OPMODE"; break;
+    case NL80211_ATTR_KEY_DEFAULT_TYPES:
+      return "NL80211_ATTR_KEY_DEFAULT_TYPES"; break;
+    case NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION:
+      return "NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION"; break;
+    case NL80211_ATTR_MESH_SETUP:
+      return "NL80211_ATTR_MESH_SETUP"; break;
+    case NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX:
+      return "NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX"; break;
+    case NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX:
+      return "NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX"; break;
+    case NL80211_ATTR_SUPPORT_MESH_AUTH:
+      return "NL80211_ATTR_SUPPORT_MESH_AUTH"; break;
+    case NL80211_ATTR_STA_PLINK_STATE:
+      return "NL80211_ATTR_STA_PLINK_STATE"; break;
+    case NL80211_ATTR_WOWLAN_TRIGGERS:
+      return "NL80211_ATTR_WOWLAN_TRIGGERS"; break;
+    case NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED:
+      return "NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED"; break;
+    case NL80211_ATTR_SCHED_SCAN_INTERVAL:
+      return "NL80211_ATTR_SCHED_SCAN_INTERVAL"; break;
+    case NL80211_ATTR_INTERFACE_COMBINATIONS:
+      return "NL80211_ATTR_INTERFACE_COMBINATIONS"; break;
+    case NL80211_ATTR_SOFTWARE_IFTYPES:
+      return "NL80211_ATTR_SOFTWARE_IFTYPES"; break;
+    case NL80211_ATTR_REKEY_DATA:
+      return "NL80211_ATTR_REKEY_DATA"; break;
+    case NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS:
+      return "NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS"; break;
+    case NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN:
+      return "NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN"; break;
+    case NL80211_ATTR_SCAN_SUPP_RATES:
+      return "NL80211_ATTR_SCAN_SUPP_RATES"; break;
+    case NL80211_ATTR_HIDDEN_SSID:
+      return "NL80211_ATTR_HIDDEN_SSID"; break;
+    case NL80211_ATTR_IE_PROBE_RESP:
+      return "NL80211_ATTR_IE_PROBE_RESP"; break;
+    case NL80211_ATTR_IE_ASSOC_RESP:
+      return "NL80211_ATTR_IE_ASSOC_RESP"; break;
+    case NL80211_ATTR_STA_WME:
+      return "NL80211_ATTR_STA_WME"; break;
+    case NL80211_ATTR_SUPPORT_AP_UAPSD:
+      return "NL80211_ATTR_SUPPORT_AP_UAPSD"; break;
+    case NL80211_ATTR_ROAM_SUPPORT:
+      return "NL80211_ATTR_ROAM_SUPPORT"; break;
+    case NL80211_ATTR_SCHED_SCAN_MATCH:
+      return "NL80211_ATTR_SCHED_SCAN_MATCH"; break;
+    case NL80211_ATTR_MAX_MATCH_SETS:
+      return "NL80211_ATTR_MAX_MATCH_SETS"; break;
+    case NL80211_ATTR_PMKSA_CANDIDATE:
+      return "NL80211_ATTR_PMKSA_CANDIDATE"; break;
+    case NL80211_ATTR_TX_NO_CCK_RATE:
+      return "NL80211_ATTR_TX_NO_CCK_RATE"; break;
+    case NL80211_ATTR_TDLS_ACTION:
+      return "NL80211_ATTR_TDLS_ACTION"; break;
+    case NL80211_ATTR_TDLS_DIALOG_TOKEN:
+      return "NL80211_ATTR_TDLS_DIALOG_TOKEN"; break;
+    case NL80211_ATTR_TDLS_OPERATION:
+      return "NL80211_ATTR_TDLS_OPERATION"; break;
+    case NL80211_ATTR_TDLS_SUPPORT:
+      return "NL80211_ATTR_TDLS_SUPPORT"; break;
+    case NL80211_ATTR_TDLS_EXTERNAL_SETUP:
+      return "NL80211_ATTR_TDLS_EXTERNAL_SETUP"; break;
+    case NL80211_ATTR_DEVICE_AP_SME:
+      return "NL80211_ATTR_DEVICE_AP_SME"; break;
+    case NL80211_ATTR_DONT_WAIT_FOR_ACK:
+      return "NL80211_ATTR_DONT_WAIT_FOR_ACK"; break;
+    case NL80211_ATTR_FEATURE_FLAGS:
+      return "NL80211_ATTR_FEATURE_FLAGS"; break;
+    case NL80211_ATTR_PROBE_RESP_OFFLOAD:
+      return "NL80211_ATTR_PROBE_RESP_OFFLOAD"; break;
+    case NL80211_ATTR_PROBE_RESP:
+      return "NL80211_ATTR_PROBE_RESP"; break;
+    case NL80211_ATTR_DFS_REGION:
+      return "NL80211_ATTR_DFS_REGION"; break;
+    case NL80211_ATTR_DISABLE_HT:
+      return "NL80211_ATTR_DISABLE_HT"; break;
+    case NL80211_ATTR_HT_CAPABILITY_MASK:
+      return "NL80211_ATTR_HT_CAPABILITY_MASK"; break;
+    case NL80211_ATTR_NOACK_MAP:
+      return "NL80211_ATTR_NOACK_MAP"; break;
+    case NL80211_ATTR_INACTIVITY_TIMEOUT:
+      return "NL80211_ATTR_INACTIVITY_TIMEOUT"; break;
+    case NL80211_ATTR_RX_SIGNAL_DBM:
+      return "NL80211_ATTR_RX_SIGNAL_DBM"; break;
+    case NL80211_ATTR_BG_SCAN_PERIOD:
+      return "NL80211_ATTR_BG_SCAN_PERIOD"; break;
+    default:
+      return "<UNKNOWN>"; break;
+  }
+}
+
+// Protected members.
+
+// Duplicate attribute data, store in map indexed on |name|.
+bool UserBoundNlMessage::AddAttribute(enum nl80211_attrs name,
+                                      nlattr *data) {
+  if (ContainsKey(attributes_, name)) {
+    LOG(ERROR) << "Already have attribute name " << name;
+    return false;
+  }
+
+  if ((!data) || (nla_total_size(nla_len(data)) == 0)) {
+    attributes_[name] = NULL;
+  } else {
+    nlattr *newdata = reinterpret_cast<nlattr *>(
+        new uint8_t[nla_total_size(nla_len(data))]);
+    memcpy(newdata, data, nla_total_size(nla_len(data)));
+    attributes_[name] = newdata;
+  }
+  return true;
+}
+
+const nlattr *UserBoundNlMessage::GetAttribute(enum nl80211_attrs name)
+    const {
+  map<enum nl80211_attrs, nlattr *>::const_iterator match;
+  match = attributes_.find(name);
+  // This method may be called to explore the existence of the attribute so
+  // we'll not emit an error if it's not found.
+  if (match == attributes_.end()) {
+    return NULL;
+  }
+  return match->second;
+}
+
+string UserBoundNlMessage::GetHeaderString() const {
+  char ifname[IF_NAMESIZE] = "";
+  uint32_t ifindex = UINT32_MAX;
+  bool ifindex_exists = GetU32Attribute(NL80211_ATTR_IFINDEX, &ifindex);
+
+  uint32_t wifi = UINT32_MAX;
+  bool wifi_exists = GetU32Attribute(NL80211_ATTR_WIPHY, &wifi);
+
+  string output;
+  if (ifindex_exists && wifi_exists) {
+    StringAppendF(&output, "%s (phy #%" PRIu32 "): ",
+                  (if_indextoname(ifindex, ifname) ? ifname : "<unknown>"),
+                  wifi);
+  } else if (ifindex_exists) {
+    StringAppendF(&output, "%s: ",
+                  (if_indextoname(ifindex, ifname) ? ifname : "<unknown>"));
+  } else if (wifi_exists) {
+    StringAppendF(&output, "phy #%" PRIu32 "u: ", wifi);
+  }
+
+  return output;
+}
+
+string UserBoundNlMessage::StringFromFrame(enum nl80211_attrs attr_name) const {
+  string output;
+
+  void *rawdata = NULL;
+  int frame_byte_count = 0;
+  if (GetRawAttributeData(attr_name, &rawdata, &frame_byte_count) && rawdata) {
+    const uint8_t *frame_data = reinterpret_cast<const uint8_t *>(rawdata);
+
+    Nl80211Frame frame(frame_data, frame_byte_count);
+    frame.ToString(&output);
+  } else {
+    output.append(" [no frame]");
+  }
+
+  return output;
+}
+
+// static
+string UserBoundNlMessage::StringFromKeyType(nl80211_key_type key_type) {
+  switch (key_type) {
+  case NL80211_KEYTYPE_GROUP:
+    return "Group";
+  case NL80211_KEYTYPE_PAIRWISE:
+    return "Pairwise";
+  case NL80211_KEYTYPE_PEERKEY:
+    return "PeerKey";
+  default:
+    return "<Unknown Key Type>";
+  }
+}
+
+// static
+string UserBoundNlMessage::StringFromMacAddress(const uint8_t *arg) {
+  string output;
+
+  if (!arg) {
+    output = kBogusMacAddress;
+    LOG(ERROR) << "|arg| parameter is NULL.";
+  } else {
+    StringAppendF(&output, "%02x", arg[0]);
+
+    for (int i = 1; i < kEthernetAddressBytes ; ++i) {
+      StringAppendF(&output, ":%02x", arg[i]);
+    }
+  }
+  return output;
+}
+
+// static
+string UserBoundNlMessage::StringFromRegInitiator(__u8 initiator) {
+  switch (initiator) {
+  case NL80211_REGDOM_SET_BY_CORE:
+    return "the wireless core upon initialization";
+  case NL80211_REGDOM_SET_BY_USER:
+    return "a user";
+  case NL80211_REGDOM_SET_BY_DRIVER:
+    return "a driver";
+  case NL80211_REGDOM_SET_BY_COUNTRY_IE:
+    return "a country IE";
+  default:
+    return "<Unknown Reg Initiator>";
+  }
+}
+
+// static
+string UserBoundNlMessage::StringFromSsid(const uint8_t len,
+                                          const uint8_t *data) {
+  string output;
+  if (!data) {
+    StringAppendF(&output, "<Error from %s, NULL parameter>", __func__);
+    LOG(ERROR) << "|data| parameter is NULL.";
+    return output;
+  }
+
+  for (int i = 0; i < len; ++i) {
+    if (data[i] == ' ')
+      output.append(" ");
+    else if (isprint(data[i]))
+      StringAppendF(&output, "%c", static_cast<char>(data[i]));
+    else
+      StringAppendF(&output, "\\x%2x", data[i]);
+  }
+
+  return output;
+}
+
+// static
+string UserBoundNlMessage::StringFromStatus(uint16_t status) {
+  map<uint16_t, string>::const_iterator match;
+  match = connect_status_map_->find(status);
+  if (match == connect_status_map_->end()) {
+    string output;
+    StringAppendF(&output, "<Unknown Status:%u>", status);
+    return output;
+  }
+  return match->second;
+}
+
+Nl80211Frame::Nl80211Frame(const uint8_t *raw_frame, int frame_byte_count) :
+    frame_type_(kIllegalFrameType), status_(0), frame_(0), byte_count_(0) {
+  if (raw_frame == NULL)
+    return;
+
+  frame_ = new uint8_t[frame_byte_count];
+  memcpy(frame_, raw_frame, frame_byte_count);
+  byte_count_ = frame_byte_count;
+  const IEEE_80211::ieee80211_frame *frame =
+      reinterpret_cast<const IEEE_80211::ieee80211_frame *>(frame_);
+
+  // Now, let's populate the other stuff.
+  if (frame_byte_count >= kMinimumFrameByteCount) {
+    mac_from_ =
+        UserBoundNlMessage::StringFromMacAddress(&frame->destination_mac[0]);
+    mac_to_ = UserBoundNlMessage::StringFromMacAddress(&frame->source_mac[0]);
+    frame_type_ = frame->frame_control & kFrameTypeMask;
+
+    switch (frame_type_) {
+    case kAssocResponseFrameType:
+    case kReassocResponseFrameType:
+      status_ = le16toh(frame->u.associate_response.status_code);
+      break;
+
+    case kAuthFrameType:
+      status_ = le16toh(frame->u.authentiate_message.status_code);
+      break;
+
+    case kDisassocFrameType:
+    case kDeauthFrameType:
+      status_ = le16toh(frame->u.deauthentiate_message.reason_code);
+      break;
+
+    default:
+      break;
+    }
+  }
+}
+
+Nl80211Frame::~Nl80211Frame() {
+  delete [] frame_;
+  frame_ = NULL;
+}
+
+bool Nl80211Frame::ToString(string *output) {
+  if (!output) {
+    LOG(ERROR) << "NULL |output|";
+    return false;
+  }
+
+  if ((byte_count_ == 0) || (frame_ == reinterpret_cast<uint8_t *>(NULL))) {
+    output->append(" [no frame]");
+    return true;
+  }
+
+  if (byte_count_ < kMinimumFrameByteCount) {
+    output->append(" [invalid frame: ");
+  } else {
+    StringAppendF(output, " %s -> %s", mac_from_.c_str(), mac_to_.c_str());
+
+    switch (frame_[0] & kFrameTypeMask) {
+    case kAssocResponseFrameType:
+      StringAppendF(output, "; AssocResponse status: %u: %s",
+                    status_,
+                    UserBoundNlMessage::StringFromStatus(status_).c_str());
+      break;
+    case kReassocResponseFrameType:
+      StringAppendF(output, "; ReassocResponse status: %u: %s",
+                    status_,
+                    UserBoundNlMessage::StringFromStatus(status_).c_str());
+      break;
+    case kAuthFrameType:
+      StringAppendF(output, "; Auth status: %u: %s",
+                    status_,
+                    UserBoundNlMessage::StringFromStatus(status_).c_str());
+      break;
+
+    case kDisassocFrameType:
+      StringAppendF(output, "; Disassoc reason %u: %s",
+                    status_,
+                    UserBoundNlMessage::StringFromStatus(status_).c_str());
+      break;
+    case kDeauthFrameType:
+      StringAppendF(output, "; Deauth reason %u: %s",
+                    status_,
+                    UserBoundNlMessage::StringFromStatus(status_).c_str());
+      break;
+
+    default:
+      break;
+    }
+    output->append(" [frame: ");
+  }
+
+  for (int i = 0; i < byte_count_; ++i) {
+    StringAppendF(output, "%02x, ", frame_[i]);
+  }
+  output->append("]");
+
+  return true;
+}
+
+bool Nl80211Frame::IsEqual(const Nl80211Frame &other) {
+  if (byte_count_ != other.byte_count_) {
+    return false;
+  }
+
+  for (int i = 0; i < byte_count_; ++i) {
+    if (frame_[i] != other.frame_[i]) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+//
+// Specific UserBoundNlMessage types.
+//
+
+const uint8_t AssociateMessage::kCommand = NL80211_CMD_ASSOCIATE;
+const char AssociateMessage::kCommandString[] = "NL80211_CMD_ASSOCIATE";
+
+string AssociateMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("assoc");
+  if (AttributeExists(NL80211_ATTR_FRAME))
+    output.append(StringFromFrame(NL80211_ATTR_FRAME));
+  else if (AttributeExists(NL80211_ATTR_TIMED_OUT))
+    output.append(": timed out");
+  else
+    output.append(": unknown event");
+  return output;
+}
+
+const uint8_t AuthenticateMessage::kCommand = NL80211_CMD_AUTHENTICATE;
+const char AuthenticateMessage::kCommandString[] = "NL80211_CMD_AUTHENTICATE";
+
+string AuthenticateMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("auth");
+  if (AttributeExists(NL80211_ATTR_FRAME)) {
+    output.append(StringFromFrame(NL80211_ATTR_FRAME));
+  } else {
+    output.append(AttributeExists(NL80211_ATTR_TIMED_OUT) ?
+                  ": timed out" : ": unknown event");
+  }
+  return output;
+}
+
+const uint8_t CancelRemainOnChannelMessage::kCommand =
+  NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL;
+const char CancelRemainOnChannelMessage::kCommandString[] =
+  "NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL";
+
+string CancelRemainOnChannelMessage::ToString() const {
+  string output(GetHeaderString());
+  uint32_t freq;
+  uint64_t cookie;
+  StringAppendF(&output,
+                "done with remain on freq %" PRIu32 " (cookie %" PRIx64 ")",
+                (GetU32Attribute(NL80211_ATTR_WIPHY_FREQ, &freq) ? 0 : freq),
+                (GetU64Attribute(NL80211_ATTR_COOKIE, &cookie) ? 0 : cookie));
+  return output;
+}
+
+const uint8_t ConnectMessage::kCommand = NL80211_CMD_CONNECT;
+const char ConnectMessage::kCommandString[] = "NL80211_CMD_CONNECT";
+
+string ConnectMessage::ToString() const {
+  string output(GetHeaderString());
+
+  uint16_t status = UINT16_MAX;
+
+  if (!GetU16Attribute(NL80211_ATTR_STATUS_CODE, &status)) {
+    output.append("unknown connect status");
+  } else if (status == 0) {
+    output.append("connected");
+  } else {
+    output.append("failed to connect");
+  }
+
+  if (AttributeExists(NL80211_ATTR_MAC)) {
+    string mac;
+    GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+    StringAppendF(&output, " to %s", mac.c_str());
+  }
+  if (status)
+    StringAppendF(&output, ", status: %u: %s", status,
+                  StringFromStatus(status).c_str());
+  return output;
+}
+
+const uint8_t DeauthenticateMessage::kCommand = NL80211_CMD_DEAUTHENTICATE;
+const char DeauthenticateMessage::kCommandString[] =
+    "NL80211_CMD_DEAUTHENTICATE";
+
+string DeauthenticateMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "deauth%s",
+                StringFromFrame(NL80211_ATTR_FRAME).c_str());
+  return output;
+}
+
+const uint8_t DeleteStationMessage::kCommand = NL80211_CMD_DEL_STATION;
+const char DeleteStationMessage::kCommandString[] = "NL80211_CMD_DEL_STATION";
+
+string DeleteStationMessage::ToString() const {
+  string mac;
+  GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+  string output(GetHeaderString());
+  StringAppendF(&output, "del station %s", mac.c_str());
+  return output;
+}
+
+const uint8_t DisassociateMessage::kCommand = NL80211_CMD_DISASSOCIATE;
+const char DisassociateMessage::kCommandString[] = "NL80211_CMD_DISASSOCIATE";
+
+string DisassociateMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "disassoc%s",
+                StringFromFrame(NL80211_ATTR_FRAME).c_str());
+  return output;
+}
+
+const uint8_t DisconnectMessage::kCommand = NL80211_CMD_DISCONNECT;
+const char DisconnectMessage::kCommandString[] = "NL80211_CMD_DISCONNECT";
+
+string DisconnectMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "disconnected %s",
+                ((AttributeExists(NL80211_ATTR_DISCONNECTED_BY_AP)) ?
+                  "(by AP)" : "(local request)"));
+
+  uint16_t reason = UINT16_MAX;
+  if (GetU16Attribute(NL80211_ATTR_REASON_CODE, &reason)) {
+    StringAppendF(&output, " reason: %u: %s",
+                  reason, StringFromStatus(reason).c_str());
+  }
+  return output;
+}
+
+const uint8_t FrameTxStatusMessage::kCommand = NL80211_CMD_FRAME_TX_STATUS;
+const char FrameTxStatusMessage::kCommandString[] =
+    "NL80211_CMD_FRAME_TX_STATUS";
+
+string FrameTxStatusMessage::ToString() const {
+  string output(GetHeaderString());
+  uint64_t cookie = UINT64_MAX;
+  GetU64Attribute(NL80211_ATTR_COOKIE, &cookie);
+
+  StringAppendF(&output, "mgmt TX status (cookie %" PRIx64 "): %s",
+                cookie,
+                (AttributeExists(NL80211_ATTR_ACK) ? "acked" : "no ack"));
+  return output;
+}
+
+const uint8_t JoinIbssMessage::kCommand = NL80211_CMD_JOIN_IBSS;
+const char JoinIbssMessage::kCommandString[] = "NL80211_CMD_JOIN_IBSS";
+
+string JoinIbssMessage::ToString() const {
+  string mac;
+  GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+  string output(GetHeaderString());
+  StringAppendF(&output, "IBSS %s joined", mac.c_str());
+  return output;
+}
+
+const uint8_t MichaelMicFailureMessage::kCommand =
+    NL80211_CMD_MICHAEL_MIC_FAILURE;
+const char MichaelMicFailureMessage::kCommandString[] =
+    "NL80211_CMD_MICHAEL_MIC_FAILURE";
+
+string MichaelMicFailureMessage::ToString() const {
+  string output(GetHeaderString());
+
+  output.append("Michael MIC failure event:");
+
+  if (AttributeExists(NL80211_ATTR_MAC)) {
+    string mac;
+    GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+    StringAppendF(&output, " source MAC address %s", mac.c_str());
+  }
+
+  if (AttributeExists(NL80211_ATTR_KEY_SEQ)) {
+    void *rawdata = NULL;
+    int length = 0;
+    if (GetRawAttributeData(NL80211_ATTR_KEY_SEQ, &rawdata, &length) &&
+        rawdata && length == 6) {
+      const unsigned char *seq = reinterpret_cast<const unsigned char *>(
+          rawdata);
+      StringAppendF(&output, " seq=%02x%02x%02x%02x%02x%02x",
+                    seq[0], seq[1], seq[2], seq[3], seq[4], seq[5]);
+    }
+  }
+  uint32_t key_type_val = UINT32_MAX;
+  if (GetU32Attribute(NL80211_ATTR_KEY_TYPE, &key_type_val)) {
+    enum nl80211_key_type key_type =
+        static_cast<enum nl80211_key_type >(key_type_val);
+    StringAppendF(&output, " Key Type %s", StringFromKeyType(key_type).c_str());
+  }
+
+  uint8_t key_index = UINT8_MAX;
+  if (GetU8Attribute(NL80211_ATTR_KEY_IDX, &key_index)) {
+    StringAppendF(&output, " Key Id %u", key_index);
+  }
+
+  return output;
+}
+
+const uint8_t NewScanResultsMessage::kCommand = NL80211_CMD_NEW_SCAN_RESULTS;
+const char NewScanResultsMessage::kCommandString[] =
+    "NL80211_CMD_NEW_SCAN_RESULTS";
+
+string NewScanResultsMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("scan finished");
+
+  {
+    output.append("; frequencies: ");
+    vector<uint32_t> list;
+    if (GetScanFrequenciesAttribute(NL80211_ATTR_SCAN_FREQUENCIES, &list)) {
+      string str;
+      for (vector<uint32_t>::const_iterator i = list.begin();
+             i != list.end(); ++i) {
+        StringAppendF(&str, " %" PRIu32 ", ", *i);
+      }
+      output.append(str);
+    }
+  }
+
+  {
+    output.append("; SSIDs: ");
+    vector<string> list;
+    if (GetScanSsidsAttribute(NL80211_ATTR_SCAN_SSIDS, &list)) {
+      string str;
+      for (vector<string>::const_iterator i = list.begin();
+           i != list.end(); ++i) {
+        StringAppendF(&str, "\"%s\", ", i->c_str());
+      }
+      output.append(str);
+    }
+  }
+
+  return output;
+}
+
+const uint8_t NewStationMessage::kCommand = NL80211_CMD_NEW_STATION;
+const char NewStationMessage::kCommandString[] = "NL80211_CMD_NEW_STATION";
+
+string NewStationMessage::ToString() const {
+  string mac;
+  GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+  string output(GetHeaderString());
+  StringAppendF(&output, "new station %s", mac.c_str());
+
+  return output;
+}
+
+const uint8_t NewWifiMessage::kCommand = NL80211_CMD_NEW_WIPHY;
+const char NewWifiMessage::kCommandString[] = "NL80211_CMD_NEW_WIPHY";
+
+string NewWifiMessage::ToString() const {
+  string output(GetHeaderString());
+  string wifi_name = "None";
+  GetStringAttribute(NL80211_ATTR_WIPHY_NAME, &wifi_name);
+  StringAppendF(&output, "renamed to %s", wifi_name.c_str());
+  return output;
+}
+
+const uint8_t NotifyCqmMessage::kCommand = NL80211_CMD_NOTIFY_CQM;
+const char NotifyCqmMessage::kCommandString[] = "NL80211_CMD_NOTIFY_CQM";
+
+string NotifyCqmMessage::ToString() const {
+  static const nla_policy kCqmPolicy[NL80211_ATTR_CQM_MAX + 1] = {
+    { NLA_U32, 0, 0 },  // Who Knows?
+    { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_THOLD]
+    { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_HYST]
+    { NLA_U32, 0, 0 },  // [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]
+  };
+
+  string output(GetHeaderString());
+  output.append("connection quality monitor event: ");
+
+  const nlattr *const_data = GetAttribute(NL80211_ATTR_CQM);
+  nlattr *cqm_attr = const_cast<nlattr *>(const_data);
+
+  nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
+  if (!AttributeExists(NL80211_ATTR_CQM) || !cqm_attr ||
+      nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, cqm_attr,
+                       const_cast<nla_policy *>(kCqmPolicy))) {
+    output.append("missing data!");
+    return output;
+  }
+  if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]) {
+    enum nl80211_cqm_rssi_threshold_event rssi_event =
+        static_cast<enum nl80211_cqm_rssi_threshold_event>(
+          nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]));
+    if (rssi_event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH)
+      output.append("RSSI went above threshold");
+    else
+      output.append("RSSI went below threshold");
+  } else if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT] &&
+       AttributeExists(NL80211_ATTR_MAC)) {
+    string mac;
+    GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+    StringAppendF(&output, "peer %s didn't ACK %" PRIu32 " packets",
+                  mac.c_str(),
+                  nla_get_u32(cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]));
+  } else {
+    output.append("unknown event");
+  }
+
+  return output;
+}
+
+const uint8_t PmksaCandidateMessage::kCommand = NL80211_ATTR_PMKSA_CANDIDATE;
+const char PmksaCandidateMessage::kCommandString[] =
+  "NL80211_ATTR_PMKSA_CANDIDATE";
+
+string PmksaCandidateMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("PMKSA candidate found");
+  return output;
+}
+
+const uint8_t RegBeaconHintMessage::kCommand = NL80211_CMD_REG_BEACON_HINT;
+const char RegBeaconHintMessage::kCommandString[] =
+    "NL80211_CMD_REG_BEACON_HINT";
+
+string RegBeaconHintMessage::ToString() const {
+  string output(GetHeaderString());
+  uint32_t wiphy_idx = UINT32_MAX;
+  GetU32Attribute(NL80211_ATTR_WIPHY, &wiphy_idx);
+
+  const nlattr *const_before = GetAttribute(NL80211_ATTR_FREQ_BEFORE);
+  ieee80211_beacon_channel chan_before_beacon;
+  memset(&chan_before_beacon, 0, sizeof(chan_before_beacon));
+  if (ParseBeaconHintChan(const_before, &chan_before_beacon))
+    return "";
+
+  const nlattr *const_after = GetAttribute(NL80211_ATTR_FREQ_AFTER);
+  ieee80211_beacon_channel chan_after_beacon;
+  memset(&chan_after_beacon, 0, sizeof(chan_after_beacon));
+  if (ParseBeaconHintChan(const_after, &chan_after_beacon))
+    return "";
+
+  if (chan_before_beacon.center_freq != chan_after_beacon.center_freq)
+    return "";
+
+  /* A beacon hint is sent _only_ if something _did_ change */
+  output.append("beacon hint:");
+  StringAppendF(&output, "phy%" PRIu32 " %u MHz [%d]:",
+                wiphy_idx, chan_before_beacon.center_freq,
+                ChannelFromIeee80211Frequency(chan_before_beacon.center_freq));
+
+  if (chan_before_beacon.passive_scan && !chan_after_beacon.passive_scan)
+    output.append("\to active scanning enabled");
+  if (chan_before_beacon.no_ibss && !chan_after_beacon.no_ibss)
+    output.append("\to beaconing enabled");
+  return output;
+}
+
+int RegBeaconHintMessage::ParseBeaconHintChan(const nlattr *tb,
+                                              ieee80211_beacon_channel *chan)
+    const {
+  static const nla_policy kBeaconFreqPolicy[
+      NL80211_FREQUENCY_ATTR_MAX + 1] = {
+        {0, 0, 0},
+        { NLA_U32, 0, 0 },  // [NL80211_FREQUENCY_ATTR_FREQ]
+        {0, 0, 0},
+        { NLA_FLAG, 0, 0 },  // [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN]
+        { NLA_FLAG, 0, 0 },  // [NL80211_FREQUENCY_ATTR_NO_IBSS]
+  };
+
+  if (!tb) {
+    LOG(ERROR) << "|tb| parameter is NULL.";
+    return -EINVAL;
+  }
+
+  if (!chan) {
+    LOG(ERROR) << "|chan| parameter is NULL.";
+    return -EINVAL;
+  }
+
+  nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
+
+  if (nla_parse_nested(tb_freq,
+                       NL80211_FREQUENCY_ATTR_MAX,
+                       const_cast<nlattr *>(tb),
+                       const_cast<nla_policy *>(kBeaconFreqPolicy)))
+    return -EINVAL;
+
+  chan->center_freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
+
+  if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
+    chan->passive_scan = true;
+  if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
+    chan->no_ibss = true;
+
+  return 0;
+}
+
+int RegBeaconHintMessage::ChannelFromIeee80211Frequency(int freq) {
+  // TODO(wdg): get rid of these magic numbers.
+  if (freq == 2484)
+    return 14;
+
+  if (freq < 2484)
+    return (freq - 2407) / 5;
+
+  /* FIXME: dot11ChannelStartingFactor (802.11-2007 17.3.8.3.2) */
+  return freq/5 - 1000;
+}
+
+const uint8_t RegChangeMessage::kCommand = NL80211_CMD_REG_CHANGE;
+const char RegChangeMessage::kCommandString[] = "NL80211_CMD_REG_CHANGE";
+
+string RegChangeMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("regulatory domain change: ");
+
+  uint8_t reg_type = UINT8_MAX;
+  GetU8Attribute(NL80211_ATTR_REG_TYPE, &reg_type);
+
+  uint32_t initiator = UINT32_MAX;
+  GetU32Attribute(NL80211_ATTR_REG_INITIATOR, &initiator);
+
+  uint32_t wifi = UINT32_MAX;
+  bool wifi_exists = GetU32Attribute(NL80211_ATTR_WIPHY, &wifi);
+
+  string alpha2 = "<None>";
+  GetStringAttribute(NL80211_ATTR_REG_ALPHA2, &alpha2);
+
+  switch (reg_type) {
+  case NL80211_REGDOM_TYPE_COUNTRY:
+    StringAppendF(&output, "set to %s by %s request",
+                  alpha2.c_str(), StringFromRegInitiator(initiator).c_str());
+    if (wifi_exists)
+      StringAppendF(&output, " on phy%" PRIu32, wifi);
+    break;
+
+  case NL80211_REGDOM_TYPE_WORLD:
+    StringAppendF(&output, "set to world roaming by %s request",
+                  StringFromRegInitiator(initiator).c_str());
+    break;
+
+  case NL80211_REGDOM_TYPE_CUSTOM_WORLD:
+    StringAppendF(&output,
+                  "custom world roaming rules in place on phy%" PRIu32
+                  " by %s request",
+                  wifi, StringFromRegInitiator(initiator).c_str());
+    break;
+
+  case NL80211_REGDOM_TYPE_INTERSECTION:
+    StringAppendF(&output, "intersection used due to a request made by %s",
+                  StringFromRegInitiator(initiator).c_str());
+    if (wifi_exists)
+      StringAppendF(&output, " on phy%" PRIu32, wifi);
+    break;
+
+  default:
+    output.append("unknown source");
+    break;
+  }
+  return output;
+}
+
+const uint8_t RemainOnChannelMessage::kCommand = NL80211_CMD_REMAIN_ON_CHANNEL;
+const char RemainOnChannelMessage::kCommandString[] =
+    "NL80211_CMD_REMAIN_ON_CHANNEL";
+
+string RemainOnChannelMessage::ToString() const {
+  string output(GetHeaderString());
+
+  uint32_t wifi_freq = UINT32_MAX;
+  GetU32Attribute(NL80211_ATTR_WIPHY_FREQ, &wifi_freq);
+
+  uint32_t duration = UINT32_MAX;
+  GetU32Attribute(NL80211_ATTR_DURATION, &duration);
+
+  uint64_t cookie = UINT64_MAX;
+  GetU64Attribute(NL80211_ATTR_COOKIE, &cookie);
+
+  StringAppendF(&output, "remain on freq %" PRIu32 " (%" PRIu32 "ms, cookie %"
+                PRIx64 ")",
+                wifi_freq, duration, cookie);
+  return output;
+}
+
+const uint8_t RoamMessage::kCommand = NL80211_CMD_ROAM;
+const char RoamMessage::kCommandString[] = "NL80211_CMD_ROAM";
+
+string RoamMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("roamed");
+
+  if (AttributeExists(NL80211_ATTR_MAC)) {
+    string mac;
+    GetMacAttributeString(NL80211_ATTR_MAC, &mac);
+    StringAppendF(&output, " to %s", mac.c_str());
+  }
+  return output;
+}
+
+const uint8_t ScanAbortedMessage::kCommand = NL80211_CMD_SCAN_ABORTED;
+const char ScanAbortedMessage::kCommandString[] = "NL80211_CMD_SCAN_ABORTED";
+
+string ScanAbortedMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("scan aborted");
+
+  {
+    output.append("; frequencies: ");
+    vector<uint32_t> list;
+    if (GetScanFrequenciesAttribute(NL80211_ATTR_SCAN_FREQUENCIES, &list)) {
+      string str;
+      for (vector<uint32_t>::const_iterator i = list.begin();
+           i != list.end(); ++i) {
+        StringAppendF(&str, " %" PRIu32 ", ", *i);
+      }
+      output.append(str);
+    }
+  }
+
+  {
+    output.append("; SSIDs: ");
+    vector<string> list;
+    if (GetScanSsidsAttribute(NL80211_ATTR_SCAN_SSIDS, &list)) {
+      string str;
+      for (vector<string>::const_iterator i = list.begin();
+           i != list.end(); ++i) {
+        StringAppendF(&str, "\"%s\", ", i->c_str());
+      }
+      output.append(str);
+    }
+  }
+
+  return output;
+}
+
+const uint8_t TriggerScanMessage::kCommand = NL80211_CMD_TRIGGER_SCAN;
+const char TriggerScanMessage::kCommandString[] = "NL80211_CMD_TRIGGER_SCAN";
+
+string TriggerScanMessage::ToString() const {
+  string output(GetHeaderString());
+  output.append("scan started");
+
+  {
+    output.append("; frequencies: ");
+    vector<uint32_t> list;
+    if (GetScanFrequenciesAttribute(NL80211_ATTR_SCAN_FREQUENCIES, &list)) {
+      string str;
+      for (vector<uint32_t>::const_iterator i = list.begin();
+             i != list.end(); ++i) {
+        StringAppendF(&str, "%" PRIu32 ", ", *i);
+      }
+      output.append(str);
+    }
+  }
+
+  {
+    output.append("; SSIDs: ");
+    vector<string> list;
+    if (GetScanSsidsAttribute(NL80211_ATTR_SCAN_SSIDS, &list)) {
+      string str;
+      for (vector<string>::const_iterator i = list.begin();
+           i != list.end(); ++i) {
+        StringAppendF(&str, "\"%s\", ", i->c_str());
+      }
+      output.append(str);
+    }
+  }
+
+  return output;
+}
+
+const uint8_t UnknownMessage::kCommand = 0xff;
+const char UnknownMessage::kCommandString[] = "<Unknown Message Type>";
+
+string UnknownMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "unknown event %u", command_);
+  return output;
+}
+
+const uint8_t UnprotDeauthenticateMessage::kCommand =
+    NL80211_CMD_UNPROT_DEAUTHENTICATE;
+const char UnprotDeauthenticateMessage::kCommandString[] =
+    "NL80211_CMD_UNPROT_DEAUTHENTICATE";
+
+string UnprotDeauthenticateMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "unprotected deauth %s",
+                StringFromFrame(NL80211_ATTR_FRAME).c_str());
+  return output;
+}
+
+const uint8_t UnprotDisassociateMessage::kCommand =
+    NL80211_CMD_UNPROT_DISASSOCIATE;
+const char UnprotDisassociateMessage::kCommandString[] =
+    "NL80211_CMD_UNPROT_DISASSOCIATE";
+
+string UnprotDisassociateMessage::ToString() const {
+  string output(GetHeaderString());
+  StringAppendF(&output, "unprotected disassoc %s",
+                StringFromFrame(NL80211_ATTR_FRAME).c_str());
+  return output;
+}
+
+//
+// Factory class.
+//
+
+UserBoundNlMessage *UserBoundNlMessageFactory::CreateMessage(nlmsghdr *msg) {
+  if (!msg) {
+    LOG(ERROR) << "NULL |msg| parameter";
+    return NULL;
+  }
+
+  scoped_ptr<UserBoundNlMessage> message;
+  genlmsghdr *gnlh =
+      reinterpret_cast<genlmsghdr *>(nlmsg_data(msg));
+
+  if (!gnlh) {
+    LOG(ERROR) << "NULL gnlh";
+    return NULL;
+  }
+
+  switch (gnlh->cmd) {
+    case AssociateMessage::kCommand:
+      message.reset(new AssociateMessage()); break;
+    case AuthenticateMessage::kCommand:
+      message.reset(new AuthenticateMessage()); break;
+    case CancelRemainOnChannelMessage::kCommand:
+      message.reset(new CancelRemainOnChannelMessage()); break;
+    case ConnectMessage::kCommand:
+      message.reset(new ConnectMessage()); break;
+    case DeauthenticateMessage::kCommand:
+      message.reset(new DeauthenticateMessage()); break;
+
+#if 0
+    // TODO(wdg): our version of 'iw' doesn't have this so I can't put it in
+    // without breaking the diff.  Remove the 'if 0' after the unit tests are
+    // added.
+    case DeleteStationMessage::kCommand:
+      message.reset(new DeleteStationMessage()); break;
+#endif
+
+    case DisassociateMessage::kCommand:
+      message.reset(new DisassociateMessage()); break;
+    case DisconnectMessage::kCommand:
+      message.reset(new DisconnectMessage()); break;
+    case FrameTxStatusMessage::kCommand:
+      message.reset(new FrameTxStatusMessage()); break;
+    case JoinIbssMessage::kCommand:
+      message.reset(new JoinIbssMessage()); break;
+    case MichaelMicFailureMessage::kCommand:
+      message.reset(new MichaelMicFailureMessage()); break;
+    case NewScanResultsMessage::kCommand:
+      message.reset(new NewScanResultsMessage()); break;
+    case NewStationMessage::kCommand:
+      message.reset(new NewStationMessage()); break;
+    case NewWifiMessage::kCommand:
+      message.reset(new NewWifiMessage()); break;
+    case NotifyCqmMessage::kCommand:
+      message.reset(new NotifyCqmMessage()); break;
+    case PmksaCandidateMessage::kCommand:
+      message.reset(new PmksaCandidateMessage()); break;
+    case RegBeaconHintMessage::kCommand:
+      message.reset(new RegBeaconHintMessage()); break;
+    case RegChangeMessage::kCommand:
+      message.reset(new RegChangeMessage()); break;
+    case RemainOnChannelMessage::kCommand:
+      message.reset(new RemainOnChannelMessage()); break;
+    case RoamMessage::kCommand:
+      message.reset(new RoamMessage()); break;
+    case ScanAbortedMessage::kCommand:
+      message.reset(new ScanAbortedMessage()); break;
+    case TriggerScanMessage::kCommand:
+      message.reset(new TriggerScanMessage()); break;
+    case UnprotDeauthenticateMessage::kCommand:
+      message.reset(new UnprotDeauthenticateMessage()); break;
+    case UnprotDisassociateMessage::kCommand:
+      message.reset(new UnprotDisassociateMessage()); break;
+
+    default:
+      message.reset(new UnknownMessage(gnlh->cmd)); break;
+      break;
+  }
+
+  nlattr *tb[NL80211_ATTR_MAX + 1];
+
+  // Parse the attributes from the nl message payload (which starts at the
+  // header) into the 'tb' array.
+  nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
+    genlmsg_attrlen(gnlh, 0), NULL);
+
+  if (!message->Init(tb, msg)) {
+    LOG(ERROR) << "Message did not initialize properly";
+    return NULL;
+  }
+
+//#if 0  // If we're collecting data for unit tests, uncommnet this.
+  UserBoundNlMessageDataCollector::GetInstance()->CollectDebugData(*message,
+                                                                   msg);
+//#endif // 0
+
+  return message.release();
+}
+
+UserBoundNlMessageDataCollector *
+    UserBoundNlMessageDataCollector::GetInstance() {
+  return g_datacollector.Pointer();
+}
+
+UserBoundNlMessageDataCollector::UserBoundNlMessageDataCollector() {
+  need_to_print[NL80211_ATTR_PMKSA_CANDIDATE] = true;
+  need_to_print[NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL] = true;
+  need_to_print[NL80211_CMD_DEL_STATION] = true;
+  need_to_print[NL80211_CMD_FRAME_TX_STATUS] = true;
+  need_to_print[NL80211_CMD_JOIN_IBSS] = true;
+  need_to_print[NL80211_CMD_MICHAEL_MIC_FAILURE] = true;
+  need_to_print[NL80211_CMD_NEW_WIPHY] = true;
+  need_to_print[NL80211_CMD_REG_BEACON_HINT] = true;
+  need_to_print[NL80211_CMD_REG_CHANGE] = true;
+  need_to_print[NL80211_CMD_REMAIN_ON_CHANNEL] = true;
+  need_to_print[NL80211_CMD_ROAM] = true;
+  need_to_print[NL80211_CMD_SCAN_ABORTED] = true;
+  need_to_print[NL80211_CMD_UNPROT_DEAUTHENTICATE] = true;
+  need_to_print[NL80211_CMD_UNPROT_DISASSOCIATE] = true;
+}
+
+void UserBoundNlMessageDataCollector::CollectDebugData(
+    const UserBoundNlMessage &message, nlmsghdr *msg)
+{
+  if (!msg) {
+    LOG(ERROR) << "NULL |msg| parameter";
+    return;
+  }
+
+  bool doit = false;
+
+  map<uint8_t, bool>::const_iterator node;
+  node = need_to_print.find(message.GetMessageType());
+  if (node != need_to_print.end())
+    doit = node->second;
+
+  if (doit) {
+    LOG(ERROR) << "@@const unsigned char "
+               << "k" << message.GetMessageTypeString()
+               << "[] = { ";
+
+    int payload_bytes = nlmsg_len(msg);
+
+    size_t bytes = nlmsg_total_size(payload_bytes);
+    unsigned char *rawdata = reinterpret_cast<unsigned char *>(msg);
+    for (size_t i=0; i<bytes; ++i) {
+      LOG(ERROR) << "  0x"
+                 << std::hex << std::setfill('0') << std::setw(2)
+                 << + rawdata[i] << ",";
+    }
+    LOG(ERROR) << "};";
+    need_to_print[message.GetMessageType()] = false;
+  }
+}
+
+}  // namespace shill.
diff --git a/user_bound_nlmessage.h b/user_bound_nlmessage.h
new file mode 100644
index 0000000..e3a9427
--- /dev/null
+++ b/user_bound_nlmessage.h
@@ -0,0 +1,778 @@
+// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef SHILL_USER_BOUND_NLMESSAGE_H_
+#define SHILL_USER_BOUND_NLMESSAGE_H_
+
+#include <iomanip>
+#include <map>
+#include <vector>
+#include <string>
+
+#include <base/basictypes.h>
+#include <base/bind.h>
+#include <base/lazy_instance.h>
+#include <gtest/gtest.h>
+
+#include <linux/nl80211.h>
+
+struct nlattr;
+struct nlmsghdr;
+
+namespace shill {
+
+// Class for messages received from libnl.
+class UserBoundNlMessage {
+ public:
+  enum Type {
+    kTypeUnspecified,
+    kTypeU8,
+    kTypeU16,
+    kTypeU32,
+    kTypeU64,
+    kTypeString,
+    kTypeFlag,
+    kTypeMsecs,
+    kTypeNested,
+    kTypeOther,  // Specified in the message but not listed, here.
+    kTypeError
+  };
+  // TODO(wdg): break 'Attribute' into its own class to handle
+  // nested attributes better.
+
+  // A const iterator to the attribute names in the attributes_ map of a
+  // UserBoundNlMessage.  The purpose, here, is to hide the way that the
+  // attribute is stored.
+  class AttributeNameIterator {
+   public:
+    explicit AttributeNameIterator(const std::map<nl80211_attrs,
+                                                  nlattr *> &map_param)
+        : map_(map_param) {
+      iter_ = map_.begin();
+    }
+
+    // Causes the iterator to point to the next attribute in the list.
+    void Advance() { ++iter_; }
+
+    // Returns 'true' if the iterator points beyond the last attribute in the
+    // list; returns 'false' otherwise.
+    bool AtEnd() const { return iter_ == map_.end(); }
+
+    // Returns the attribute name (which is actually an 'enum' value).
+    nl80211_attrs GetName() const { return iter_->first; }
+
+   private:
+    const std::map<nl80211_attrs, nlattr *> &map_;
+    std::map<nl80211_attrs, nlattr *>::const_iterator iter_;
+
+    DISALLOW_COPY_AND_ASSIGN(AttributeNameIterator);
+  };
+
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+  static const char kBogusMacAddress[];
+
+  UserBoundNlMessage() : message_(NULL) { }
+  virtual ~UserBoundNlMessage();
+
+  // Non-trivial initialization.
+  virtual bool Init(nlattr *tb[NL80211_ATTR_MAX + 1], nlmsghdr *msg);
+
+  // Provide a suite of methods to allow (const) iteration over the names of the
+  // attributes inside a message object.
+
+  AttributeNameIterator *GetAttributeNameIterator() const;
+  bool HasAttributes() const { return !attributes_.empty(); }
+  uint32_t GetAttributeCount() const { return attributes_.size(); }
+
+  virtual uint8_t GetMessageType() const {
+    return UserBoundNlMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return UserBoundNlMessage::kCommandString;
+  }
+
+  // Other ways to see the internals of the object.
+
+  // Return true if the attribute is in our map, regardless of the value of
+  // the attribute, itself.
+  bool AttributeExists(nl80211_attrs name) const;
+
+  // Message ID is equivalent to the message's sequence number.
+  uint32_t GetId() const;
+
+  // Returns the data type of a given attribute.
+  Type GetAttributeType(nl80211_attrs name) const;
+
+  // Returns a string describing the data type of a given attribute.
+  std::string GetAttributeTypeString(nl80211_attrs name) const;
+
+  // If successful, returns 'true' and sets *|value| to the raw attribute data
+  // (after the header) for this attribute and, if |length| is not
+  // null, *|length| to the number of bytes of data available.  If no
+  // attribute by this name exists in this message, sets *|value| to NULL and
+  // returns 'false'.  If otherwise unsuccessful, returns 'false' and leaves
+  // |value| and |length| unchanged.
+  bool GetRawAttributeData(nl80211_attrs name, void **value, int *length) const;
+
+  // Each of these methods set |value| with the value of the specified
+  // attribute (if the attribute is not found, |value| remains unchanged).
+
+  bool GetStringAttribute(nl80211_attrs name, std::string *value) const;
+  bool GetU8Attribute(nl80211_attrs name, uint8_t *value) const;
+  bool GetU16Attribute(nl80211_attrs name, uint16_t *value) const;
+  bool GetU32Attribute(nl80211_attrs name, uint32_t *value) const;
+  bool GetU64Attribute(nl80211_attrs name, uint64_t *value) const;
+
+  // Fill a string with characters that represents the value of the attribute.
+  // If no attribute is found or if the type isn't trivially stringizable,
+  // this method returns 'false' and |value| remains unchanged.
+  bool GetAttributeString(nl80211_attrs name, std::string *value) const;
+
+  // Helper function to provide a string for a MAC address.  If no attribute
+  // is found, this method returns 'false'.  On any error with a non-NULL
+  // |value|, this method sets |value| to a bogus MAC address.
+  bool GetMacAttributeString(nl80211_attrs name, std::string *value) const;
+
+  // Helper function to provide a vector of scan frequencies for attributes
+  // that contain them (such as NL80211_ATTR_SCAN_FREQUENCIES).
+  bool GetScanFrequenciesAttribute(enum nl80211_attrs name,
+                                   std::vector<uint32_t> *value) const;
+
+  // Helper function to provide a vector of SSIDs for attributes that contain
+  // them (such as NL80211_ATTR_SCAN_SSIDS).
+  bool GetScanSsidsAttribute(enum nl80211_attrs name,
+                             std::vector<std::string> *value) const;
+
+  // Writes the raw attribute data to a string.  For debug.
+  virtual std::string RawToString(nl80211_attrs name) const;
+
+  // Returns a string describing a given attribute name.
+  static std::string StringFromAttributeName(nl80211_attrs name);
+
+  // Stringizes the MAC address found in 'arg'.  If there are problems (such
+  // as a NULL |arg|), |value| is set to a bogus MAC address.
+  static std::string StringFromMacAddress(const uint8_t *arg);
+
+  // Returns a string representing the passed-in |status|, the value of which
+  // has been acquired from libnl (for example, from the
+  // NL80211_ATTR_STATUS_CODE or NL80211_ATTR_REASON_CODE attribute).
+  static std::string StringFromStatus(uint16_t status);
+
+  // Returns a string that describes this message.
+  virtual std::string ToString() const { return GetHeaderString(); }
+
+ protected:
+  // Duplicate attribute data, store in map indexed on 'name'.
+  bool AddAttribute(nl80211_attrs name, nlattr *data);
+
+  // Returns the raw nlattr for a given attribute (NULL if attribute doesn't
+  // exist).
+  const nlattr *GetAttribute(nl80211_attrs name) const;
+
+  // Returns a string that should precede all user-bound message strings.
+  virtual std::string GetHeaderString() const;
+
+  // Returns a string that describes the contents of the frame pointed to by
+  // 'attr'.
+  std::string StringFromFrame(nl80211_attrs attr_name) const;
+
+  // Converts key_type to a string.
+  static std::string StringFromKeyType(nl80211_key_type key_type);
+
+  // Returns a string representation of the REG initiator described by the
+  // method's parameter.
+  static std::string StringFromRegInitiator(__u8 initiator);
+
+  // Returns a string based on the SSID found in 'data'.  Non-printable
+  // characters are string-ized.
+  static std::string StringFromSsid(const uint8_t len, const uint8_t *data);
+
+ private:
+  friend class AttributeNameIterator;
+  friend class Config80211Test;
+  FRIEND_TEST(Config80211Test, NL80211_CMD_NOTIFY_CQM);
+
+  static const uint32_t kIllegalMessage;
+  static const int kEthernetAddressBytes;
+
+  nlmsghdr *message_;
+  static std::map<uint16_t, std::string> *connect_status_map_;
+  std::map<nl80211_attrs, nlattr *> attributes_;
+
+  DISALLOW_COPY_AND_ASSIGN(UserBoundNlMessage);
+};
+
+class Nl80211Frame {
+ public:
+  enum Type {
+    kAssocResponseFrameType = 0x10,
+    kReassocResponseFrameType = 0x30,
+    kAssocRequestFrameType = 0x00,
+    kReassocRequestFrameType = 0x20,
+    kAuthFrameType = 0xb0,
+    kDisassocFrameType = 0xa0,
+    kDeauthFrameType = 0xc0,
+    kIllegalFrameType = 0xff
+  };
+
+  Nl80211Frame(const uint8_t *frame, int frame_byte_count);
+  ~Nl80211Frame();
+  bool ToString(std::string *output);
+  bool IsEqual(const Nl80211Frame &other);
+
+ private:
+  static const uint8_t kMinimumFrameByteCount;
+  static const uint8_t kFrameTypeMask;
+
+  std::string mac_from_;
+  std::string mac_to_;
+  uint8_t frame_type_;
+  uint16_t status_;
+  uint8_t *frame_;
+  int byte_count_;
+
+  DISALLOW_COPY_AND_ASSIGN(Nl80211Frame);
+};
+
+//
+// Specific UserBoundNlMessage types.
+//
+
+class AssociateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  AssociateMessage() {}
+
+  virtual uint8_t GetMessageType() const { return AssociateMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return AssociateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(AssociateMessage);
+};
+
+
+class AuthenticateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  AuthenticateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return AuthenticateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return AuthenticateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(AuthenticateMessage);
+};
+
+
+class CancelRemainOnChannelMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  CancelRemainOnChannelMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return CancelRemainOnChannelMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return CancelRemainOnChannelMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(CancelRemainOnChannelMessage);
+};
+
+
+class ConnectMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  ConnectMessage() {}
+
+  virtual uint8_t GetMessageType() const { return ConnectMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return ConnectMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(ConnectMessage);
+};
+
+
+class DeauthenticateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  DeauthenticateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return DeauthenticateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return DeauthenticateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(DeauthenticateMessage);
+};
+
+
+class DeleteStationMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  DeleteStationMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return DeleteStationMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return DeleteStationMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(DeleteStationMessage);
+};
+
+
+class DisassociateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  DisassociateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return DisassociateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return DisassociateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(DisassociateMessage);
+};
+
+
+class DisconnectMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  DisconnectMessage() {}
+
+  virtual uint8_t GetMessageType() const { return DisconnectMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return DisconnectMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(DisconnectMessage);
+};
+
+
+class FrameTxStatusMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  FrameTxStatusMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return FrameTxStatusMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return FrameTxStatusMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(FrameTxStatusMessage);
+};
+
+
+class JoinIbssMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  JoinIbssMessage() {}
+
+  virtual uint8_t GetMessageType() const { return JoinIbssMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return JoinIbssMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(JoinIbssMessage);
+};
+
+
+class MichaelMicFailureMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  MichaelMicFailureMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return MichaelMicFailureMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return MichaelMicFailureMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(MichaelMicFailureMessage);
+};
+
+
+class NewScanResultsMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  NewScanResultsMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return NewScanResultsMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return NewScanResultsMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(NewScanResultsMessage);
+};
+
+
+class NewStationMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  NewStationMessage() {}
+
+  virtual uint8_t GetMessageType() const { return NewStationMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return NewStationMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(NewStationMessage);
+};
+
+
+class NewWifiMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  NewWifiMessage() {}
+
+  virtual uint8_t GetMessageType() const { return NewWifiMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return NewWifiMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(NewWifiMessage);
+};
+
+
+class NotifyCqmMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  NotifyCqmMessage() {}
+
+  virtual uint8_t GetMessageType() const { return NotifyCqmMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return NotifyCqmMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(NotifyCqmMessage);
+};
+
+
+class PmksaCandidateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  PmksaCandidateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return PmksaCandidateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return PmksaCandidateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(PmksaCandidateMessage);
+};
+
+
+class RegBeaconHintMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  RegBeaconHintMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return RegBeaconHintMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return RegBeaconHintMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  struct ieee80211_beacon_channel {
+    __u16 center_freq;
+    bool passive_scan;
+    bool no_ibss;
+  };
+
+  // Returns the channel ID calculated from the 802.11 frequency.
+  static int ChannelFromIeee80211Frequency(int freq);
+
+  // Sets values in |chan| based on attributes in |tb|, the array of pointers
+  // to netlink attributes, indexed by attribute type.
+  int ParseBeaconHintChan(const nlattr *tb,
+                          ieee80211_beacon_channel *chan) const;
+
+  DISALLOW_COPY_AND_ASSIGN(RegBeaconHintMessage);
+};
+
+
+class RegChangeMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  RegChangeMessage() {}
+
+  virtual uint8_t GetMessageType() const { return RegChangeMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return RegChangeMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(RegChangeMessage);
+};
+
+
+class RemainOnChannelMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  RemainOnChannelMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return RemainOnChannelMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return RemainOnChannelMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(RemainOnChannelMessage);
+};
+
+
+class RoamMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  RoamMessage() {}
+
+  virtual uint8_t GetMessageType() const { return RoamMessage::kCommand; }
+  virtual std::string GetMessageTypeString() const {
+    return RoamMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(RoamMessage);
+};
+
+
+class ScanAbortedMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  ScanAbortedMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return ScanAbortedMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return ScanAbortedMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(ScanAbortedMessage);
+};
+
+
+class TriggerScanMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  TriggerScanMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return TriggerScanMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return TriggerScanMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(TriggerScanMessage);
+};
+
+
+class UnknownMessage : public UserBoundNlMessage {
+ public:
+  explicit UnknownMessage(uint8_t command) : command_(command) {}
+
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  virtual uint8_t GetMessageType() const { return command_; }
+  virtual std::string GetMessageTypeString() const {
+    return UnknownMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  uint8_t command_;
+
+  DISALLOW_COPY_AND_ASSIGN(UnknownMessage);
+};
+
+
+class UnprotDeauthenticateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  UnprotDeauthenticateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return UnprotDeauthenticateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return UnprotDeauthenticateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(UnprotDeauthenticateMessage);
+};
+
+
+class UnprotDisassociateMessage : public UserBoundNlMessage {
+ public:
+  static const uint8_t kCommand;
+  static const char kCommandString[];
+
+  UnprotDisassociateMessage() {}
+
+  virtual uint8_t GetMessageType() const {
+    return UnprotDisassociateMessage::kCommand;
+  }
+  virtual std::string GetMessageTypeString() const {
+    return UnprotDisassociateMessage::kCommandString;
+  }
+  virtual std::string ToString() const;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(UnprotDisassociateMessage);
+};
+
+
+//
+// Factory class.
+//
+
+class UserBoundNlMessageFactory {
+ public:
+  // Ownership of the message is passed to the caller and, as such, he should
+  // delete it.
+  static UserBoundNlMessage *CreateMessage(nlmsghdr *msg);
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(UserBoundNlMessageFactory);
+};
+
+
+// UserBoundNlMessageDataCollector - this class is used to collect data to be
+// used for unit tests.  It is only invoked in this case.
+
+class UserBoundNlMessageDataCollector {
+ public:
+  // This is a singleton -- use Config80211::GetInstance()->Foo()
+  static UserBoundNlMessageDataCollector *GetInstance();
+
+  void CollectDebugData(const UserBoundNlMessage &message, nlmsghdr *msg);
+
+ protected:
+  friend struct
+      base::DefaultLazyInstanceTraits<UserBoundNlMessageDataCollector>;
+
+  explicit UserBoundNlMessageDataCollector();
+
+ private:
+  // In order to limit the output from this class, I keep track of types I
+  // haven't yet printed.
+  std::map<uint8_t, bool> need_to_print;
+};
+
+}  // namespace shill
+
+#endif  // SHILL_USER_BOUND_NLMESSAGE_H_