Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(82)

Side by Side Diff: net/base/network_change_notifier_linux.cc

Issue 8249008: Offline state detection for linux, using new D-Bus library. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: More updates from review Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/base/network_change_notifier_linux.h" 5 #include "net/base/network_change_notifier_linux.h"
6 6
7 #include <errno.h> 7 #include <errno.h>
8 #include <sys/socket.h> 8 #include <sys/socket.h>
9 9
10 #include "base/bind.h" 10 #include "base/bind.h"
11 #include "base/bind_helpers.h" 11 #include "base/bind_helpers.h"
12 #include "base/callback.h" 12 #include "base/callback.h"
13 #include "base/compiler_specific.h" 13 #include "base/compiler_specific.h"
14 #include "base/eintr_wrapper.h" 14 #include "base/eintr_wrapper.h"
15 #include "base/file_util.h" 15 #include "base/file_util.h"
16 #include "base/files/file_path_watcher.h" 16 #include "base/files/file_path_watcher.h"
17 #include "base/memory/weak_ptr.h" 17 #include "base/memory/weak_ptr.h"
18 #include "base/synchronization/lock.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/threading/platform_thread.h"
18 #include "base/threading/thread.h" 21 #include "base/threading/thread.h"
22 #include "dbus/bus.h"
23 #include "dbus/message.h"
24 #include "dbus/object_proxy.h"
19 #include "net/base/net_errors.h" 25 #include "net/base/net_errors.h"
20 #include "net/base/network_change_notifier_netlink_linux.h" 26 #include "net/base/network_change_notifier_netlink_linux.h"
21 27
22 using ::base::files::FilePathWatcher; 28 using ::base::files::FilePathWatcher;
23 29
24 namespace net { 30 namespace net {
25 31
26 namespace { 32 namespace {
27 33
28 const int kInvalidSocket = -1; 34 const int kInvalidSocket = -1;
29 35
36 const char kNetworkManagerServiceName[] = "org.freedesktop.NetworkManager";
37 const char kNetworkManagerPath[] = "/org/freedesktop/NetworkManager";
38 const char kNetworkManagerInterface[] = "org.freedesktop.NetworkManager";
39
40 // http://projects.gnome.org/NetworkManager/developers/spec-08.html#type-NM_STAT E
41 enum {
42 NM_LEGACY_STATE_UNKNOWN = 0,
43 NM_LEGACY_STATE_ASLEEP = 1,
44 NM_LEGACY_STATE_CONNECTING = 2,
45 NM_LEGACY_STATE_CONNECTED = 3,
46 NM_LEGACY_STATE_DISCONNECTED = 4
47 };
48
49 // http://projects.gnome.org/NetworkManager/developers/migrating-to-09/spec.html #type-NM_STATE
50 enum {
51 NM_STATE_UNKNOWN = 0,
52 NM_STATE_ASLEEP = 10,
53 NM_STATE_DISCONNECTED = 20,
54 NM_STATE_DISCONNECTING = 30,
55 NM_STATE_CONNECTING = 40,
56 NM_STATE_CONNECTED_LOCAL = 50,
57 NM_STATE_CONNECTED_SITE = 60,
58 NM_STATE_CONNECTED_GLOBAL = 70
59 };
60
61 // A wrapper around NetworkManager's D-Bus API.
62 class NetworkManagerApi {
63 public:
64 NetworkManagerApi(const base::Closure& notification_callback, dbus::Bus* bus)
65 : is_offline_(false),
66 offline_state_initialized_(true /*manual_reset*/, false),
67 notification_callback_(notification_callback),
68 helper_thread_id_(base::kInvalidThreadId),
69 ALLOW_THIS_IN_INITIALIZER_LIST(ptr_factory_(this)),
70 system_bus_(bus) { }
71
72 ~NetworkManagerApi() { }
73
74 // Should be called on a helper thread which must be of type IO.
75 void Init();
76
77 // Must be called by the helper thread's CleanUp() method.
78 void CleanUp();
79
80 // Implementation of NetworkChangeNotifierLinux::IsCurrentlyOffline().
81 // Safe to call from any thread, but will block until Init() has completed.
82 bool IsCurrentlyOffline();
83
84 private:
85 // Callbacks for D-Bus API.
86 void OnStateChanged(dbus::Message* message);
87
88 void OnResponse(dbus::Response* response) {
89 OnStateChanged(response);
90 offline_state_initialized_.Signal();
91 }
92
93 void OnSignaled(dbus::Signal* signal) {
94 OnStateChanged(signal);
95 }
96
97 void OnConnected(const std::string&, const std::string&, bool success) {
98 if (!success) {
99 DLOG(WARNING) << "Failed to set up offline state detection";
100 offline_state_initialized_.Signal();
101 }
102 }
103
104 // Converts a NetworkManager state uint to a bool.
105 static bool StateIsOffline(uint32 state);
106
107 bool is_offline_;
108 base::Lock is_offline_lock_;
109 base::WaitableEvent offline_state_initialized_;
110
111 base::Closure notification_callback_;
112
113 base::PlatformThreadId helper_thread_id_;
114
115 base::WeakPtrFactory<NetworkManagerApi> ptr_factory_;
116
117 scoped_refptr<dbus::Bus> system_bus_;
118
119 DISALLOW_COPY_AND_ASSIGN(NetworkManagerApi);
120 };
121
122 void NetworkManagerApi::Init() {
123 // D-Bus requires an IO MessageLoop.
124 DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_IO);
125 helper_thread_id_ = base::PlatformThread::CurrentId();
126
127 if (!system_bus_) {
128 dbus::Bus::Options options;
129 options.bus_type = dbus::Bus::SYSTEM;
130 options.connection_type = dbus::Bus::PRIVATE;
131 system_bus_ = new dbus::Bus(options);
132 }
133
134 dbus::ObjectProxy* proxy =
135 system_bus_->GetObjectProxy(kNetworkManagerServiceName,
136 kNetworkManagerPath);
137
138 // Get the initial state asynchronously.
139 dbus::MethodCall method_call(DBUS_INTERFACE_PROPERTIES, "Get");
140 dbus::MessageWriter builder(&method_call);
141 builder.AppendString(kNetworkManagerInterface);
142 builder.AppendString("State");
143 proxy->CallMethod(
144 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
145 base::Bind(&NetworkManagerApi::OnResponse, ptr_factory_.GetWeakPtr()));
146
147 // And sign up for notifications.
148 proxy->ConnectToSignal(
149 kNetworkManagerInterface,
150 "StateChanged",
151 base::Bind(&NetworkManagerApi::OnSignaled, ptr_factory_.GetWeakPtr()),
152 base::Bind(&NetworkManagerApi::OnConnected, ptr_factory_.GetWeakPtr()));
153 }
154
155 void NetworkManagerApi::CleanUp() {
156 DCHECK_EQ(helper_thread_id_, base::PlatformThread::CurrentId());
157 ptr_factory_.InvalidateWeakPtrs();
158 }
159
160 void NetworkManagerApi::OnStateChanged(dbus::Message* message) {
161 DCHECK_EQ(helper_thread_id_, base::PlatformThread::CurrentId());
162 if (!message) {
163 DLOG(WARNING) << "No response received for initial state request";
164 return;
165 }
166 dbus::MessageReader reader(message);
167 uint32 state = 0;
168 if (!reader.HasMoreData() || !reader.PopUint32(&state)) {
169 DLOG(WARNING) << "Unexpected response for NetworkManager State request: "
170 << message->ToString();
171 return;
172 }
173 bool new_is_offline = StateIsOffline(state);
174 {
175 base::AutoLock lock(is_offline_lock_);
176 if (is_offline_ != new_is_offline)
177 is_offline_ = new_is_offline;
178 else
179 return;
180 }
181 if (offline_state_initialized_.IsSignaled())
182 notification_callback_.Run();
183 }
184
185 bool NetworkManagerApi::StateIsOffline(uint32 state) {
186 switch (state) {
187 case NM_LEGACY_STATE_CONNECTED:
188 case NM_STATE_CONNECTED_SITE:
189 case NM_STATE_CONNECTED_GLOBAL:
190 // Definitely connected
191 return false;
192 case NM_LEGACY_STATE_DISCONNECTED:
193 case NM_STATE_DISCONNECTED:
194 // Definitely disconnected
195 return true;
196 case NM_STATE_CONNECTED_LOCAL:
197 // Local networking only; I'm treating this as offline (keybuk)
198 return true;
199 case NM_LEGACY_STATE_CONNECTING:
200 case NM_STATE_DISCONNECTING:
201 case NM_STATE_CONNECTING:
202 // In-flight change to connection status currently underway
203 return true;
204 case NM_LEGACY_STATE_ASLEEP:
205 case NM_STATE_ASLEEP:
206 // Networking disabled or no devices on system
207 return true;
208 default:
209 // Unknown status
210 return false;
211 }
212 }
213
214 bool NetworkManagerApi::IsCurrentlyOffline() {
215 offline_state_initialized_.Wait();
216 base::AutoLock lock(is_offline_lock_);
217 return is_offline_;
218 }
219
30 class DNSWatchDelegate : public FilePathWatcher::Delegate { 220 class DNSWatchDelegate : public FilePathWatcher::Delegate {
31 public: 221 public:
32 explicit DNSWatchDelegate(const base::Closure& callback) 222 explicit DNSWatchDelegate(const base::Closure& callback)
33 : callback_(callback) {} 223 : callback_(callback) {}
34 virtual ~DNSWatchDelegate() {} 224 virtual ~DNSWatchDelegate() {}
35 // FilePathWatcher::Delegate interface 225 // FilePathWatcher::Delegate interface
36 virtual void OnFilePathChanged(const FilePath& path) OVERRIDE; 226 virtual void OnFilePathChanged(const FilePath& path) OVERRIDE;
37 virtual void OnFilePathError(const FilePath& path) OVERRIDE; 227 virtual void OnFilePathError(const FilePath& path) OVERRIDE;
38 private: 228 private:
39 base::Closure callback_; 229 base::Closure callback_;
40 DISALLOW_COPY_AND_ASSIGN(DNSWatchDelegate); 230 DISALLOW_COPY_AND_ASSIGN(DNSWatchDelegate);
41 }; 231 };
42 232
43 void DNSWatchDelegate::OnFilePathChanged(const FilePath& path) { 233 void DNSWatchDelegate::OnFilePathChanged(const FilePath& path) {
44 // Calls NetworkChangeNotifier::NotifyObserversOfDNSChange(). 234 // Calls NetworkChangeNotifier::NotifyObserversOfDNSChange().
45 callback_.Run(); 235 callback_.Run();
46 } 236 }
47 237
48 void DNSWatchDelegate::OnFilePathError(const FilePath& path) { 238 void DNSWatchDelegate::OnFilePathError(const FilePath& path) {
49 LOG(ERROR) << "DNSWatchDelegate::OnFilePathError for " << path.value(); 239 LOG(ERROR) << "DNSWatchDelegate::OnFilePathError for " << path.value();
50 } 240 }
51 241
52 } // namespace 242 } // namespace
53 243
54 class NetworkChangeNotifierLinux::Thread 244 class NetworkChangeNotifierLinux::Thread
55 : public base::Thread, public MessageLoopForIO::Watcher { 245 : public base::Thread, public MessageLoopForIO::Watcher {
56 public: 246 public:
57 Thread(); 247 explicit Thread(dbus::Bus* bus);
58 virtual ~Thread(); 248 virtual ~Thread();
59 249
60 // MessageLoopForIO::Watcher: 250 // MessageLoopForIO::Watcher:
61 virtual void OnFileCanReadWithoutBlocking(int fd); 251 virtual void OnFileCanReadWithoutBlocking(int fd);
62 virtual void OnFileCanWriteWithoutBlocking(int /* fd */); 252 virtual void OnFileCanWriteWithoutBlocking(int /* fd */);
63 253
254 // Plumbing for NetworkChangeNotifier::IsCurrentlyOffline.
255 // Safe to call from any thread.
256 bool IsCurrentlyOffline() {
257 return network_manager_api_.IsCurrentlyOffline();
258 }
259
64 protected: 260 protected:
65 // base::Thread 261 // base::Thread
66 virtual void Init(); 262 virtual void Init();
67 virtual void CleanUp(); 263 virtual void CleanUp();
68 264
69 private: 265 private:
70 void NotifyObserversOfIPAddressChange() { 266 void NotifyObserversOfIPAddressChange() {
71 NetworkChangeNotifier::NotifyObserversOfIPAddressChange(); 267 NetworkChangeNotifier::NotifyObserversOfIPAddressChange();
72 } 268 }
73 269
74 void NotifyObserversOfDNSChange() { 270 static void NotifyObserversOfDNSChange() {
75 NetworkChangeNotifier::NotifyObserversOfDNSChange(); 271 NetworkChangeNotifier::NotifyObserversOfDNSChange();
76 } 272 }
77 273
274 static void NotifyObserversOfOnlineStateChange() {
275 NetworkChangeNotifier::NotifyObserversOfOnlineStateChange();
276 }
277
78 // Starts listening for netlink messages. Also handles the messages if there 278 // Starts listening for netlink messages. Also handles the messages if there
79 // are any available on the netlink socket. 279 // are any available on the netlink socket.
80 void ListenForNotifications(); 280 void ListenForNotifications();
81 281
82 // Attempts to read from the netlink socket into |buf| of length |len|. 282 // Attempts to read from the netlink socket into |buf| of length |len|.
83 // Returns the bytes read on synchronous success and ERR_IO_PENDING if the 283 // Returns the bytes read on synchronous success and ERR_IO_PENDING if the
84 // recv() would block. Otherwise, it returns a net error code. 284 // recv() would block. Otherwise, it returns a net error code.
85 int ReadNotificationMessage(char* buf, size_t len); 285 int ReadNotificationMessage(char* buf, size_t len);
86 286
87 // The netlink socket descriptor. 287 // The netlink socket descriptor.
88 int netlink_fd_; 288 int netlink_fd_;
89 MessageLoopForIO::FileDescriptorWatcher netlink_watcher_; 289 MessageLoopForIO::FileDescriptorWatcher netlink_watcher_;
90 290
91 // Technically only needed for ChromeOS, but it's ugly to #ifdef out. 291 // Technically only needed for ChromeOS, but it's ugly to #ifdef out.
92 base::WeakPtrFactory<Thread> ptr_factory_; 292 base::WeakPtrFactory<Thread> ptr_factory_;
93 293
94 // Used to watch for changes to /etc/resolv.conf and /etc/hosts. 294 // Used to watch for changes to /etc/resolv.conf and /etc/hosts.
95 scoped_ptr<base::files::FilePathWatcher> resolv_file_watcher_; 295 scoped_ptr<base::files::FilePathWatcher> resolv_file_watcher_;
96 scoped_ptr<base::files::FilePathWatcher> hosts_file_watcher_; 296 scoped_ptr<base::files::FilePathWatcher> hosts_file_watcher_;
97 scoped_refptr<DNSWatchDelegate> file_watcher_delegate_; 297 scoped_refptr<DNSWatchDelegate> file_watcher_delegate_;
98 298
299 // Used to detect online/offline state changes.
300 NetworkManagerApi network_manager_api_;
301
99 DISALLOW_COPY_AND_ASSIGN(Thread); 302 DISALLOW_COPY_AND_ASSIGN(Thread);
100 }; 303 };
101 304
102 NetworkChangeNotifierLinux::Thread::Thread() 305 NetworkChangeNotifierLinux::Thread::Thread(dbus::Bus* bus)
103 : base::Thread("NetworkChangeNotifier"), 306 : base::Thread("NetworkChangeNotifier"),
104 netlink_fd_(kInvalidSocket), 307 netlink_fd_(kInvalidSocket),
105 ALLOW_THIS_IN_INITIALIZER_LIST(ptr_factory_(this)) { 308 ALLOW_THIS_IN_INITIALIZER_LIST(ptr_factory_(this)),
309 network_manager_api_(
310 base::Bind(&NetworkChangeNotifierLinux::Thread
311 ::NotifyObserversOfOnlineStateChange),
312 bus) {
106 } 313 }
107 314
108 NetworkChangeNotifierLinux::Thread::~Thread() {} 315 NetworkChangeNotifierLinux::Thread::~Thread() {}
109 316
110 void NetworkChangeNotifierLinux::Thread::Init() { 317 void NetworkChangeNotifierLinux::Thread::Init() {
111 resolv_file_watcher_.reset(new FilePathWatcher); 318 resolv_file_watcher_.reset(new FilePathWatcher);
112 hosts_file_watcher_.reset(new FilePathWatcher); 319 hosts_file_watcher_.reset(new FilePathWatcher);
113 file_watcher_delegate_ = new DNSWatchDelegate(base::Bind( 320 file_watcher_delegate_ = new DNSWatchDelegate(base::Bind(
114 &NetworkChangeNotifierLinux::Thread::NotifyObserversOfDNSChange, 321 &NetworkChangeNotifierLinux::Thread::NotifyObserversOfDNSChange));
115 base::Unretained(this)));
116 if (!resolv_file_watcher_->Watch( 322 if (!resolv_file_watcher_->Watch(
117 FilePath(FILE_PATH_LITERAL("/etc/resolv.conf")), 323 FilePath(FILE_PATH_LITERAL("/etc/resolv.conf")),
118 file_watcher_delegate_.get())) { 324 file_watcher_delegate_.get())) {
119 LOG(ERROR) << "Failed to setup watch for /etc/resolv.conf"; 325 LOG(ERROR) << "Failed to setup watch for /etc/resolv.conf";
120 } 326 }
121 if (!hosts_file_watcher_->Watch(FilePath(FILE_PATH_LITERAL("/etc/hosts")), 327 if (!hosts_file_watcher_->Watch(FilePath(FILE_PATH_LITERAL("/etc/hosts")),
122 file_watcher_delegate_.get())) { 328 file_watcher_delegate_.get())) {
123 LOG(ERROR) << "Failed to setup watch for /etc/hosts"; 329 LOG(ERROR) << "Failed to setup watch for /etc/hosts";
124 } 330 }
125 netlink_fd_ = InitializeNetlinkSocket(); 331 netlink_fd_ = InitializeNetlinkSocket();
126 if (netlink_fd_ < 0) { 332 if (netlink_fd_ < 0) {
127 netlink_fd_ = kInvalidSocket; 333 netlink_fd_ = kInvalidSocket;
128 return; 334 return;
129 } 335 }
130 ListenForNotifications(); 336 ListenForNotifications();
337
338 network_manager_api_.Init();
131 } 339 }
132 340
133 void NetworkChangeNotifierLinux::Thread::CleanUp() { 341 void NetworkChangeNotifierLinux::Thread::CleanUp() {
134 if (netlink_fd_ != kInvalidSocket) { 342 if (netlink_fd_ != kInvalidSocket) {
135 if (HANDLE_EINTR(close(netlink_fd_)) != 0) 343 if (HANDLE_EINTR(close(netlink_fd_)) != 0)
136 PLOG(ERROR) << "Failed to close socket"; 344 PLOG(ERROR) << "Failed to close socket";
137 netlink_fd_ = kInvalidSocket; 345 netlink_fd_ = kInvalidSocket;
138 netlink_watcher_.StopWatchingFileDescriptor(); 346 netlink_watcher_.StopWatchingFileDescriptor();
139 } 347 }
140 // Kill watchers early to make sure they won't try to call 348 // Kill watchers early to make sure they won't try to call
141 // into us via the delegate during destruction. 349 // into us via the delegate during destruction.
142 resolv_file_watcher_.reset(); 350 resolv_file_watcher_.reset();
143 hosts_file_watcher_.reset(); 351 hosts_file_watcher_.reset();
352
353 network_manager_api_.CleanUp();
144 } 354 }
145 355
146 void NetworkChangeNotifierLinux::Thread::OnFileCanReadWithoutBlocking(int fd) { 356 void NetworkChangeNotifierLinux::Thread::OnFileCanReadWithoutBlocking(int fd) {
147 DCHECK_EQ(fd, netlink_fd_); 357 DCHECK_EQ(fd, netlink_fd_);
148 ListenForNotifications(); 358 ListenForNotifications();
149 } 359 }
150 360
151 void NetworkChangeNotifierLinux::Thread::OnFileCanWriteWithoutBlocking( 361 void NetworkChangeNotifierLinux::Thread::OnFileCanWriteWithoutBlocking(
152 int /* fd */) { 362 int /* fd */) {
153 NOTREACHED(); 363 NOTREACHED();
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
198 DCHECK_NE(rv, 0); 408 DCHECK_NE(rv, 0);
199 if (errno != EAGAIN && errno != EWOULDBLOCK) { 409 if (errno != EAGAIN && errno != EWOULDBLOCK) {
200 PLOG(DFATAL) << "recv"; 410 PLOG(DFATAL) << "recv";
201 return ERR_FAILED; 411 return ERR_FAILED;
202 } 412 }
203 413
204 return ERR_IO_PENDING; 414 return ERR_IO_PENDING;
205 } 415 }
206 416
207 NetworkChangeNotifierLinux::NetworkChangeNotifierLinux() 417 NetworkChangeNotifierLinux::NetworkChangeNotifierLinux()
208 : notifier_thread_(new Thread) { 418 : notifier_thread_(new Thread(NULL)) {
209 // We create this notifier thread because the notification implementation 419 // We create this notifier thread because the notification implementation
210 // needs a MessageLoopForIO, and there's no guarantee that 420 // needs a MessageLoopForIO, and there's no guarantee that
211 // MessageLoop::current() meets that criterion. 421 // MessageLoop::current() meets that criterion.
212 base::Thread::Options thread_options(MessageLoop::TYPE_IO, 0); 422 base::Thread::Options thread_options(MessageLoop::TYPE_IO, 0);
213 notifier_thread_->StartWithOptions(thread_options); 423 notifier_thread_->StartWithOptions(thread_options);
214 } 424 }
215 425
426 // Used only for testing, injects a dbus::Bus into the helper thread.
427 NetworkChangeNotifierLinux::NetworkChangeNotifierLinux(dbus::Bus* bus)
428 : notifier_thread_(new Thread(bus)) {
429 base::Thread::Options thread_options(MessageLoop::TYPE_IO, 0);
430 notifier_thread_->StartWithOptions(thread_options);
431 }
432
216 NetworkChangeNotifierLinux::~NetworkChangeNotifierLinux() { 433 NetworkChangeNotifierLinux::~NetworkChangeNotifierLinux() {
217 // We don't need to explicitly Stop(), but doing so allows us to sanity- 434 // We don't need to explicitly Stop(), but doing so allows us to sanity-
218 // check that the notifier thread shut down properly. 435 // check that the notifier thread shut down properly.
219 notifier_thread_->Stop(); 436 notifier_thread_->Stop();
220 } 437 }
221 438
222 bool NetworkChangeNotifierLinux::IsCurrentlyOffline() const { 439 bool NetworkChangeNotifierLinux::IsCurrentlyOffline() const {
223 // TODO(eroman): http://crbug.com/53473 440 return notifier_thread_->IsCurrentlyOffline();
224 return false;
225 } 441 }
226 442
227 } // namespace net 443 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698