blob: e2c523ddfd4e8f72d53d9f3aefb6d0ce623f1bc7 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.database.ContentObserver;
25import android.net.NetworkInfo;
26import android.net.DhcpInfo;
27import android.net.wifi.ScanResult;
28import android.net.wifi.WifiInfo;
29import android.net.wifi.WifiManager;
30import android.net.wifi.WifiStateTracker;
31import android.os.Handler;
32import android.os.Looper;
33import android.os.Message;
34import android.provider.Settings;
35import android.text.TextUtils;
36import android.util.Config;
Joe Onorato8a9b2202010-02-26 18:56:32 -080037import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038
39import java.io.IOException;
40import java.net.DatagramPacket;
41import java.net.DatagramSocket;
42import java.net.InetAddress;
43import java.net.SocketException;
44import java.net.SocketTimeoutException;
45import java.net.UnknownHostException;
46import java.util.List;
47import java.util.Random;
48
49/**
50 * {@link WifiWatchdogService} monitors the initial connection to a Wi-Fi
51 * network with multiple access points. After the framework successfully
52 * connects to an access point, the watchdog verifies whether the DNS server is
53 * reachable. If not, the watchdog blacklists the current access point, leading
54 * to a connection on another access point within the same network.
55 * <p>
56 * The watchdog has a few safeguards:
57 * <ul>
58 * <li>Only monitor networks with multiple access points
59 * <li>Only check at most {@link #getMaxApChecks()} different access points
60 * within the network before giving up
61 * <p>
62 * The watchdog checks for connectivity on an access point by ICMP pinging the
63 * DNS. There are settings that allow disabling the watchdog, or tweaking the
64 * acceptable packet loss (and other various parameters).
65 * <p>
66 * The core logic of the watchdog is done on the main watchdog thread. Wi-Fi
67 * callbacks can come in on other threads, so we must queue messages to the main
68 * watchdog thread's handler. Most (if not all) state is only written to from
69 * the main thread.
70 *
71 * {@hide}
72 */
73public class WifiWatchdogService {
74 private static final String TAG = "WifiWatchdogService";
75 private static final boolean V = false || Config.LOGV;
76 private static final boolean D = true || Config.LOGD;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private Context mContext;
79 private ContentResolver mContentResolver;
80 private WifiStateTracker mWifiStateTracker;
81 private WifiManager mWifiManager;
82
83 /**
84 * The main watchdog thread.
85 */
86 private WifiWatchdogThread mThread;
87 /**
88 * The handler for the main watchdog thread.
89 */
90 private WifiWatchdogHandler mHandler;
91
Irfan Sheriff7b009782010-03-11 16:37:45 -080092 private ContentObserver mContentObserver;
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 /**
95 * The current watchdog state. Only written from the main thread!
96 */
97 private WatchdogState mState = WatchdogState.IDLE;
98 /**
99 * The SSID of the network that the watchdog is currently monitoring. Only
100 * touched in the main thread!
101 */
102 private String mSsid;
103 /**
104 * The number of access points in the current network ({@link #mSsid}) that
105 * have been checked. Only touched in the main thread!
106 */
107 private int mNumApsChecked;
108 /** Whether the current AP check should be canceled. */
109 private boolean mShouldCancel;
110
111 WifiWatchdogService(Context context, WifiStateTracker wifiStateTracker) {
112 mContext = context;
113 mContentResolver = context.getContentResolver();
114 mWifiStateTracker = wifiStateTracker;
115 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
116
117 createThread();
118
119 // The content observer to listen needs a handler, which createThread creates
120 registerForSettingsChanges();
121 if (isWatchdogEnabled()) {
122 registerForWifiBroadcasts();
123 }
124
125 if (V) {
126 myLogV("WifiWatchdogService: Created");
127 }
128 }
129
130 /**
131 * Observes the watchdog on/off setting, and takes action when changed.
132 */
133 private void registerForSettingsChanges() {
134 ContentResolver contentResolver = mContext.getContentResolver();
135 contentResolver.registerContentObserver(
136 Settings.Secure.getUriFor(Settings.Secure.WIFI_WATCHDOG_ON), false,
Irfan Sheriff7b009782010-03-11 16:37:45 -0800137 mContentObserver = new ContentObserver(mHandler) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 @Override
139 public void onChange(boolean selfChange) {
140 if (isWatchdogEnabled()) {
141 registerForWifiBroadcasts();
142 } else {
143 unregisterForWifiBroadcasts();
144 if (mHandler != null) {
145 mHandler.disableWatchdog();
146 }
147 }
148 }
149 });
150 }
151
152 /**
153 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_ON
154 */
155 private boolean isWatchdogEnabled() {
156 return Settings.Secure.getInt(mContentResolver, Settings.Secure.WIFI_WATCHDOG_ON, 1) == 1;
157 }
158
159 /**
160 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_AP_COUNT
161 */
162 private int getApCount() {
163 return Settings.Secure.getInt(mContentResolver,
164 Settings.Secure.WIFI_WATCHDOG_AP_COUNT, 2);
165 }
166
167 /**
168 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT
169 */
170 private int getInitialIgnoredPingCount() {
171 return Settings.Secure.getInt(mContentResolver,
172 Settings.Secure.WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT , 2);
173 }
174
175 /**
176 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_PING_COUNT
177 */
178 private int getPingCount() {
179 return Settings.Secure.getInt(mContentResolver,
180 Settings.Secure.WIFI_WATCHDOG_PING_COUNT, 4);
181 }
182
183 /**
184 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_PING_TIMEOUT_MS
185 */
186 private int getPingTimeoutMs() {
187 return Settings.Secure.getInt(mContentResolver,
188 Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS, 500);
189 }
190
191 /**
192 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_PING_DELAY_MS
193 */
194 private int getPingDelayMs() {
195 return Settings.Secure.getInt(mContentResolver,
196 Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS, 250);
197 }
198
199 /**
200 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE
201 */
202 private int getAcceptablePacketLossPercentage() {
203 return Settings.Secure.getInt(mContentResolver,
204 Settings.Secure.WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE, 25);
205 }
206
207 /**
208 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_MAX_AP_CHECKS
209 */
210 private int getMaxApChecks() {
211 return Settings.Secure.getInt(mContentResolver,
212 Settings.Secure.WIFI_WATCHDOG_MAX_AP_CHECKS, 7);
213 }
214
215 /**
216 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED
217 */
218 private boolean isBackgroundCheckEnabled() {
219 return Settings.Secure.getInt(mContentResolver,
220 Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED, 1) == 1;
221 }
222
223 /**
224 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS
225 */
226 private int getBackgroundCheckDelayMs() {
227 return Settings.Secure.getInt(mContentResolver,
228 Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS, 60000);
229 }
230
231 /**
232 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS
233 */
234 private int getBackgroundCheckTimeoutMs() {
235 return Settings.Secure.getInt(mContentResolver,
236 Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS, 1000);
237 }
238
239 /**
240 * @see android.provider.Settings.Secure#WIFI_WATCHDOG_WATCH_LIST
241 * @return the comma-separated list of SSIDs
242 */
243 private String getWatchList() {
244 return Settings.Secure.getString(mContentResolver,
245 Settings.Secure.WIFI_WATCHDOG_WATCH_LIST);
246 }
247
248 /**
249 * Registers to receive the necessary Wi-Fi broadcasts.
250 */
251 private void registerForWifiBroadcasts() {
252 IntentFilter intentFilter = new IntentFilter();
253 intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
254 intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
255 intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
256 mContext.registerReceiver(mReceiver, intentFilter);
257 }
258
259 /**
260 * Unregisters from receiving the Wi-Fi broadcasts.
261 */
262 private void unregisterForWifiBroadcasts() {
263 mContext.unregisterReceiver(mReceiver);
264 }
265
266 /**
267 * Creates the main watchdog thread, including waiting for the handler to be
268 * created.
269 */
270 private void createThread() {
271 mThread = new WifiWatchdogThread();
272 mThread.start();
273 waitForHandlerCreation();
274 }
275
276 /**
Irfan Sheriff7b009782010-03-11 16:37:45 -0800277 * Unregister broadcasts and quit the watchdog thread
278 */
279 public void quit() {
280 unregisterForWifiBroadcasts();
281 mContext.getContentResolver().unregisterContentObserver(mContentObserver);
282 mHandler.removeAllActions();
283 mHandler.getLooper().quit();
284 }
285
286 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 * Waits for the main watchdog thread to create the handler.
288 */
289 private void waitForHandlerCreation() {
290 synchronized(this) {
291 while (mHandler == null) {
292 try {
293 // Wait for the handler to be set by the other thread
294 wait();
295 } catch (InterruptedException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800296 Slog.e(TAG, "Interrupted while waiting on handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298 }
299 }
300 }
301
302 // Utility methods
303
304 /**
305 * Logs with the current thread.
306 */
307 private static void myLogV(String message) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800308 Slog.v(TAG, "(" + Thread.currentThread().getName() + ") " + message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 }
310
311 private static void myLogD(String message) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800312 Slog.d(TAG, "(" + Thread.currentThread().getName() + ") " + message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314
315 /**
316 * Gets the DNS of the current AP.
317 *
318 * @return The DNS of the current AP.
319 */
320 private int getDns() {
321 DhcpInfo addressInfo = mWifiManager.getDhcpInfo();
322 if (addressInfo != null) {
323 return addressInfo.dns1;
324 } else {
325 return -1;
326 }
327 }
328
329 /**
330 * Checks whether the DNS can be reached using multiple attempts according
331 * to the current setting values.
332 *
333 * @return Whether the DNS is reachable
334 */
335 private boolean checkDnsConnectivity() {
336 int dns = getDns();
337 if (dns == -1) {
338 if (V) {
339 myLogV("checkDnsConnectivity: Invalid DNS, returning false");
340 }
341 return false;
342 }
343
344 if (V) {
345 myLogV("checkDnsConnectivity: Checking 0x" +
346 Integer.toHexString(Integer.reverseBytes(dns)) + " for connectivity");
347 }
348
349 int numInitialIgnoredPings = getInitialIgnoredPingCount();
350 int numPings = getPingCount();
351 int pingDelay = getPingDelayMs();
352 int acceptableLoss = getAcceptablePacketLossPercentage();
353
354 /** See {@link Secure#WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT} */
355 int ignoredPingCounter = 0;
356 int pingCounter = 0;
357 int successCounter = 0;
358
359 // No connectivity check needed
360 if (numPings == 0) {
361 return true;
362 }
363
364 // Do the initial pings that we ignore
365 for (; ignoredPingCounter < numInitialIgnoredPings; ignoredPingCounter++) {
366 if (shouldCancel()) return false;
367
368 boolean dnsAlive = DnsPinger.isDnsReachable(dns, getPingTimeoutMs());
369 if (dnsAlive) {
370 /*
371 * Successful "ignored" pings are *not* ignored (they count in the total number
372 * of pings), but failures are really ignored.
373 */
374 pingCounter++;
375 successCounter++;
376 }
377
378 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800379 Slog.v(TAG, (dnsAlive ? " +" : " Ignored: -"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
382 if (shouldCancel()) return false;
383
384 try {
385 Thread.sleep(pingDelay);
386 } catch (InterruptedException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800387 Slog.w(TAG, "Interrupted while pausing between pings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 }
389 }
390
391 // Do the pings that we use to measure packet loss
392 for (; pingCounter < numPings; pingCounter++) {
393 if (shouldCancel()) return false;
394
395 if (DnsPinger.isDnsReachable(dns, getPingTimeoutMs())) {
396 successCounter++;
397 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800398 Slog.v(TAG, " +");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 }
400 } else {
401 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800402 Slog.v(TAG, " -");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
404 }
405
406 if (shouldCancel()) return false;
407
408 try {
409 Thread.sleep(pingDelay);
410 } catch (InterruptedException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800411 Slog.w(TAG, "Interrupted while pausing between pings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
413 }
414
415 int packetLossPercentage = 100 * (numPings - successCounter) / numPings;
416 if (D) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800417 Slog.d(TAG, packetLossPercentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 + "% packet loss (acceptable is " + acceptableLoss + "%)");
419 }
420
421 return !shouldCancel() && (packetLossPercentage <= acceptableLoss);
422 }
423
424 private boolean backgroundCheckDnsConnectivity() {
425 int dns = getDns();
426 if (false && V) {
427 myLogV("backgroundCheckDnsConnectivity: Background checking " + dns +
428 " for connectivity");
429 }
430
431 if (dns == -1) {
432 if (V) {
433 myLogV("backgroundCheckDnsConnectivity: DNS is empty, returning false");
434 }
435 return false;
436 }
437
438 return DnsPinger.isDnsReachable(dns, getBackgroundCheckTimeoutMs());
439 }
440
441 /**
442 * Signals the current action to cancel.
443 */
444 private void cancelCurrentAction() {
445 mShouldCancel = true;
446 }
447
448 /**
449 * Helper to check whether to cancel.
450 *
451 * @return Whether to cancel processing the action.
452 */
453 private boolean shouldCancel() {
454 if (V && mShouldCancel) {
455 myLogV("shouldCancel: Cancelling");
456 }
457
458 return mShouldCancel;
459 }
460
461 // Wi-Fi initiated callbacks (could be executed in another thread)
462
463 /**
464 * Called when connected to an AP (this can be the next AP in line, or
465 * it can be a completely different network).
466 *
467 * @param ssid The SSID of the access point.
468 * @param bssid The BSSID of the access point.
469 */
470 private void onConnected(String ssid, String bssid) {
471 if (V) {
472 myLogV("onConnected: SSID: " + ssid + ", BSSID: " + bssid);
473 }
474
475 /*
476 * The current action being processed by the main watchdog thread is now
477 * stale, so cancel it.
478 */
479 cancelCurrentAction();
480
481 if ((mSsid == null) || !mSsid.equals(ssid)) {
482 /*
483 * This is a different network than what the main watchdog thread is
484 * processing, dispatch the network change message on the main thread.
485 */
486 mHandler.dispatchNetworkChanged(ssid);
487 }
488
489 if (requiresWatchdog(ssid, bssid)) {
490 if (D) {
491 myLogD(ssid + " (" + bssid + ") requires the watchdog");
492 }
493
494 // This access point requires a watchdog, so queue the check on the main thread
495 mHandler.checkAp(new AccessPoint(ssid, bssid));
496
497 } else {
498 if (D) {
499 myLogD(ssid + " (" + bssid + ") does not require the watchdog");
500 }
501
502 // This access point does not require a watchdog, so queue idle on the main thread
503 mHandler.idle();
504 }
505 }
506
507 /**
508 * Called when Wi-Fi is enabled.
509 */
510 private void onEnabled() {
511 cancelCurrentAction();
512 // Queue a hard-reset of the state on the main thread
513 mHandler.reset();
514 }
515
516 /**
517 * Called when disconnected (or some other event similar to being disconnected).
518 */
519 private void onDisconnected() {
520 if (V) {
521 myLogV("onDisconnected");
522 }
523
524 /*
525 * Disconnected from an access point, the action being processed by the
526 * watchdog thread is now stale, so cancel it.
527 */
528 cancelCurrentAction();
529 // Dispatch the disconnected to the main watchdog thread
530 mHandler.dispatchDisconnected();
531 // Queue the action to go idle
532 mHandler.idle();
533 }
534
535 /**
536 * Checks whether an access point requires watchdog monitoring.
537 *
538 * @param ssid The SSID of the access point.
539 * @param bssid The BSSID of the access point.
540 * @return Whether the access point/network should be monitored by the
541 * watchdog.
542 */
543 private boolean requiresWatchdog(String ssid, String bssid) {
544 if (V) {
545 myLogV("requiresWatchdog: SSID: " + ssid + ", BSSID: " + bssid);
546 }
547
548 WifiInfo info = null;
549 if (ssid == null) {
550 /*
551 * This is called from a Wi-Fi callback, so assume the WifiInfo does
552 * not have stale data.
553 */
554 info = mWifiManager.getConnectionInfo();
555 ssid = info.getSSID();
556 if (ssid == null) {
557 // It's still null, give up
558 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800559 Slog.v(TAG, " Invalid SSID, returning false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561 return false;
562 }
563 }
564
565 if (TextUtils.isEmpty(bssid)) {
566 // Similar as above
567 if (info == null) {
568 info = mWifiManager.getConnectionInfo();
569 }
570 bssid = info.getBSSID();
571 if (TextUtils.isEmpty(bssid)) {
572 // It's still null, give up
573 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800574 Slog.v(TAG, " Invalid BSSID, returning false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576 return false;
577 }
578 }
579
580 if (!isOnWatchList(ssid)) {
581 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800582 Slog.v(TAG, " SSID not on watch list, returning false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584 return false;
585 }
586
587 // The watchdog only monitors networks with multiple APs
588 if (!hasRequiredNumberOfAps(ssid)) {
589 return false;
590 }
591
592 return true;
593 }
594
595 private boolean isOnWatchList(String ssid) {
596 String watchList;
597
598 if (ssid == null || (watchList = getWatchList()) == null) {
599 return false;
600 }
601
602 String[] list = watchList.split(" *, *");
603
604 for (String name : list) {
605 if (ssid.equals(name)) {
606 return true;
607 }
608 }
609
610 return false;
611 }
612
613 /**
614 * Checks if the current scan results have multiple access points with an SSID.
615 *
616 * @param ssid The SSID to check.
617 * @return Whether the SSID has multiple access points.
618 */
619 private boolean hasRequiredNumberOfAps(String ssid) {
620 List<ScanResult> results = mWifiManager.getScanResults();
621 if (results == null) {
622 if (V) {
623 myLogV("hasRequiredNumberOfAps: Got null scan results, returning false");
624 }
625 return false;
626 }
627
628 int numApsRequired = getApCount();
629 int numApsFound = 0;
630 int resultsSize = results.size();
631 for (int i = 0; i < resultsSize; i++) {
632 ScanResult result = results.get(i);
633 if (result == null) continue;
634 if (result.SSID == null) continue;
635
636 if (result.SSID.equals(ssid)) {
637 numApsFound++;
638
639 if (numApsFound >= numApsRequired) {
640 if (V) {
641 myLogV("hasRequiredNumberOfAps: SSID: " + ssid + ", returning true");
642 }
643 return true;
644 }
645 }
646 }
647
648 if (V) {
649 myLogV("hasRequiredNumberOfAps: SSID: " + ssid + ", returning false");
650 }
651 return false;
652 }
653
654 // Watchdog logic (assume all of these methods will be in our main thread)
655
656 /**
657 * Handles a Wi-Fi network change (for example, from networkA to networkB).
658 */
659 private void handleNetworkChanged(String ssid) {
660 // Set the SSID being monitored to the new SSID
661 mSsid = ssid;
662 // Set various state to that when being idle
663 setIdleState(true);
664 }
665
666 /**
667 * Handles checking whether an AP is a "good" AP. If not, it will be blacklisted.
668 *
669 * @param ap The access point to check.
670 */
671 private void handleCheckAp(AccessPoint ap) {
672 // Reset the cancel state since this is the entry point of this action
673 mShouldCancel = false;
674
675 if (V) {
676 myLogV("handleCheckAp: AccessPoint: " + ap);
677 }
678
679 // Make sure we are not sleeping
680 if (mState == WatchdogState.SLEEP) {
681 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 Slog.v(TAG, " Sleeping (in " + mSsid + "), so returning");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684 return;
685 }
686
687 mState = WatchdogState.CHECKING_AP;
688
689 /*
690 * Checks to make sure we haven't exceeded the max number of checks
691 * we're allowed per network
692 */
693 mNumApsChecked++;
694 if (mNumApsChecked > getMaxApChecks()) {
695 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800696 Slog.v(TAG, " Passed the max attempts (" + getMaxApChecks()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 + "), going to sleep for " + mSsid);
698 }
699 mHandler.sleep(mSsid);
700 return;
701 }
702
703 // Do the check
704 boolean isApAlive = checkDnsConnectivity();
705
706 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800707 Slog.v(TAG, " Is it alive: " + isApAlive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709
710 // Take action based on results
711 if (isApAlive) {
712 handleApAlive(ap);
713 } else {
714 handleApUnresponsive(ap);
715 }
716 }
717
718 /**
719 * Handles the case when an access point is alive.
720 *
721 * @param ap The access point.
722 */
723 private void handleApAlive(AccessPoint ap) {
724 // Check whether we are stale and should cancel
725 if (shouldCancel()) return;
726 // We're satisfied with this AP, so go idle
727 setIdleState(false);
728
729 if (D) {
730 myLogD("AP is alive: " + ap.toString());
731 }
732
733 // Queue the next action to be a background check
734 mHandler.backgroundCheckAp(ap);
735 }
736
737 /**
738 * Handles an unresponsive AP by blacklisting it.
739 *
740 * @param ap The access point.
741 */
742 private void handleApUnresponsive(AccessPoint ap) {
743 // Check whether we are stale and should cancel
744 if (shouldCancel()) return;
745 // This AP is "bad", switch to another
746 mState = WatchdogState.SWITCHING_AP;
747
748 if (D) {
749 myLogD("AP is dead: " + ap.toString());
750 }
751
752 // Black list this "bad" AP, this will cause an attempt to connect to another
753 blacklistAp(ap.bssid);
Irfan Sheriff0049a1b2010-01-14 12:37:49 -0800754 // Initiate an association to an alternate AP
755 mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
757
758 private void blacklistAp(String bssid) {
759 if (TextUtils.isEmpty(bssid)) {
760 return;
761 }
762
763 // Before taking action, make sure we should not cancel our processing
764 if (shouldCancel()) return;
765
766 if (!mWifiStateTracker.addToBlacklist(bssid)) {
767 // There's a known bug where this method returns failure on success
Joe Onorato8a9b2202010-02-26 18:56:32 -0800768 //Slog.e(TAG, "Blacklisting " + bssid + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
770
771 if (D) {
772 myLogD("Blacklisting " + bssid);
773 }
774 }
775
776 /**
777 * Handles a single background check. If it fails, it should trigger a
778 * normal check. If it succeeds, it should queue another background check.
779 *
780 * @param ap The access point to do a background check for. If this is no
781 * longer the current AP, it is okay to return without any
782 * processing.
783 */
784 private void handleBackgroundCheckAp(AccessPoint ap) {
785 // Reset the cancel state since this is the entry point of this action
786 mShouldCancel = false;
787
788 if (false && V) {
789 myLogV("handleBackgroundCheckAp: AccessPoint: " + ap);
790 }
791
792 // Make sure we are not sleeping
793 if (mState == WatchdogState.SLEEP) {
794 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800795 Slog.v(TAG, " handleBackgroundCheckAp: Sleeping (in " + mSsid + "), so returning");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797 return;
798 }
799
800 // Make sure the AP we're supposed to be background checking is still the active one
801 WifiInfo info = mWifiManager.getConnectionInfo();
802 if (info.getSSID() == null || !info.getSSID().equals(ap.ssid)) {
803 if (V) {
804 myLogV("handleBackgroundCheckAp: We are no longer connected to "
805 + ap + ", and instead are on " + info);
806 }
807 return;
808 }
809
810 if (info.getBSSID() == null || !info.getBSSID().equals(ap.bssid)) {
811 if (V) {
812 myLogV("handleBackgroundCheckAp: We are no longer connected to "
813 + ap + ", and instead are on " + info);
814 }
815 return;
816 }
817
818 // Do the check
819 boolean isApAlive = backgroundCheckDnsConnectivity();
820
821 if (V && !isApAlive) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800822 Slog.v(TAG, " handleBackgroundCheckAp: Is it alive: " + isApAlive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824
825 if (shouldCancel()) {
826 return;
827 }
828
829 // Take action based on results
830 if (isApAlive) {
831 // Queue another background check
832 mHandler.backgroundCheckAp(ap);
833
834 } else {
835 if (D) {
836 myLogD("Background check failed for " + ap.toString());
837 }
838
839 // Queue a normal check, so it can take proper action
840 mHandler.checkAp(ap);
841 }
842 }
843
844 /**
845 * Handles going to sleep for this network. Going to sleep means we will not
846 * monitor this network anymore.
847 *
848 * @param ssid The network that will not be monitored anymore.
849 */
850 private void handleSleep(String ssid) {
851 // Make sure the network we're trying to sleep in is still the current network
852 if (ssid != null && ssid.equals(mSsid)) {
853 mState = WatchdogState.SLEEP;
854
855 if (D) {
856 myLogD("Going to sleep for " + ssid);
857 }
858
859 /*
860 * Before deciding to go to sleep, we may have checked a few APs
861 * (and blacklisted them). Clear the blacklist so the AP with best
862 * signal is chosen.
863 */
864 if (!mWifiStateTracker.clearBlacklist()) {
865 // There's a known bug where this method returns failure on success
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 //Slog.e(TAG, "Clearing blacklist failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868
869 if (V) {
870 myLogV("handleSleep: Set state to SLEEP and cleared blacklist");
871 }
872 }
873 }
874
875 /**
876 * Handles an access point disconnection.
877 */
878 private void handleDisconnected() {
879 /*
880 * We purposefully do not change mSsid to null. This is to handle
881 * disconnected followed by connected better (even if there is some
882 * duration in between). For example, if the watchdog went to sleep in a
883 * network, and then the phone goes to sleep, when the phone wakes up we
884 * still want to be in the sleeping state. When the phone went to sleep,
885 * we would have gotten a disconnected event which would then set mSsid
886 * = null. This is bad, since the following connect would cause us to do
887 * the "network is good?" check all over again. */
888
889 /*
890 * Set the state as if we were idle (don't come out of sleep, only
891 * hard reset and network changed should do that.
892 */
893 setIdleState(false);
894 }
895
896 /**
897 * Handles going idle. Idle means we are satisfied with the current state of
898 * things, but if a new connection occurs we'll re-evaluate.
899 */
900 private void handleIdle() {
901 // Reset the cancel state since this is the entry point for this action
902 mShouldCancel = false;
903
904 if (V) {
905 myLogV("handleSwitchToIdle");
906 }
907
908 // If we're sleeping, don't do anything
909 if (mState == WatchdogState.SLEEP) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 Slog.v(TAG, " Sleeping (in " + mSsid + "), so returning");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 return;
912 }
913
914 // Set the idle state
915 setIdleState(false);
916
917 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 Slog.v(TAG, " Set state to IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920 }
921
922 /**
923 * Sets the state as if we are going idle.
924 */
925 private void setIdleState(boolean forceIdleState) {
926 // Setting idle state does not kick us out of sleep unless the forceIdleState is set
927 if (forceIdleState || (mState != WatchdogState.SLEEP)) {
928 mState = WatchdogState.IDLE;
929 }
930 mNumApsChecked = 0;
931 }
932
933 /**
934 * Handles a hard reset. A hard reset is rarely used, but when used it
935 * should revert anything done by the watchdog monitoring.
936 */
937 private void handleReset() {
938 mWifiStateTracker.clearBlacklist();
939 setIdleState(true);
940 }
941
942 // Inner classes
943
944 /**
945 * Possible states for the watchdog to be in.
946 */
947 private static enum WatchdogState {
948 /** The watchdog is currently idle, but it is still responsive to future AP checks in this network. */
949 IDLE,
950 /** The watchdog is sleeping, so it will not try any AP checks for the network. */
951 SLEEP,
952 /** The watchdog is currently checking an AP for connectivity. */
953 CHECKING_AP,
954 /** The watchdog is switching to another AP in the network. */
955 SWITCHING_AP
956 }
957
958 /**
959 * The main thread for the watchdog monitoring. This will be turned into a
960 * {@link Looper} thread.
961 */
962 private class WifiWatchdogThread extends Thread {
963 WifiWatchdogThread() {
964 super("WifiWatchdogThread");
965 }
966
967 @Override
968 public void run() {
969 // Set this thread up so the handler will work on it
970 Looper.prepare();
971
972 synchronized(WifiWatchdogService.this) {
973 mHandler = new WifiWatchdogHandler();
974
975 // Notify that the handler has been created
976 WifiWatchdogService.this.notify();
977 }
978
979 // Listen for messages to the handler
980 Looper.loop();
981 }
982 }
983
984 /**
985 * The main thread's handler. There are 'actions', and just general
986 * 'messages'. There should only ever be one 'action' in the queue (aside
987 * from the one being processed, if any). There may be multiple messages in
988 * the queue. So, actions are replaced by more recent actions, where as
989 * messages will be executed for sure. Messages end up being used to just
990 * change some state, and not really take any action.
991 * <p>
992 * There is little logic inside this class, instead methods of the form
993 * "handle___" are called in the main {@link WifiWatchdogService}.
994 */
995 private class WifiWatchdogHandler extends Handler {
996 /** Check whether the AP is "good". The object will be an {@link AccessPoint}. */
997 static final int ACTION_CHECK_AP = 1;
998 /** Go into the idle state. */
999 static final int ACTION_IDLE = 2;
1000 /**
1001 * Performs a periodic background check whether the AP is still "good".
1002 * The object will be an {@link AccessPoint}.
1003 */
1004 static final int ACTION_BACKGROUND_CHECK_AP = 3;
1005
1006 /**
1007 * Go to sleep for the current network. We are conservative with making
1008 * this a message rather than action. We want to make sure our main
1009 * thread sees this message, but if it were an action it could be
1010 * removed from the queue and replaced by another action. The main
1011 * thread will ensure when it sees the message that the state is still
1012 * valid for going to sleep.
1013 * <p>
1014 * For an explanation of sleep, see {@link android.provider.Settings.Secure#WIFI_WATCHDOG_MAX_AP_CHECKS}.
1015 */
1016 static final int MESSAGE_SLEEP = 101;
1017 /** Disables the watchdog. */
1018 static final int MESSAGE_DISABLE_WATCHDOG = 102;
1019 /** The network has changed. */
1020 static final int MESSAGE_NETWORK_CHANGED = 103;
1021 /** The current access point has disconnected. */
1022 static final int MESSAGE_DISCONNECTED = 104;
1023 /** Performs a hard-reset on the watchdog state. */
1024 static final int MESSAGE_RESET = 105;
1025
1026 void checkAp(AccessPoint ap) {
1027 removeAllActions();
1028 sendMessage(obtainMessage(ACTION_CHECK_AP, ap));
1029 }
1030
1031 void backgroundCheckAp(AccessPoint ap) {
1032 if (!isBackgroundCheckEnabled()) return;
1033
1034 removeAllActions();
1035 sendMessageDelayed(obtainMessage(ACTION_BACKGROUND_CHECK_AP, ap),
1036 getBackgroundCheckDelayMs());
1037 }
1038
1039 void idle() {
1040 removeAllActions();
1041 sendMessage(obtainMessage(ACTION_IDLE));
1042 }
1043
1044 void sleep(String ssid) {
1045 removeAllActions();
1046 sendMessage(obtainMessage(MESSAGE_SLEEP, ssid));
1047 }
1048
1049 void disableWatchdog() {
1050 removeAllActions();
1051 sendMessage(obtainMessage(MESSAGE_DISABLE_WATCHDOG));
1052 }
1053
1054 void dispatchNetworkChanged(String ssid) {
1055 removeAllActions();
1056 sendMessage(obtainMessage(MESSAGE_NETWORK_CHANGED, ssid));
1057 }
1058
1059 void dispatchDisconnected() {
1060 removeAllActions();
1061 sendMessage(obtainMessage(MESSAGE_DISCONNECTED));
1062 }
1063
1064 void reset() {
1065 removeAllActions();
1066 sendMessage(obtainMessage(MESSAGE_RESET));
1067 }
1068
1069 private void removeAllActions() {
1070 removeMessages(ACTION_CHECK_AP);
1071 removeMessages(ACTION_IDLE);
1072 removeMessages(ACTION_BACKGROUND_CHECK_AP);
1073 }
1074
1075 @Override
1076 public void handleMessage(Message msg) {
1077 switch (msg.what) {
1078 case MESSAGE_NETWORK_CHANGED:
1079 handleNetworkChanged((String) msg.obj);
1080 break;
1081 case ACTION_CHECK_AP:
1082 handleCheckAp((AccessPoint) msg.obj);
1083 break;
1084 case ACTION_BACKGROUND_CHECK_AP:
1085 handleBackgroundCheckAp((AccessPoint) msg.obj);
1086 break;
1087 case MESSAGE_SLEEP:
1088 handleSleep((String) msg.obj);
1089 break;
1090 case ACTION_IDLE:
1091 handleIdle();
1092 break;
1093 case MESSAGE_DISABLE_WATCHDOG:
1094 handleIdle();
1095 break;
1096 case MESSAGE_DISCONNECTED:
1097 handleDisconnected();
1098 break;
1099 case MESSAGE_RESET:
1100 handleReset();
1101 break;
1102 }
1103 }
1104 }
1105
1106 /**
1107 * Receives Wi-Fi broadcasts.
1108 * <p>
1109 * There is little logic in this class, instead methods of the form "on___"
1110 * are called in the {@link WifiWatchdogService}.
1111 */
1112 private BroadcastReceiver mReceiver = new BroadcastReceiver() {
1113
1114 @Override
1115 public void onReceive(Context context, Intent intent) {
1116 final String action = intent.getAction();
1117 if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
1118 handleNetworkStateChanged(
1119 (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO));
1120 } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
1121 handleSupplicantConnectionChanged(
1122 intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false));
1123 } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
1124 handleWifiStateChanged(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
1125 WifiManager.WIFI_STATE_UNKNOWN));
1126 }
1127 }
1128
1129 private void handleNetworkStateChanged(NetworkInfo info) {
1130 if (V) {
1131 myLogV("Receiver.handleNetworkStateChanged: NetworkInfo: "
1132 + info);
1133 }
1134
1135 switch (info.getState()) {
1136 case CONNECTED:
1137 WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
1138 if (wifiInfo.getSSID() == null || wifiInfo.getBSSID() == null) {
1139 if (V) {
1140 myLogV("handleNetworkStateChanged: Got connected event but SSID or BSSID are null. SSID: "
1141 + wifiInfo.getSSID()
1142 + ", BSSID: "
1143 + wifiInfo.getBSSID() + ", ignoring event");
1144 }
1145 return;
1146 }
1147 onConnected(wifiInfo.getSSID(), wifiInfo.getBSSID());
1148 break;
1149
1150 case DISCONNECTED:
1151 onDisconnected();
1152 break;
1153 }
1154 }
1155
1156 private void handleSupplicantConnectionChanged(boolean connected) {
1157 if (!connected) {
1158 onDisconnected();
1159 }
1160 }
1161
1162 private void handleWifiStateChanged(int wifiState) {
1163 if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
1164 onDisconnected();
1165 } else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
1166 onEnabled();
1167 }
1168 }
1169 };
1170
1171 /**
1172 * Describes an access point by its SSID and BSSID.
1173 */
1174 private static class AccessPoint {
1175 String ssid;
1176 String bssid;
1177
1178 AccessPoint(String ssid, String bssid) {
1179 this.ssid = ssid;
1180 this.bssid = bssid;
1181 }
1182
1183 private boolean hasNull() {
1184 return ssid == null || bssid == null;
1185 }
1186
1187 @Override
1188 public boolean equals(Object o) {
1189 if (!(o instanceof AccessPoint)) return false;
1190 AccessPoint otherAp = (AccessPoint) o;
1191 boolean iHaveNull = hasNull();
1192 // Either we both have a null, or our SSIDs and BSSIDs are equal
1193 return (iHaveNull && otherAp.hasNull()) ||
1194 (otherAp.bssid != null && ssid.equals(otherAp.ssid)
1195 && bssid.equals(otherAp.bssid));
1196 }
1197
1198 @Override
1199 public int hashCode() {
1200 if (ssid == null || bssid == null) return 0;
1201 return ssid.hashCode() + bssid.hashCode();
1202 }
1203
1204 @Override
1205 public String toString() {
1206 return ssid + " (" + bssid + ")";
1207 }
1208 }
1209
1210 /**
1211 * Performs a simple DNS "ping" by sending a "server status" query packet to
1212 * the DNS server. As long as the server replies, we consider it a success.
1213 * <p>
1214 * We do not use a simple hostname lookup because that could be cached and
1215 * the API may not differentiate between a time out and a failure lookup
1216 * (which we really care about).
1217 */
1218 private static class DnsPinger {
1219
1220 /** Number of bytes for the query */
1221 private static final int DNS_QUERY_BASE_SIZE = 33;
1222
1223 /** The DNS port */
1224 private static final int DNS_PORT = 53;
1225
1226 /** Used to generate IDs */
1227 private static Random sRandom = new Random();
1228
1229 static boolean isDnsReachable(int dns, int timeout) {
1230 try {
1231 DatagramSocket socket = new DatagramSocket();
1232
1233 // Set some socket properties
1234 socket.setSoTimeout(timeout);
1235
1236 byte[] buf = new byte[DNS_QUERY_BASE_SIZE];
1237 fillQuery(buf);
1238
1239 // Send the DNS query
1240 byte parts[] = new byte[4];
1241 parts[0] = (byte)(dns & 0xff);
1242 parts[1] = (byte)((dns >> 8) & 0xff);
1243 parts[2] = (byte)((dns >> 16) & 0xff);
1244 parts[3] = (byte)((dns >> 24) & 0xff);
1245
1246 InetAddress dnsAddress = InetAddress.getByAddress(parts);
1247 DatagramPacket packet = new DatagramPacket(buf,
1248 buf.length, dnsAddress, DNS_PORT);
1249 socket.send(packet);
1250
1251 // Wait for reply (blocks for the above timeout)
1252 DatagramPacket replyPacket = new DatagramPacket(buf, buf.length);
1253 socket.receive(replyPacket);
1254
1255 // If a timeout occurred, an exception would have been thrown. We got a reply!
1256 return true;
1257
1258 } catch (SocketException e) {
1259 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001260 Slog.v(TAG, "DnsPinger.isReachable received SocketException", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262 return false;
1263
1264 } catch (UnknownHostException e) {
1265 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001266 Slog.v(TAG, "DnsPinger.isReachable is unable to resolve the DNS host", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268 return false;
1269
1270 } catch (SocketTimeoutException e) {
1271 return false;
1272
1273 } catch (IOException e) {
1274 if (V) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001275 Slog.v(TAG, "DnsPinger.isReachable got an IOException", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277 return false;
1278
1279 } catch (Exception e) {
1280 if (V || Config.LOGD) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001281 Slog.d(TAG, "DnsPinger.isReachable got an unknown exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 }
1283 return false;
1284 }
1285 }
1286
1287 private static void fillQuery(byte[] buf) {
1288
1289 /*
1290 * See RFC2929 (though the bit tables in there are misleading for
1291 * us. For example, the recursion desired bit is the 0th bit for us,
1292 * but looking there it would appear as the 7th bit of the byte
1293 */
1294
1295 // Make sure it's all zeroed out
1296 for (int i = 0; i < buf.length; i++) buf[i] = 0;
1297
1298 // Form a query for www.android.com
1299
1300 // [0-1] bytes are an ID, generate random ID for this query
1301 buf[0] = (byte) sRandom.nextInt(256);
1302 buf[1] = (byte) sRandom.nextInt(256);
1303
1304 // [2-3] bytes are for flags.
1305 buf[2] = 1; // Recursion desired
1306
1307 // [4-5] bytes are for the query count
1308 buf[5] = 1; // One query
1309
1310 // [6-7] [8-9] [10-11] are all counts of other fields we don't use
1311
1312 // [12-15] for www
1313 writeString(buf, 12, "www");
1314
1315 // [16-23] for android
1316 writeString(buf, 16, "android");
1317
1318 // [24-27] for com
1319 writeString(buf, 24, "com");
1320
1321 // [29-30] bytes are for QTYPE, set to 1
1322 buf[30] = 1;
1323
1324 // [31-32] bytes are for QCLASS, set to 1
1325 buf[32] = 1;
1326 }
1327
1328 private static void writeString(byte[] buf, int startPos, String string) {
1329 int pos = startPos;
1330
1331 // Write the length first
1332 buf[pos++] = (byte) string.length();
1333 for (int i = 0; i < string.length(); i++) {
1334 buf[pos++] = (byte) string.charAt(i);
1335 }
1336 }
1337 }
1338}