We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / extensions / browser / api / networking_private / networking_private_linux.cc
blob1d9ad8796fca5f51f7657ff95aa8bed7729b5bb9
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/api/networking_private/networking_private_linux.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string16.h"
12 #include "base/strings/string_split.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/sequenced_worker_pool.h"
15 #include "components/onc/onc_constants.h"
16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/browser_thread.h"
18 #include "dbus/bus.h"
19 #include "dbus/message.h"
20 #include "dbus/object_path.h"
21 #include "dbus/object_proxy.h"
22 #include "extensions/browser/api/networking_private/network_config_dbus_constants_linux.h"
23 #include "extensions/browser/api/networking_private/networking_private_api.h"
24 #include "extensions/browser/api/networking_private/networking_private_delegate_observer.h"
26 ////////////////////////////////////////////////////////////////////////////////
28 namespace extensions {
30 namespace {
31 // Access Point info strings.
32 const char kAccessPointInfoName[] = "Name";
33 const char kAccessPointInfoGuid[] = "GUID";
34 const char kAccessPointInfoConnectable[] = "Connectable";
35 const char kAccessPointInfoConnectionState[] = "ConnectionState";
36 const char kAccessPointInfoType[] = "Type";
37 const char kAccessPointInfoTypeWifi[] = "WiFi";
38 const char kAccessPointInfoWifiSignalStrengthDotted[] = "WiFi.SignalStrength";
39 const char kAccessPointInfoWifiSecurityDotted[] = "WiFi.Security";
41 // Access point security type strings.
42 const char kAccessPointSecurityNone[] = "None";
43 const char kAccessPointSecurityUnknown[] = "Unknown";
44 const char kAccessPointSecurityWpaPsk[] = "WPA-PSK";
45 const char kAccessPointSecurity9021X[] = "WEP-8021X";
47 // Parses the GUID which contains 3 pieces of relevant information. The
48 // object path to the network device, the object path of the access point,
49 // and the ssid.
50 bool ParseNetworkGuid(const std::string& guid,
51 std::string* device_path,
52 std::string* access_point_path,
53 std::string* ssid) {
54 std::vector<std::string> guid_parts;
56 base::SplitString(guid, '|', &guid_parts);
58 if (guid_parts.size() != 3) {
59 return false;
62 *device_path = guid_parts[0];
63 *access_point_path = guid_parts[1];
64 *ssid = guid_parts[2];
66 if (device_path->empty() || access_point_path->empty() || ssid->empty()) {
67 return false;
70 return true;
73 // Simplified helper to parse the SSID from the GUID.
74 bool GuidToSsid(const std::string& guid, std::string* ssid) {
75 std::string unused_1;
76 std::string unused_2;
77 return ParseNetworkGuid(guid, &unused_1, &unused_2, ssid);
80 // Iterates over the map cloning the contained networks to a
81 // list then returns the list.
82 scoped_ptr<base::ListValue> CopyNetworkMapToList(
83 const NetworkingPrivateLinux::NetworkMap& network_map) {
84 scoped_ptr<base::ListValue> network_list(new base::ListValue);
86 for (const auto& network : network_map) {
87 network_list->Append(network.second->DeepCopy());
90 return network_list.Pass();
93 // Constructs a network guid from its constituent parts.
94 std::string ConstructNetworkGuid(const dbus::ObjectPath& device_path,
95 const dbus::ObjectPath& access_point_path,
96 const std::string& ssid) {
97 return device_path.value() + "|" + access_point_path.value() + "|" + ssid;
100 // Logs that the method is not implemented and reports |kErrorNotSupported|
101 // to the failure callback.
102 void ReportNotSupported(
103 const std::string& method_name,
104 const NetworkingPrivateDelegate::FailureCallback& failure_callback) {
105 LOG(WARNING) << method_name << " is not supported";
106 failure_callback.Run(extensions::networking_private::kErrorNotSupported);
109 // Fires the appropriate callback when the network connect operation succeeds
110 // or fails.
111 void OnNetworkConnectOperationCompleted(
112 scoped_ptr<std::string> error,
113 const NetworkingPrivateDelegate::VoidCallback& success_callback,
114 const NetworkingPrivateDelegate::FailureCallback& failure_callback) {
115 if (!error->empty()) {
116 failure_callback.Run(*error);
117 return;
119 success_callback.Run();
122 // Fires the appropriate callback when the network properties are returned
123 // from the |dbus_thread_|.
124 void GetCachedNetworkPropertiesCallback(
125 scoped_ptr<std::string> error,
126 scoped_ptr<base::DictionaryValue> properties,
127 const NetworkingPrivateDelegate::DictionaryCallback& success_callback,
128 const NetworkingPrivateDelegate::FailureCallback& failure_callback) {
129 if (!error->empty()) {
130 failure_callback.Run(*error);
131 return;
133 success_callback.Run(properties.Pass());
136 } // namespace
138 NetworkingPrivateLinux::NetworkingPrivateLinux(
139 content::BrowserContext* browser_context,
140 scoped_ptr<VerifyDelegate> verify_delegate)
141 : NetworkingPrivateDelegate(verify_delegate.Pass()),
142 browser_context_(browser_context),
143 dbus_thread_("Networking Private DBus"),
144 network_manager_proxy_(NULL) {
145 base::Thread::Options thread_options(base::MessageLoop::Type::TYPE_IO, 0);
147 dbus_thread_.StartWithOptions(thread_options);
148 dbus_thread_.task_runner()->PostTask(
149 FROM_HERE,
150 base::Bind(&NetworkingPrivateLinux::Initialize, base::Unretained(this)));
153 NetworkingPrivateLinux::~NetworkingPrivateLinux() {
154 dbus_thread_.Stop();
157 void NetworkingPrivateLinux::AssertOnDBusThread() {
158 DCHECK(dbus_task_runner_->RunsTasksOnCurrentThread());
161 void NetworkingPrivateLinux::Initialize() {
162 dbus_task_runner_ = dbus_thread_.task_runner();
163 // This has to be called after the task runner is initialized.
164 AssertOnDBusThread();
166 dbus::Bus::Options dbus_options;
167 dbus_options.bus_type = dbus::Bus::SYSTEM;
168 dbus_options.connection_type = dbus::Bus::PRIVATE;
169 dbus_options.dbus_task_runner = dbus_task_runner_;
171 dbus_ = new dbus::Bus(dbus_options);
172 network_manager_proxy_ = dbus_->GetObjectProxy(
173 networking_private::kNetworkManagerNamespace,
174 dbus::ObjectPath(networking_private::kNetworkManagerPath));
176 if (!network_manager_proxy_) {
177 LOG(ERROR) << "Platform does not support NetworkManager over DBUS";
180 network_map_.reset(new NetworkMap());
183 bool NetworkingPrivateLinux::CheckNetworkManagerSupported(
184 const FailureCallback& failure_callback) {
185 if (!network_manager_proxy_) {
186 ReportNotSupported("NetworkManager over DBus", failure_callback);
187 return false;
190 return true;
193 void NetworkingPrivateLinux::GetProperties(
194 const std::string& guid,
195 const DictionaryCallback& success_callback,
196 const FailureCallback& failure_callback) {
197 GetState(guid, success_callback, failure_callback);
200 void NetworkingPrivateLinux::GetManagedProperties(
201 const std::string& guid,
202 const DictionaryCallback& success_callback,
203 const FailureCallback& failure_callback) {
204 ReportNotSupported("GetManagedProperties", failure_callback);
207 void NetworkingPrivateLinux::GetState(
208 const std::string& guid,
209 const DictionaryCallback& success_callback,
210 const FailureCallback& failure_callback) {
211 if (!CheckNetworkManagerSupported(failure_callback))
212 return;
214 scoped_ptr<std::string> error(new std::string);
215 scoped_ptr<base::DictionaryValue> network_properties(
216 new base::DictionaryValue);
218 // Runs GetCachedNetworkProperties on |dbus_thread|.
219 dbus_thread_.task_runner()->PostTaskAndReply(
220 FROM_HERE, base::Bind(&NetworkingPrivateLinux::GetCachedNetworkProperties,
221 base::Unretained(this), guid,
222 base::Unretained(network_properties.get()),
223 base::Unretained(error.get())),
224 base::Bind(&GetCachedNetworkPropertiesCallback, base::Passed(&error),
225 base::Passed(&network_properties), success_callback,
226 failure_callback));
229 void NetworkingPrivateLinux::GetCachedNetworkProperties(
230 const std::string& guid,
231 base::DictionaryValue* properties,
232 std::string* error) {
233 AssertOnDBusThread();
234 std::string ssid;
236 if (!GuidToSsid(guid, &ssid)) {
237 *error = "Invalid Network GUID format";
238 return;
241 NetworkMap::const_iterator network_iter =
242 network_map_->find(base::UTF8ToUTF16(ssid));
243 if (network_iter == network_map_->end()) {
244 *error = "Unknown network GUID";
245 return;
248 // Make a copy of the properties out of the cached map.
249 scoped_ptr<base::DictionaryValue> temp_properties(
250 network_iter->second->DeepCopy());
252 // Swap the new copy into the dictionary that is shared with the reply.
253 properties->Swap(temp_properties.get());
256 void NetworkingPrivateLinux::SetProperties(
257 const std::string& guid,
258 scoped_ptr<base::DictionaryValue> properties,
259 const VoidCallback& success_callback,
260 const FailureCallback& failure_callback) {
261 ReportNotSupported("SetProperties", failure_callback);
264 void NetworkingPrivateLinux::CreateNetwork(
265 bool shared,
266 scoped_ptr<base::DictionaryValue> properties,
267 const StringCallback& success_callback,
268 const FailureCallback& failure_callback) {
269 ReportNotSupported("CreateNetwork", failure_callback);
272 void NetworkingPrivateLinux::ForgetNetwork(
273 const std::string& guid,
274 const VoidCallback& success_callback,
275 const FailureCallback& failure_callback) {
276 // TODO(zentaro): Implement for Linux.
277 ReportNotSupported("ForgetNetwork", failure_callback);
280 void NetworkingPrivateLinux::GetNetworks(
281 const std::string& network_type,
282 bool configured_only,
283 bool visible_only,
284 int limit,
285 const NetworkListCallback& success_callback,
286 const FailureCallback& failure_callback) {
287 if (!CheckNetworkManagerSupported(failure_callback)) {
288 return;
291 scoped_ptr<NetworkMap> network_map(new NetworkMap);
293 if (!(network_type == ::onc::network_type::kWiFi ||
294 network_type == ::onc::network_type::kWireless ||
295 network_type == ::onc::network_type::kAllTypes)) {
296 // Only enumerating WiFi networks is supported on linux.
297 ReportNotSupported("GetNetworks with network_type=" + network_type,
298 failure_callback);
299 return;
302 // Runs GetAllWiFiAccessPoints on the dbus_thread and returns the
303 // results back to OnAccessPointsFound where the callback is fired.
304 dbus_thread_.task_runner()->PostTaskAndReply(
305 FROM_HERE,
306 base::Bind(&NetworkingPrivateLinux::GetAllWiFiAccessPoints,
307 base::Unretained(this), configured_only, visible_only, limit,
308 base::Unretained(network_map.get())),
309 base::Bind(&NetworkingPrivateLinux::OnAccessPointsFound,
310 base::Unretained(this), base::Passed(&network_map),
311 success_callback, failure_callback));
314 bool NetworkingPrivateLinux::GetNetworksForScanRequest() {
315 if (!network_manager_proxy_) {
316 return false;
319 scoped_ptr<NetworkMap> network_map(new NetworkMap);
321 // Runs GetAllWiFiAccessPoints on the dbus_thread and returns the
322 // results back to SendNetworkListChangedEvent to fire the event. No
323 // callbacks are used in this case.
324 dbus_thread_.task_runner()->PostTaskAndReply(
325 FROM_HERE, base::Bind(&NetworkingPrivateLinux::GetAllWiFiAccessPoints,
326 base::Unretained(this), false /* configured_only */,
327 false /* visible_only */, 0 /* limit */,
328 base::Unretained(network_map.get())),
329 base::Bind(&NetworkingPrivateLinux::OnAccessPointsFoundViaScan,
330 base::Unretained(this), base::Passed(&network_map)));
332 return true;
335 // Constructs the network configuration message and connects to the network.
336 // The message is of the form:
337 // {
338 // '802-11-wireless': {
339 // 'ssid': 'FooNetwork'
340 // }
341 // }
342 void NetworkingPrivateLinux::ConnectToNetwork(const std::string& guid,
343 std::string* error) {
344 AssertOnDBusThread();
345 std::string device_path_str;
346 std::string access_point_path_str;
347 std::string ssid;
348 DVLOG(1) << "Connecting to network GUID " << guid;
350 if (!ParseNetworkGuid(guid, &device_path_str, &access_point_path_str,
351 &ssid)) {
352 *error = "Invalid Network GUID format";
353 return;
356 // Set the connection state to connecting in the map.
357 if (!SetConnectionStateAndPostEvent(guid, ssid,
358 ::onc::connection_state::kConnecting)) {
359 *error = "Unknown network GUID";
360 return;
363 dbus::ObjectPath device_path(device_path_str);
364 dbus::ObjectPath access_point_path(access_point_path_str);
366 dbus::MethodCall method_call(
367 networking_private::kNetworkManagerNamespace,
368 networking_private::kNetworkManagerAddAndActivateConnectionMethod);
369 dbus::MessageWriter builder(&method_call);
371 // Build up the settings nested dictionary.
372 dbus::MessageWriter array_writer(&method_call);
373 builder.OpenArray("{sa{sv}}", &array_writer);
375 dbus::MessageWriter dict_writer(&method_call);
376 array_writer.OpenDictEntry(&dict_writer);
377 // TODO(zentaro): Support other network types. Currently only WiFi is
378 // supported.
379 dict_writer.AppendString(
380 networking_private::kNetworkManagerConnectionConfig80211Wireless);
382 dbus::MessageWriter wifi_array(&method_call);
383 dict_writer.OpenArray("{sv}", &wifi_array);
385 dbus::MessageWriter wifi_dict_writer(&method_call);
386 wifi_array.OpenDictEntry(&wifi_dict_writer);
387 wifi_dict_writer.AppendString(
388 networking_private::kNetworkManagerConnectionConfigSsid);
390 dbus::MessageWriter variant_writer(&method_call);
391 wifi_dict_writer.OpenVariant("ay", &variant_writer);
392 variant_writer.AppendArrayOfBytes(
393 reinterpret_cast<const uint8*>(ssid.c_str()), ssid.size());
395 // Close all the arrays and dicts.
396 wifi_dict_writer.CloseContainer(&variant_writer);
397 wifi_array.CloseContainer(&wifi_dict_writer);
398 dict_writer.CloseContainer(&wifi_array);
399 array_writer.CloseContainer(&dict_writer);
400 builder.CloseContainer(&array_writer);
402 builder.AppendObjectPath(device_path);
403 builder.AppendObjectPath(access_point_path);
405 scoped_ptr<dbus::Response> response(
406 network_manager_proxy_->CallMethodAndBlock(
407 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
408 if (!response) {
409 LOG(ERROR) << "Failed to add a new connection";
410 *error = "Failed to connect.";
412 // Set the connection state to NotConnected in the map.
413 SetConnectionStateAndPostEvent(guid, ssid,
414 ::onc::connection_state::kNotConnected);
415 return;
418 dbus::MessageReader reader(response.get());
419 dbus::ObjectPath connection_settings_path;
420 dbus::ObjectPath active_connection_path;
422 if (!reader.PopObjectPath(&connection_settings_path)) {
423 LOG(ERROR) << "Unexpected response for add connection path "
424 << ": " << response->ToString();
425 *error = "Failed to connect.";
427 // Set the connection state to NotConnected in the map.
428 SetConnectionStateAndPostEvent(guid, ssid,
429 ::onc::connection_state::kNotConnected);
430 return;
433 if (!reader.PopObjectPath(&active_connection_path)) {
434 LOG(ERROR) << "Unexpected response for connection path "
435 << ": " << response->ToString();
436 *error = "Failed to connect.";
438 // Set the connection state to NotConnected in the map.
439 SetConnectionStateAndPostEvent(guid, ssid,
440 ::onc::connection_state::kNotConnected);
441 return;
444 // Set the connection state to Connected in the map.
445 SetConnectionStateAndPostEvent(guid, ssid,
446 ::onc::connection_state::kConnected);
447 return;
450 void NetworkingPrivateLinux::DisconnectFromNetwork(const std::string& guid,
451 std::string* error) {
452 AssertOnDBusThread();
453 std::string device_path_str;
454 std::string access_point_path_str;
455 std::string ssid;
456 DVLOG(1) << "Disconnecting from network GUID " << guid;
458 if (!ParseNetworkGuid(guid, &device_path_str, &access_point_path_str,
459 &ssid)) {
460 *error = "Invalid Network GUID format";
461 return;
464 scoped_ptr<NetworkMap> network_map(new NetworkMap);
465 GetAllWiFiAccessPoints(false /* configured_only */, false /* visible_only */,
466 0 /* limit */, network_map.get());
468 NetworkMap::const_iterator network_iter =
469 network_map->find(base::UTF8ToUTF16(ssid));
470 if (network_iter == network_map->end()) {
471 // This network doesn't exist so there's nothing to do.
472 return;
475 std::string connection_state;
476 network_iter->second->GetString(kAccessPointInfoConnectionState,
477 &connection_state);
478 if (connection_state == ::onc::connection_state::kNotConnected) {
479 // Already disconnected so nothing to do.
480 return;
483 // It's not disconnected so disconnect it.
484 dbus::ObjectProxy* device_proxy =
485 dbus_->GetObjectProxy(networking_private::kNetworkManagerNamespace,
486 dbus::ObjectPath(device_path_str));
487 dbus::MethodCall method_call(
488 networking_private::kNetworkManagerDeviceNamespace,
489 networking_private::kNetworkManagerDisconnectMethod);
490 scoped_ptr<dbus::Response> response(device_proxy->CallMethodAndBlock(
491 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
493 if (!response) {
494 LOG(WARNING) << "Failed to disconnect network on device "
495 << device_path_str;
496 *error = "Failed to disconnect network";
500 void NetworkingPrivateLinux::StartConnect(
501 const std::string& guid,
502 const VoidCallback& success_callback,
503 const FailureCallback& failure_callback) {
504 if (!CheckNetworkManagerSupported(failure_callback))
505 return;
507 scoped_ptr<std::string> error(new std::string);
509 // Runs ConnectToNetwork on |dbus_thread|.
510 dbus_thread_.task_runner()->PostTaskAndReply(
511 FROM_HERE,
512 base::Bind(&NetworkingPrivateLinux::ConnectToNetwork,
513 base::Unretained(this), guid, base::Unretained(error.get())),
514 base::Bind(&OnNetworkConnectOperationCompleted, base::Passed(&error),
515 success_callback, failure_callback));
518 void NetworkingPrivateLinux::StartDisconnect(
519 const std::string& guid,
520 const VoidCallback& success_callback,
521 const FailureCallback& failure_callback) {
522 if (!CheckNetworkManagerSupported(failure_callback))
523 return;
525 scoped_ptr<std::string> error(new std::string);
527 // Runs DisconnectFromNetwork on |dbus_thread|.
528 dbus_thread_.task_runner()->PostTaskAndReply(
529 FROM_HERE,
530 base::Bind(&NetworkingPrivateLinux::DisconnectFromNetwork,
531 base::Unretained(this), guid, base::Unretained(error.get())),
532 base::Bind(&OnNetworkConnectOperationCompleted, base::Passed(&error),
533 success_callback, failure_callback));
536 void NetworkingPrivateLinux::SetWifiTDLSEnabledState(
537 const std::string& ip_or_mac_address,
538 bool enabled,
539 const StringCallback& success_callback,
540 const FailureCallback& failure_callback) {
541 ReportNotSupported("SetWifiTDLSEnabledState", failure_callback);
544 void NetworkingPrivateLinux::GetWifiTDLSStatus(
545 const std::string& ip_or_mac_address,
546 const StringCallback& success_callback,
547 const FailureCallback& failure_callback) {
548 ReportNotSupported("GetWifiTDLSStatus", failure_callback);
551 void NetworkingPrivateLinux::GetCaptivePortalStatus(
552 const std::string& guid,
553 const StringCallback& success_callback,
554 const FailureCallback& failure_callback) {
555 ReportNotSupported("GetCaptivePortalStatus", failure_callback);
558 scoped_ptr<base::ListValue> NetworkingPrivateLinux::GetEnabledNetworkTypes() {
559 scoped_ptr<base::ListValue> network_list(new base::ListValue);
560 return network_list.Pass();
563 bool NetworkingPrivateLinux::EnableNetworkType(const std::string& type) {
564 return false;
567 bool NetworkingPrivateLinux::DisableNetworkType(const std::string& type) {
568 return false;
571 bool NetworkingPrivateLinux::RequestScan() {
572 return GetNetworksForScanRequest();
575 void NetworkingPrivateLinux::AddObserver(
576 NetworkingPrivateDelegateObserver* observer) {
577 network_events_observers_.AddObserver(observer);
580 void NetworkingPrivateLinux::RemoveObserver(
581 NetworkingPrivateDelegateObserver* observer) {
582 network_events_observers_.RemoveObserver(observer);
585 void NetworkingPrivateLinux::OnAccessPointsFound(
586 scoped_ptr<NetworkMap> network_map,
587 const NetworkListCallback& success_callback,
588 const FailureCallback& failure_callback) {
589 scoped_ptr<base::ListValue> network_list = CopyNetworkMapToList(*network_map);
590 // Give ownership to the member variable.
591 network_map_.swap(network_map);
592 SendNetworkListChangedEvent(*network_list);
593 success_callback.Run(network_list.Pass());
596 void NetworkingPrivateLinux::OnAccessPointsFoundViaScan(
597 scoped_ptr<NetworkMap> network_map) {
598 scoped_ptr<base::ListValue> network_list = CopyNetworkMapToList(*network_map);
599 // Give ownership to the member variable.
600 network_map_.swap(network_map);
601 SendNetworkListChangedEvent(*network_list);
604 void NetworkingPrivateLinux::SendNetworkListChangedEvent(
605 const base::ListValue& network_list) {
606 GuidList guidsForEventCallback;
608 for (const auto& network : network_list) {
609 std::string guid;
610 base::DictionaryValue* dict;
611 if (network->GetAsDictionary(&dict)) {
612 if (dict->GetString(kAccessPointInfoGuid, &guid)) {
613 guidsForEventCallback.push_back(guid);
618 OnNetworkListChangedEventOnUIThread(guidsForEventCallback);
621 bool NetworkingPrivateLinux::GetNetworkDevices(
622 std::vector<dbus::ObjectPath>* device_paths) {
623 AssertOnDBusThread();
624 dbus::MethodCall method_call(
625 networking_private::kNetworkManagerNamespace,
626 networking_private::kNetworkManagerGetDevicesMethod);
628 scoped_ptr<dbus::Response> device_response(
629 network_manager_proxy_->CallMethodAndBlock(
630 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
632 if (!device_response) {
633 return false;
636 dbus::MessageReader reader(device_response.get());
637 if (!reader.PopArrayOfObjectPaths(device_paths)) {
638 LOG(WARNING) << "Unexpected response: " << device_response->ToString();
639 return false;
642 return true;
645 NetworkingPrivateLinux::DeviceType NetworkingPrivateLinux::GetDeviceType(
646 const dbus::ObjectPath& device_path) {
647 AssertOnDBusThread();
648 dbus::ObjectProxy* device_proxy = dbus_->GetObjectProxy(
649 networking_private::kNetworkManagerNamespace, device_path);
650 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES,
651 networking_private::kNetworkManagerGetMethod);
652 dbus::MessageWriter builder(&method_call);
653 builder.AppendString(networking_private::kNetworkManagerDeviceNamespace);
654 builder.AppendString(networking_private::kNetworkManagerDeviceType);
656 scoped_ptr<dbus::Response> response(device_proxy->CallMethodAndBlock(
657 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
659 if (!response) {
660 LOG(ERROR) << "Failed to get the device type for device "
661 << device_path.value();
662 return NetworkingPrivateLinux::NM_DEVICE_TYPE_UNKNOWN;
665 dbus::MessageReader reader(response.get());
666 uint32 device_type = 0;
667 if (!reader.PopVariantOfUint32(&device_type)) {
668 LOG(ERROR) << "Unexpected response for device " << device_type << ": "
669 << response->ToString();
670 return NM_DEVICE_TYPE_UNKNOWN;
673 return static_cast<NetworkingPrivateLinux::DeviceType>(device_type);
676 void NetworkingPrivateLinux::GetAllWiFiAccessPoints(bool configured_only,
677 bool visible_only,
678 int limit,
679 NetworkMap* network_map) {
680 AssertOnDBusThread();
681 // TODO(zentaro): The filters are not implemented and are ignored.
682 std::vector<dbus::ObjectPath> device_paths;
683 if (!GetNetworkDevices(&device_paths)) {
684 LOG(ERROR) << "Failed to enumerate network devices";
685 return;
688 for (const auto& device_path : device_paths) {
689 NetworkingPrivateLinux::DeviceType device_type = GetDeviceType(device_path);
691 // Get the access points for each WiFi adapter. Other network types are
692 // ignored.
693 if (device_type != NetworkingPrivateLinux::NM_DEVICE_TYPE_WIFI)
694 continue;
696 // Found a wlan adapter
697 if (!AddAccessPointsFromDevice(device_path, network_map)) {
698 // Ignore devices we can't enumerate.
699 LOG(WARNING) << "Failed to add access points from device "
700 << device_path.value();
705 scoped_ptr<dbus::Response> NetworkingPrivateLinux::GetAccessPointProperty(
706 dbus::ObjectProxy* access_point_proxy,
707 const std::string& property_name) {
708 AssertOnDBusThread();
709 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES,
710 networking_private::kNetworkManagerGetMethod);
711 dbus::MessageWriter builder(&method_call);
712 builder.AppendString(networking_private::kNetworkManagerAccessPointNamespace);
713 builder.AppendString(property_name);
714 scoped_ptr<dbus::Response> response = access_point_proxy->CallMethodAndBlock(
715 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT);
716 if (!response) {
717 LOG(ERROR) << "Failed to get property for " << property_name;
719 return response.Pass();
722 bool NetworkingPrivateLinux::GetAccessPointInfo(
723 const dbus::ObjectPath& access_point_path,
724 const scoped_ptr<base::DictionaryValue>& access_point_info) {
725 AssertOnDBusThread();
726 dbus::ObjectProxy* access_point_proxy = dbus_->GetObjectProxy(
727 networking_private::kNetworkManagerNamespace, access_point_path);
729 // Read the SSID. The GUID is derived from the Ssid.
731 scoped_ptr<dbus::Response> response(GetAccessPointProperty(
732 access_point_proxy, networking_private::kNetworkManagerSsidProperty));
734 if (!response) {
735 return false;
738 // The response should contain a variant that contains an array of bytes.
739 dbus::MessageReader reader(response.get());
740 dbus::MessageReader variant_reader(response.get());
741 if (!reader.PopVariant(&variant_reader)) {
742 LOG(ERROR) << "Unexpected response for " << access_point_path.value()
743 << ": " << response->ToString();
744 return false;
747 const uint8* ssid_bytes = NULL;
748 size_t ssid_length = 0;
749 if (!variant_reader.PopArrayOfBytes(&ssid_bytes, &ssid_length)) {
750 LOG(ERROR) << "Unexpected response for " << access_point_path.value()
751 << ": " << response->ToString();
752 return false;
755 std::string ssidUTF8(ssid_bytes, ssid_bytes + ssid_length);
756 base::string16 ssid = base::UTF8ToUTF16(ssidUTF8);
758 access_point_info->SetString(kAccessPointInfoName, ssid);
761 // Read signal strength.
763 scoped_ptr<dbus::Response> response(GetAccessPointProperty(
764 access_point_proxy,
765 networking_private::kNetworkManagerStrengthProperty));
766 if (!response) {
767 return false;
770 dbus::MessageReader reader(response.get());
771 uint8 strength = 0;
772 if (!reader.PopVariantOfByte(&strength)) {
773 LOG(ERROR) << "Unexpected response for " << access_point_path.value()
774 << ": " << response->ToString();
775 return false;
778 access_point_info->SetInteger(kAccessPointInfoWifiSignalStrengthDotted,
779 strength);
782 // Read the security type. This is from the WpaFlags and RsnFlags property
783 // which are of the same type and can be OR'd together to find all supported
784 // security modes.
786 uint32 wpa_security_flags = 0;
788 scoped_ptr<dbus::Response> response(GetAccessPointProperty(
789 access_point_proxy,
790 networking_private::kNetworkManagerWpaFlagsProperty));
791 if (!response) {
792 return false;
795 dbus::MessageReader reader(response.get());
797 if (!reader.PopVariantOfUint32(&wpa_security_flags)) {
798 LOG(ERROR) << "Unexpected response for " << access_point_path.value()
799 << ": " << response->ToString();
800 return false;
804 uint32 rsn_security_flags = 0;
806 scoped_ptr<dbus::Response> response(GetAccessPointProperty(
807 access_point_proxy,
808 networking_private::kNetworkManagerRsnFlagsProperty));
809 if (!response) {
810 return false;
813 dbus::MessageReader reader(response.get());
815 if (!reader.PopVariantOfUint32(&rsn_security_flags)) {
816 LOG(ERROR) << "Unexpected response for " << access_point_path.value()
817 << ": " << response->ToString();
818 return false;
822 std::string security;
823 MapSecurityFlagsToString(rsn_security_flags | wpa_security_flags, &security);
824 access_point_info->SetString(kAccessPointInfoWifiSecurityDotted, security);
825 access_point_info->SetString(kAccessPointInfoType, kAccessPointInfoTypeWifi);
826 access_point_info->SetBoolean(kAccessPointInfoConnectable, true);
827 return true;
830 bool NetworkingPrivateLinux::AddAccessPointsFromDevice(
831 const dbus::ObjectPath& device_path,
832 NetworkMap* network_map) {
833 AssertOnDBusThread();
834 dbus::ObjectPath connected_access_point;
835 if (!GetConnectedAccessPoint(device_path, &connected_access_point)) {
836 return false;
839 dbus::ObjectProxy* device_proxy = dbus_->GetObjectProxy(
840 networking_private::kNetworkManagerNamespace, device_path);
841 dbus::MethodCall method_call(
842 networking_private::kNetworkManagerWirelessDeviceNamespace,
843 networking_private::kNetworkManagerGetAccessPointsMethod);
844 scoped_ptr<dbus::Response> response(device_proxy->CallMethodAndBlock(
845 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
847 if (!response) {
848 LOG(WARNING) << "Failed to get access points data for "
849 << device_path.value();
850 return false;
853 dbus::MessageReader reader(response.get());
854 std::vector<dbus::ObjectPath> access_point_paths;
855 if (!reader.PopArrayOfObjectPaths(&access_point_paths)) {
856 LOG(ERROR) << "Unexpected response for " << device_path.value() << ": "
857 << response->ToString();
858 return false;
861 for (const auto& access_point_path : access_point_paths) {
862 scoped_ptr<base::DictionaryValue> access_point(new base::DictionaryValue);
864 if (GetAccessPointInfo(access_point_path, access_point)) {
865 std::string connection_state =
866 (access_point_path == connected_access_point)
867 ? ::onc::connection_state::kConnected
868 : ::onc::connection_state::kNotConnected;
870 access_point->SetString(kAccessPointInfoConnectionState,
871 connection_state);
872 std::string ssid;
873 access_point->GetString(kAccessPointInfoName, &ssid);
875 std::string network_guid =
876 ConstructNetworkGuid(device_path, access_point_path, ssid);
878 // Adds the network to the map. Since each SSID can actually have multiple
879 // access point paths, this consolidates them. If it is already
880 // in the map it updates the signal strength and GUID paths if this
881 // network is stronger or the one that is connected.
882 AddOrUpdateAccessPoint(network_map, network_guid, access_point);
886 return true;
889 void NetworkingPrivateLinux::AddOrUpdateAccessPoint(
890 NetworkMap* network_map,
891 const std::string& network_guid,
892 scoped_ptr<base::DictionaryValue>& access_point) {
893 base::string16 ssid;
894 std::string connection_state;
895 int signal_strength;
897 access_point->GetString(kAccessPointInfoConnectionState, &connection_state);
898 access_point->GetInteger(kAccessPointInfoWifiSignalStrengthDotted,
899 &signal_strength);
900 access_point->GetString(kAccessPointInfoName, &ssid);
901 access_point->SetString(kAccessPointInfoGuid, network_guid);
903 NetworkMap::iterator existing_access_point_iter = network_map->find(ssid);
905 if (existing_access_point_iter == network_map->end()) {
906 // Unseen access point. Add it to the map.
907 network_map->insert(NetworkMap::value_type(
908 ssid, linked_ptr<base::DictionaryValue>(access_point.release())));
909 } else {
910 // Already seen access point. Update the record if this is the connected
911 // record or if the signal strength is higher. But don't override a weaker
912 // access point if that is the one that is connected.
913 int existing_signal_strength;
914 linked_ptr<base::DictionaryValue>& existing_access_point =
915 existing_access_point_iter->second;
916 existing_access_point->GetInteger(kAccessPointInfoWifiSignalStrengthDotted,
917 &existing_signal_strength);
919 std::string existing_connection_state;
920 existing_access_point->GetString(kAccessPointInfoConnectionState,
921 &existing_connection_state);
923 if ((connection_state == ::onc::connection_state::kConnected) ||
924 (!(existing_connection_state == ::onc::connection_state::kConnected) &&
925 signal_strength > existing_signal_strength)) {
926 existing_access_point->SetString(kAccessPointInfoConnectionState,
927 connection_state);
928 existing_access_point->SetInteger(
929 kAccessPointInfoWifiSignalStrengthDotted, signal_strength);
930 existing_access_point->SetString(kAccessPointInfoGuid, network_guid);
935 void NetworkingPrivateLinux::MapSecurityFlagsToString(uint32 security_flags,
936 std::string* security) {
937 // Valid values are None, WEP-PSK, WEP-8021X, WPA-PSK, WPA-EAP
938 if (security_flags == NetworkingPrivateLinux::NM_802_11_AP_SEC_NONE) {
939 *security = kAccessPointSecurityNone;
940 } else if (security_flags &
941 NetworkingPrivateLinux::NM_802_11_AP_SEC_KEY_MGMT_PSK) {
942 *security = kAccessPointSecurityWpaPsk;
943 } else if (security_flags &
944 NetworkingPrivateLinux::NM_802_11_AP_SEC_KEY_MGMT_802_1X) {
945 *security = kAccessPointSecurity9021X;
946 } else {
947 DVLOG(1) << "Security flag mapping is missing. Found " << security_flags;
948 *security = kAccessPointSecurityUnknown;
951 DVLOG(1) << "Network security setting " << *security;
954 bool NetworkingPrivateLinux::GetConnectedAccessPoint(
955 dbus::ObjectPath device_path,
956 dbus::ObjectPath* access_point_path) {
957 AssertOnDBusThread();
958 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES,
959 networking_private::kNetworkManagerGetMethod);
960 dbus::MessageWriter builder(&method_call);
961 builder.AppendString(networking_private::kNetworkManagerNamespace);
962 builder.AppendString(networking_private::kNetworkManagerActiveConnections);
964 scoped_ptr<dbus::Response> response(
965 network_manager_proxy_->CallMethodAndBlock(
966 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
968 if (!response) {
969 LOG(WARNING) << "Failed to get a list of active connections";
970 return false;
973 dbus::MessageReader reader(response.get());
974 dbus::MessageReader variant_reader(response.get());
975 if (!reader.PopVariant(&variant_reader)) {
976 LOG(ERROR) << "Unexpected response: " << response->ToString();
977 return false;
980 std::vector<dbus::ObjectPath> connection_paths;
981 if (!variant_reader.PopArrayOfObjectPaths(&connection_paths)) {
982 LOG(ERROR) << "Unexpected response: " << response->ToString();
983 return false;
986 for (const auto& connection_path : connection_paths) {
987 dbus::ObjectPath connections_device_path;
988 if (!GetDeviceOfConnection(connection_path, &connections_device_path)) {
989 return false;
992 if (connections_device_path == device_path) {
993 if (!GetAccessPointForConnection(connection_path, access_point_path)) {
994 return false;
997 break;
1001 return true;
1004 bool NetworkingPrivateLinux::GetDeviceOfConnection(
1005 dbus::ObjectPath connection_path,
1006 dbus::ObjectPath* device_path) {
1007 AssertOnDBusThread();
1008 dbus::ObjectProxy* connection_proxy = dbus_->GetObjectProxy(
1009 networking_private::kNetworkManagerNamespace, connection_path);
1011 if (!connection_proxy) {
1012 return false;
1015 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES,
1016 networking_private::kNetworkManagerGetMethod);
1017 dbus::MessageWriter builder(&method_call);
1018 builder.AppendString(
1019 networking_private::kNetworkManagerActiveConnectionNamespace);
1020 builder.AppendString("Devices");
1022 scoped_ptr<dbus::Response> response(connection_proxy->CallMethodAndBlock(
1023 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
1025 if (!response) {
1026 LOG(ERROR) << "Failed to get devices";
1027 return false;
1030 dbus::MessageReader reader(response.get());
1031 dbus::MessageReader variant_reader(response.get());
1032 if (!reader.PopVariant(&variant_reader)) {
1033 LOG(ERROR) << "Unexpected response: " << response->ToString();
1034 return false;
1037 std::vector<dbus::ObjectPath> device_paths;
1038 if (!variant_reader.PopArrayOfObjectPaths(&device_paths)) {
1039 LOG(ERROR) << "Unexpected response: " << response->ToString();
1040 return false;
1043 if (device_paths.size() == 1) {
1044 *device_path = device_paths[0];
1046 return true;
1049 return false;
1052 bool NetworkingPrivateLinux::GetAccessPointForConnection(
1053 dbus::ObjectPath connection_path,
1054 dbus::ObjectPath* access_point_path) {
1055 AssertOnDBusThread();
1056 dbus::ObjectProxy* connection_proxy = dbus_->GetObjectProxy(
1057 networking_private::kNetworkManagerNamespace, connection_path);
1059 if (!connection_proxy) {
1060 return false;
1063 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES,
1064 networking_private::kNetworkManagerGetMethod);
1065 dbus::MessageWriter builder(&method_call);
1066 builder.AppendString(
1067 networking_private::kNetworkManagerActiveConnectionNamespace);
1068 builder.AppendString(networking_private::kNetworkManagerSpecificObject);
1070 scoped_ptr<dbus::Response> response(connection_proxy->CallMethodAndBlock(
1071 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
1073 if (!response) {
1074 LOG(WARNING) << "Failed to get access point from active connection";
1075 return false;
1078 dbus::MessageReader reader(response.get());
1079 dbus::MessageReader variant_reader(response.get());
1080 if (!reader.PopVariant(&variant_reader)) {
1081 LOG(ERROR) << "Unexpected response: " << response->ToString();
1082 return false;
1085 if (!variant_reader.PopObjectPath(access_point_path)) {
1086 LOG(ERROR) << "Unexpected response: " << response->ToString();
1087 return false;
1090 return true;
1093 bool NetworkingPrivateLinux::SetConnectionStateAndPostEvent(
1094 const std::string& guid,
1095 const std::string& ssid,
1096 const std::string& connection_state) {
1097 AssertOnDBusThread();
1099 NetworkMap::iterator network_iter =
1100 network_map_->find(base::UTF8ToUTF16(ssid));
1101 if (network_iter == network_map_->end()) {
1102 return false;
1105 DVLOG(1) << "Setting connection state of " << ssid << " to "
1106 << connection_state;
1108 // If setting this network to connected, find the previously connected network
1109 // and disconnect that one. Also retain the guid of that network to fire a
1110 // changed event.
1111 std::string connected_network_guid;
1112 if (connection_state == ::onc::connection_state::kConnected) {
1113 for (auto& network : *network_map_) {
1114 std::string other_connection_state;
1115 if (network.second->GetString(kAccessPointInfoConnectionState,
1116 &other_connection_state)) {
1117 if (other_connection_state == ::onc::connection_state::kConnected) {
1118 network.second->GetString(kAccessPointInfoGuid,
1119 &connected_network_guid);
1120 network.second->SetString(kAccessPointInfoConnectionState,
1121 ::onc::connection_state::kNotConnected);
1127 // Set the status.
1128 network_iter->second->SetString(kAccessPointInfoConnectionState,
1129 connection_state);
1131 scoped_ptr<GuidList> changed_networks(new GuidList());
1132 changed_networks->push_back(guid);
1134 // Only add a second network if it exists and it is not the same as the
1135 // network already being added to the list.
1136 if (!connected_network_guid.empty() && connected_network_guid != guid) {
1137 changed_networks->push_back(connected_network_guid);
1140 PostOnNetworksChangedToUIThread(changed_networks.Pass());
1141 return true;
1144 void NetworkingPrivateLinux::OnNetworksChangedEventOnUIThread(
1145 const GuidList& network_guids) {
1146 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1147 FOR_EACH_OBSERVER(NetworkingPrivateDelegateObserver,
1148 network_events_observers_,
1149 OnNetworksChangedEvent(network_guids));
1152 void NetworkingPrivateLinux::OnNetworkListChangedEventOnUIThread(
1153 const GuidList& network_guids) {
1154 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1155 FOR_EACH_OBSERVER(NetworkingPrivateDelegateObserver,
1156 network_events_observers_,
1157 OnNetworkListChangedEvent(network_guids));
1160 void NetworkingPrivateLinux::PostOnNetworksChangedToUIThread(
1161 scoped_ptr<GuidList> guid_list) {
1162 AssertOnDBusThread();
1164 content::BrowserThread::PostTask(
1165 content::BrowserThread::UI, FROM_HERE,
1166 base::Bind(&NetworkingPrivateLinux::OnNetworksChangedEventTask,
1167 base::Unretained(this), base::Passed(&guid_list)));
1170 void NetworkingPrivateLinux::OnNetworksChangedEventTask(
1171 scoped_ptr<GuidList> guid_list) {
1172 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1173 OnNetworksChangedEventOnUIThread(*guid_list);
1176 } // namespace extensions