blob: ddf92e2a9d37904c9a61f67b5e6d36121d9a9772 [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 static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.app.AlarmManager;
26import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070027import android.bluetooth.BluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
34import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
37import android.net.wifi.WifiNative;
38import android.net.wifi.WifiStateTracker;
39import android.net.wifi.ScanResult;
40import android.net.wifi.WifiConfiguration;
41import android.net.NetworkStateTracker;
42import android.net.DhcpInfo;
43import android.os.Binder;
44import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.Looper;
48import android.os.Message;
49import android.os.PowerManager;
50import android.os.RemoteException;
51import android.provider.Settings;
52import android.util.Log;
The Android Open Source Project10592532009-03-18 17:39:46 -070053import android.telephony.TelephonyManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.text.TextUtils;
55
56import java.util.ArrayList;
57import java.util.BitSet;
58import java.util.HashMap;
59import java.util.LinkedHashMap;
60import java.util.List;
61import java.util.Map;
62import java.util.regex.Pattern;
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066import com.android.internal.app.IBatteryStats;
67import com.android.internal.os.BatteryStatsImpl;
68import com.android.server.am.BatteryStatsService;
69
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070/**
71 * WifiService handles remote WiFi operation requests by implementing
72 * the IWifiManager interface. It also creates a WifiMonitor to listen
73 * for Wifi-related events.
74 *
75 * @hide
76 */
77public class WifiService extends IWifiManager.Stub {
78 private static final String TAG = "WifiService";
79 private static final boolean DBG = false;
80 private static final Pattern scanResultPattern = Pattern.compile("\t+");
81 private final WifiStateTracker mWifiStateTracker;
82
83 private Context mContext;
84 private int mWifiState;
85
86 private AlarmManager mAlarmManager;
87 private PendingIntent mIdleIntent;
88 private static final int IDLE_REQUEST = 0;
89 private boolean mScreenOff;
90 private boolean mDeviceIdle;
91 private int mPluggedType;
92
93 private final LockList mLocks = new LockList();
The Android Open Source Project10592532009-03-18 17:39:46 -070094
95 private final IBatteryStats mBatteryStats;
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 /**
98 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
99 * Settings.Gservices value is not present. This timeout value is chosen as
100 * the approximate point at which the battery drain caused by Wi-Fi
101 * being enabled but not active exceeds the battery drain caused by
102 * re-establishing a connection to the mobile data network.
103 */
104 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
105
106 private static final String WAKELOCK_TAG = "WifiService";
107
108 /**
109 * The maximum amount of time to hold the wake lock after a disconnect
110 * caused by stopping the driver. Establishing an EDGE connection has been
111 * observed to take about 5 seconds under normal circumstances. This
112 * provides a bit of extra margin.
113 * <p>
114 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
115 * This is the default value if a Settings.Secure value is not present.
116 */
117 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
118
119 // Wake lock used by driver-stop operation
120 private static PowerManager.WakeLock sDriverStopWakeLock;
121 // Wake lock used by other operations
122 private static PowerManager.WakeLock sWakeLock;
123
124 private static final int MESSAGE_ENABLE_WIFI = 0;
125 private static final int MESSAGE_DISABLE_WIFI = 1;
126 private static final int MESSAGE_STOP_WIFI = 2;
127 private static final int MESSAGE_START_WIFI = 3;
128 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
129
130 private final WifiHandler mWifiHandler;
131
132 /*
133 * Map used to keep track of hidden networks presence, which
134 * is needed to switch between active and passive scan modes.
135 * If there is at least one hidden network that is currently
136 * present (enabled), we want to do active scans instead of
137 * passive.
138 */
139 private final Map<Integer, Boolean> mIsHiddenNetworkPresent;
140 /*
141 * The number of currently present hidden networks. When this
142 * counter goes from 0 to 1 or from 1 to 0, we change the
143 * scan mode to active or passive respectively. Initially, we
144 * set the counter to 0 and we increment it every time we add
145 * a new present (enabled) hidden network.
146 */
147 private int mNumHiddenNetworkPresent;
148 /*
149 * Whether we change the scan mode is due to a hidden network
150 * (in this class, this is always the case)
151 */
152 private final static boolean SET_DUE_TO_A_HIDDEN_NETWORK = true;
153
154 /*
155 * Cache of scan results objects (size is somewhat arbitrary)
156 */
157 private static final int SCAN_RESULT_CACHE_SIZE = 80;
158 private final LinkedHashMap<String, ScanResult> mScanResultCache;
159
160 /*
161 * Character buffer used to parse scan results (optimization)
162 */
163 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
164 private char[] mScanResultBuffer;
165 private boolean mNeedReconfig;
166
167 /**
168 * Number of allowed radio frequency channels in various regulatory domains.
169 * This list is sufficient for 802.11b/g networks (2.4GHz range).
170 */
171 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
172
173 private static final String ACTION_DEVICE_IDLE =
174 "com.android.server.WifiManager.action.DEVICE_IDLE";
175
176 WifiService(Context context, WifiStateTracker tracker) {
177 mContext = context;
178 mWifiStateTracker = tracker;
The Android Open Source Project10592532009-03-18 17:39:46 -0700179 mBatteryStats = BatteryStatsService.getService();
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 /*
182 * Initialize the hidden-networks state
183 */
184 mIsHiddenNetworkPresent = new HashMap<Integer, Boolean>();
185 mNumHiddenNetworkPresent = 0;
186
187 mScanResultCache = new LinkedHashMap<String, ScanResult>(
188 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
189 /*
190 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
191 * elements
192 */
193 public boolean removeEldestEntry(Map.Entry eldest) {
194 return SCAN_RESULT_CACHE_SIZE < this.size();
195 }
196 };
197
198 mScanResultBuffer = new char [SCAN_RESULT_BUFFER_SIZE];
199
200 HandlerThread wifiThread = new HandlerThread("WifiService");
201 wifiThread.start();
202 mWifiHandler = new WifiHandler(wifiThread.getLooper());
203
204 mWifiState = WIFI_STATE_DISABLED;
205 boolean wifiEnabled = getPersistedWifiEnabled();
206
207 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
208 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
209 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
210
211 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
212 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
213 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
214 mWifiStateTracker.setReleaseWakeLockCallback(
215 new Runnable() {
216 public void run() {
217 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
218 synchronized (sDriverStopWakeLock) {
219 if (sDriverStopWakeLock.isHeld()) {
220 sDriverStopWakeLock.release();
221 }
222 }
223 }
224 }
225 );
226
227 Log.i(TAG, "WifiService starting up with Wi-Fi " +
228 (wifiEnabled ? "enabled" : "disabled"));
229
230 mContext.registerReceiver(
231 new BroadcastReceiver() {
232 @Override
233 public void onReceive(Context context, Intent intent) {
234 updateWifiState();
235 }
236 },
237 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
238
239 setWifiEnabledBlocking(wifiEnabled, false);
240 }
241
242 /**
243 * Initializes the hidden networks state. Must be called when we
244 * enable Wi-Fi.
245 */
246 private synchronized void initializeHiddenNetworksState() {
247 // First, reset the state
248 resetHiddenNetworksState();
249
250 // ... then add networks that are marked as hidden
251 List<WifiConfiguration> networks = getConfiguredNetworks();
252 if (!networks.isEmpty()) {
253 for (WifiConfiguration config : networks) {
254 if (config != null && config.hiddenSSID) {
255 addOrUpdateHiddenNetwork(
256 config.networkId,
257 config.status != WifiConfiguration.Status.DISABLED);
258 }
259 }
260
261 }
262 }
263
264 /**
265 * Resets the hidden networks state.
266 */
267 private synchronized void resetHiddenNetworksState() {
268 mNumHiddenNetworkPresent = 0;
269 mIsHiddenNetworkPresent.clear();
270 }
271
272 /**
273 * Marks all but netId network as not present.
274 */
275 private synchronized void markAllHiddenNetworksButOneAsNotPresent(int netId) {
276 for (Map.Entry<Integer, Boolean> entry : mIsHiddenNetworkPresent.entrySet()) {
277 if (entry != null) {
278 Integer networkId = entry.getKey();
279 if (networkId != netId) {
280 updateNetworkIfHidden(
281 networkId, false);
282 }
283 }
284 }
285 }
286
287 /**
288 * Updates the netId network presence status if netId is an existing
289 * hidden network.
290 */
291 private synchronized void updateNetworkIfHidden(int netId, boolean present) {
292 if (isHiddenNetwork(netId)) {
293 addOrUpdateHiddenNetwork(netId, present);
294 }
295 }
296
297 /**
298 * Updates the netId network presence status if netId is an existing
299 * hidden network. If the network does not exist, adds the network.
300 */
301 private synchronized void addOrUpdateHiddenNetwork(int netId, boolean present) {
302 if (0 <= netId) {
303
304 // If we are adding a new entry or modifying an existing one
305 Boolean isPresent = mIsHiddenNetworkPresent.get(netId);
306 if (isPresent == null || isPresent != present) {
307 if (present) {
308 incrementHiddentNetworkPresentCounter();
309 } else {
310 // If we add a new hidden network, no need to change
311 // the counter (it must be 0)
312 if (isPresent != null) {
313 decrementHiddentNetworkPresentCounter();
314 }
315 }
316 mIsHiddenNetworkPresent.put(netId, present);
317 }
318 } else {
319 Log.e(TAG, "addOrUpdateHiddenNetwork(): Invalid (negative) network id!");
320 }
321 }
322
323 /**
324 * Removes the netId network if it is hidden (being kept track of).
325 */
326 private synchronized void removeNetworkIfHidden(int netId) {
327 if (isHiddenNetwork(netId)) {
328 removeHiddenNetwork(netId);
329 }
330 }
331
332 /**
333 * Removes the netId network. For the call to be successful, the network
334 * must be hidden.
335 */
336 private synchronized void removeHiddenNetwork(int netId) {
337 if (0 <= netId) {
338 Boolean isPresent =
339 mIsHiddenNetworkPresent.remove(netId);
340 if (isPresent != null) {
341 // If we remove an existing hidden network that is not
342 // present, no need to change the counter
343 if (isPresent) {
344 decrementHiddentNetworkPresentCounter();
345 }
346 } else {
347 if (DBG) {
348 Log.d(TAG, "removeHiddenNetwork(): Removing a non-existent network!");
349 }
350 }
351 } else {
352 Log.e(TAG, "removeHiddenNetwork(): Invalid (negative) network id!");
353 }
354 }
355
356 /**
357 * Returns true if netId is an existing hidden network.
358 */
359 private synchronized boolean isHiddenNetwork(int netId) {
360 return mIsHiddenNetworkPresent.containsKey(netId);
361 }
362
363 /**
364 * Increments the present (enabled) hidden networks counter. If the
365 * counter value goes from 0 to 1, changes the scan mode to active.
366 */
367 private void incrementHiddentNetworkPresentCounter() {
368 ++mNumHiddenNetworkPresent;
369 if (1 == mNumHiddenNetworkPresent) {
370 // Switch the scan mode to "active"
371 mWifiStateTracker.setScanMode(true, SET_DUE_TO_A_HIDDEN_NETWORK);
372 }
373 }
374
375 /**
376 * Decrements the present (enabled) hidden networks counter. If the
377 * counter goes from 1 to 0, changes the scan mode back to passive.
378 */
379 private void decrementHiddentNetworkPresentCounter() {
380 if (0 < mNumHiddenNetworkPresent) {
381 --mNumHiddenNetworkPresent;
382 if (0 == mNumHiddenNetworkPresent) {
383 // Switch the scan mode to "passive"
384 mWifiStateTracker.setScanMode(false, SET_DUE_TO_A_HIDDEN_NETWORK);
385 }
386 } else {
387 Log.e(TAG, "Hidden-network counter invariant violation!");
388 }
389 }
390
391 private boolean getPersistedWifiEnabled() {
392 final ContentResolver cr = mContext.getContentResolver();
393 try {
394 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
395 } catch (Settings.SettingNotFoundException e) {
396 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
397 return false;
398 }
399 }
400
401 private void persistWifiEnabled(boolean enabled) {
402 final ContentResolver cr = mContext.getContentResolver();
403 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
404 }
405
406 NetworkStateTracker getNetworkStateTracker() {
407 return mWifiStateTracker;
408 }
409
410 /**
411 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
412 * @return {@code true} if the operation succeeds
413 */
414 public boolean pingSupplicant() {
415 enforceChangePermission();
416 synchronized (mWifiStateTracker) {
417 return WifiNative.pingCommand();
418 }
419 }
420
421 /**
422 * see {@link android.net.wifi.WifiManager#startScan()}
423 * @return {@code true} if the operation succeeds
424 */
425 public boolean startScan() {
426 enforceChangePermission();
427 synchronized (mWifiStateTracker) {
428 switch (mWifiStateTracker.getSupplicantState()) {
429 case DISCONNECTED:
430 case INACTIVE:
431 case SCANNING:
432 case DORMANT:
433 break;
434 default:
435 WifiNative.setScanResultHandlingCommand(
436 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
437 break;
438 }
439 return WifiNative.scanCommand();
440 }
441 }
442
443 /**
444 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
445 * @param enable {@code true} to enable, {@code false} to disable.
446 * @return {@code true} if the enable/disable operation was
447 * started or is already in the queue.
448 */
449 public boolean setWifiEnabled(boolean enable) {
450 enforceChangePermission();
451 if (mWifiHandler == null) return false;
452
453 synchronized (mWifiHandler) {
454 sWakeLock.acquire();
455 sendEnableMessage(enable, true);
456 }
457
458 return true;
459 }
460
461 /**
462 * Enables/disables Wi-Fi synchronously.
463 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
464 * @param persist {@code true} if the setting should be persisted.
465 * @return {@code true} if the operation succeeds (or if the existing state
466 * is the same as the requested state)
467 */
468 private boolean setWifiEnabledBlocking(boolean enable, boolean persist) {
469 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
470
471 if (mWifiState == eventualWifiState) {
472 return true;
473 }
474 if (enable && isAirplaneModeOn()) {
475 return false;
476 }
477
478 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING);
479
480 if (enable) {
481 if (!WifiNative.loadDriver()) {
482 Log.e(TAG, "Failed to load Wi-Fi driver.");
483 setWifiEnabledState(WIFI_STATE_UNKNOWN);
484 return false;
485 }
486 if (!WifiNative.startSupplicant()) {
487 WifiNative.unloadDriver();
488 Log.e(TAG, "Failed to start supplicant daemon.");
489 setWifiEnabledState(WIFI_STATE_UNKNOWN);
490 return false;
491 }
492 registerForBroadcasts();
493 mWifiStateTracker.startEventLoop();
494 } else {
495
496 mContext.unregisterReceiver(mReceiver);
497 // Remove notification (it will no-op if it isn't visible)
498 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
499
500 boolean failedToStopSupplicantOrUnloadDriver = false;
501 if (!WifiNative.stopSupplicant()) {
502 Log.e(TAG, "Failed to stop supplicant daemon.");
503 setWifiEnabledState(WIFI_STATE_UNKNOWN);
504 failedToStopSupplicantOrUnloadDriver = true;
505 }
506
507 // We must reset the interface before we unload the driver
508 mWifiStateTracker.resetInterface();
509
510 if (!WifiNative.unloadDriver()) {
511 Log.e(TAG, "Failed to unload Wi-Fi driver.");
512 if (!failedToStopSupplicantOrUnloadDriver) {
513 setWifiEnabledState(WIFI_STATE_UNKNOWN);
514 failedToStopSupplicantOrUnloadDriver = true;
515 }
516 }
517 if (failedToStopSupplicantOrUnloadDriver) {
518 return false;
519 }
520 }
521
522 // Success!
523
524 if (persist) {
525 persistWifiEnabled(enable);
526 }
527 setWifiEnabledState(eventualWifiState);
528
529 /*
530 * Initialize the hidden networks state and the number of allowed
531 * radio channels if Wi-Fi is being turned on.
532 */
533 if (enable) {
534 mWifiStateTracker.setNumAllowedChannels();
535 initializeHiddenNetworksState();
536 }
537
538 return true;
539 }
540
541 private void setWifiEnabledState(int wifiState) {
542 final int previousWifiState = mWifiState;
543
The Android Open Source Project10592532009-03-18 17:39:46 -0700544 long ident = Binder.clearCallingIdentity();
545 try {
546 if (wifiState == WIFI_STATE_ENABLED) {
547 mBatteryStats.noteWifiOn();
548 } else if (wifiState == WIFI_STATE_DISABLED) {
549 mBatteryStats.noteWifiOff();
550 }
551 } catch (RemoteException e) {
552 } finally {
553 Binder.restoreCallingIdentity(ident);
554 }
555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 // Update state
557 mWifiState = wifiState;
558
559 // Broadcast
560 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
561 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
562 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
563 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
564 mContext.sendStickyBroadcast(intent);
565 }
566
567 private void enforceAccessPermission() {
568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
569 "WifiService");
570 }
571
572 private void enforceChangePermission() {
573 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
574 "WifiService");
575
576 }
577
578 /**
579 * see {@link WifiManager#getWifiState()}
580 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
581 * {@link WifiManager#WIFI_STATE_DISABLING},
582 * {@link WifiManager#WIFI_STATE_ENABLED},
583 * {@link WifiManager#WIFI_STATE_ENABLING},
584 * {@link WifiManager#WIFI_STATE_UNKNOWN}
585 */
586 public int getWifiEnabledState() {
587 enforceAccessPermission();
588 return mWifiState;
589 }
590
591 /**
592 * see {@link android.net.wifi.WifiManager#disconnect()}
593 * @return {@code true} if the operation succeeds
594 */
595 public boolean disconnect() {
596 enforceChangePermission();
597 synchronized (mWifiStateTracker) {
598 return WifiNative.disconnectCommand();
599 }
600 }
601
602 /**
603 * see {@link android.net.wifi.WifiManager#reconnect()}
604 * @return {@code true} if the operation succeeds
605 */
606 public boolean reconnect() {
607 enforceChangePermission();
608 synchronized (mWifiStateTracker) {
609 return WifiNative.reconnectCommand();
610 }
611 }
612
613 /**
614 * see {@link android.net.wifi.WifiManager#reassociate()}
615 * @return {@code true} if the operation succeeds
616 */
617 public boolean reassociate() {
618 enforceChangePermission();
619 synchronized (mWifiStateTracker) {
620 return WifiNative.reassociateCommand();
621 }
622 }
623
624 /**
625 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
626 * @return the list of configured networks
627 */
628 public List<WifiConfiguration> getConfiguredNetworks() {
629 enforceAccessPermission();
630 String listStr;
631 /*
632 * We don't cache the list, because we want to allow
633 * for the possibility that the configuration file
634 * has been modified through some external means,
635 * such as the wpa_cli command line program.
636 */
637 synchronized (mWifiStateTracker) {
638 listStr = WifiNative.listNetworksCommand();
639 }
640 List<WifiConfiguration> networks =
641 new ArrayList<WifiConfiguration>();
642 if (listStr == null)
643 return networks;
644
645 String[] lines = listStr.split("\n");
646 // Skip the first line, which is a header
647 for (int i = 1; i < lines.length; i++) {
648 String[] result = lines[i].split("\t");
649 // network-id | ssid | bssid | flags
650 WifiConfiguration config = new WifiConfiguration();
651 try {
652 config.networkId = Integer.parseInt(result[0]);
653 } catch(NumberFormatException e) {
654 continue;
655 }
656 if (result.length > 3) {
657 if (result[3].indexOf("[CURRENT]") != -1)
658 config.status = WifiConfiguration.Status.CURRENT;
659 else if (result[3].indexOf("[DISABLED]") != -1)
660 config.status = WifiConfiguration.Status.DISABLED;
661 else
662 config.status = WifiConfiguration.Status.ENABLED;
663 } else
664 config.status = WifiConfiguration.Status.ENABLED;
665 synchronized (mWifiStateTracker) {
666 readNetworkVariables(config);
667 }
668 networks.add(config);
669 }
670
671 return networks;
672 }
673
674 /**
675 * Read the variables from the supplicant daemon that are needed to
676 * fill in the WifiConfiguration object.
677 * <p/>
678 * The caller must hold the synchronization monitor.
679 * @param config the {@link WifiConfiguration} object to be filled in.
680 */
681 private static void readNetworkVariables(WifiConfiguration config) {
682
683 int netId = config.networkId;
684 if (netId < 0)
685 return;
686
687 /*
688 * TODO: maybe should have a native method that takes an array of
689 * variable names and returns an array of values. But we'd still
690 * be doing a round trip to the supplicant daemon for each variable.
691 */
692 String value;
693
694 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
695 if (!TextUtils.isEmpty(value)) {
696 config.SSID = value;
697 } else {
698 config.SSID = null;
699 }
700
701 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
702 if (!TextUtils.isEmpty(value)) {
703 config.BSSID = value;
704 } else {
705 config.BSSID = null;
706 }
707
708 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
709 config.priority = -1;
710 if (!TextUtils.isEmpty(value)) {
711 try {
712 config.priority = Integer.parseInt(value);
713 } catch (NumberFormatException ignore) {
714 }
715 }
716
717 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
718 config.hiddenSSID = false;
719 if (!TextUtils.isEmpty(value)) {
720 try {
721 config.hiddenSSID = Integer.parseInt(value) != 0;
722 } catch (NumberFormatException ignore) {
723 }
724 }
725
726 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
727 config.wepTxKeyIndex = -1;
728 if (!TextUtils.isEmpty(value)) {
729 try {
730 config.wepTxKeyIndex = Integer.parseInt(value);
731 } catch (NumberFormatException ignore) {
732 }
733 }
734
735 /*
736 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
737 * just a "*" if the key is set, or the null string otherwise.
738 */
739 for (int i = 0; i < 4; i++) {
740 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
741 if (!TextUtils.isEmpty(value)) {
742 config.wepKeys[i] = value;
743 } else {
744 config.wepKeys[i] = null;
745 }
746 }
747
748 /*
749 * Get the private shared key. Note that the actual keys are not passed back,
750 * just a "*" if the key is set, or the null string otherwise.
751 */
752 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
753 if (!TextUtils.isEmpty(value)) {
754 config.preSharedKey = value;
755 } else {
756 config.preSharedKey = null;
757 }
758
759 value = WifiNative.getNetworkVariableCommand(config.networkId,
760 WifiConfiguration.Protocol.varName);
761 if (!TextUtils.isEmpty(value)) {
762 String vals[] = value.split(" ");
763 for (String val : vals) {
764 int index =
765 lookupString(val, WifiConfiguration.Protocol.strings);
766 if (0 <= index) {
767 config.allowedProtocols.set(index);
768 }
769 }
770 }
771
772 value = WifiNative.getNetworkVariableCommand(config.networkId,
773 WifiConfiguration.KeyMgmt.varName);
774 if (!TextUtils.isEmpty(value)) {
775 String vals[] = value.split(" ");
776 for (String val : vals) {
777 int index =
778 lookupString(val, WifiConfiguration.KeyMgmt.strings);
779 if (0 <= index) {
780 config.allowedKeyManagement.set(index);
781 }
782 }
783 }
784
785 value = WifiNative.getNetworkVariableCommand(config.networkId,
786 WifiConfiguration.AuthAlgorithm.varName);
787 if (!TextUtils.isEmpty(value)) {
788 String vals[] = value.split(" ");
789 for (String val : vals) {
790 int index =
791 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
792 if (0 <= index) {
793 config.allowedAuthAlgorithms.set(index);
794 }
795 }
796 }
797
798 value = WifiNative.getNetworkVariableCommand(config.networkId,
799 WifiConfiguration.PairwiseCipher.varName);
800 if (!TextUtils.isEmpty(value)) {
801 String vals[] = value.split(" ");
802 for (String val : vals) {
803 int index =
804 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
805 if (0 <= index) {
806 config.allowedPairwiseCiphers.set(index);
807 }
808 }
809 }
810
811 value = WifiNative.getNetworkVariableCommand(config.networkId,
812 WifiConfiguration.GroupCipher.varName);
813 if (!TextUtils.isEmpty(value)) {
814 String vals[] = value.split(" ");
815 for (String val : vals) {
816 int index =
817 lookupString(val, WifiConfiguration.GroupCipher.strings);
818 if (0 <= index) {
819 config.allowedGroupCiphers.set(index);
820 }
821 }
822 }
823 }
824
825 /**
826 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
827 * @return the supplicant-assigned identifier for the new or updated
828 * network if the operation succeeds, or {@code -1} if it fails
829 */
830 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
831 enforceChangePermission();
832 /*
833 * If the supplied networkId is -1, we create a new empty
834 * network configuration. Otherwise, the networkId should
835 * refer to an existing configuration.
836 */
837 int netId = config.networkId;
838 boolean newNetwork = netId == -1;
839 boolean doReconfig;
840 int currentPriority;
841 // networkId of -1 means we want to create a new network
842 if (newNetwork) {
843 netId = WifiNative.addNetworkCommand();
844 if (netId < 0) {
845 if (DBG) {
846 Log.d(TAG, "Failed to add a network!");
847 }
848 return -1;
849 }
850 doReconfig = true;
851 } else {
852 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
853 currentPriority = -1;
854 if (!TextUtils.isEmpty(priorityVal)) {
855 try {
856 currentPriority = Integer.parseInt(priorityVal);
857 } catch (NumberFormatException ignore) {
858 }
859 }
860 doReconfig = currentPriority != config.priority;
861 }
862 mNeedReconfig = mNeedReconfig || doReconfig;
863
864 /*
865 * If we have hidden networks, we may have to change the scan mode
866 */
867 if (config.hiddenSSID) {
868 // Mark the network as present unless it is disabled
869 addOrUpdateHiddenNetwork(
870 netId, config.status != WifiConfiguration.Status.DISABLED);
871 }
872
873 setVariables: {
874 /*
875 * Note that if a networkId for a non-existent network
876 * was supplied, then the first setNetworkVariableCommand()
877 * will fail, so we don't bother to make a separate check
878 * for the validity of the ID up front.
879 */
880
881 if (config.SSID != null &&
882 !WifiNative.setNetworkVariableCommand(
883 netId,
884 WifiConfiguration.ssidVarName,
885 config.SSID)) {
886 if (DBG) {
887 Log.d(TAG, "failed to set SSID: "+config.SSID);
888 }
889 break setVariables;
890 }
891
892 if (config.BSSID != null &&
893 !WifiNative.setNetworkVariableCommand(
894 netId,
895 WifiConfiguration.bssidVarName,
896 config.BSSID)) {
897 if (DBG) {
898 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
899 }
900 break setVariables;
901 }
902
903 String allowedKeyManagementString =
904 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
905 if (config.allowedKeyManagement.cardinality() != 0 &&
906 !WifiNative.setNetworkVariableCommand(
907 netId,
908 WifiConfiguration.KeyMgmt.varName,
909 allowedKeyManagementString)) {
910 if (DBG) {
911 Log.d(TAG, "failed to set key_mgmt: "+
912 allowedKeyManagementString);
913 }
914 break setVariables;
915 }
916
917 String allowedProtocolsString =
918 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
919 if (config.allowedProtocols.cardinality() != 0 &&
920 !WifiNative.setNetworkVariableCommand(
921 netId,
922 WifiConfiguration.Protocol.varName,
923 allowedProtocolsString)) {
924 if (DBG) {
925 Log.d(TAG, "failed to set proto: "+
926 allowedProtocolsString);
927 }
928 break setVariables;
929 }
930
931 String allowedAuthAlgorithmsString =
932 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
933 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
934 !WifiNative.setNetworkVariableCommand(
935 netId,
936 WifiConfiguration.AuthAlgorithm.varName,
937 allowedAuthAlgorithmsString)) {
938 if (DBG) {
939 Log.d(TAG, "failed to set auth_alg: "+
940 allowedAuthAlgorithmsString);
941 }
942 break setVariables;
943 }
944
945 String allowedPairwiseCiphersString =
946 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
947 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
948 !WifiNative.setNetworkVariableCommand(
949 netId,
950 WifiConfiguration.PairwiseCipher.varName,
951 allowedPairwiseCiphersString)) {
952 if (DBG) {
953 Log.d(TAG, "failed to set pairwise: "+
954 allowedPairwiseCiphersString);
955 }
956 break setVariables;
957 }
958
959 String allowedGroupCiphersString =
960 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
961 if (config.allowedGroupCiphers.cardinality() != 0 &&
962 !WifiNative.setNetworkVariableCommand(
963 netId,
964 WifiConfiguration.GroupCipher.varName,
965 allowedGroupCiphersString)) {
966 if (DBG) {
967 Log.d(TAG, "failed to set group: "+
968 allowedGroupCiphersString);
969 }
970 break setVariables;
971 }
972
973 // Prevent client screw-up by passing in a WifiConfiguration we gave it
974 // by preventing "*" as a key.
975 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
976 !WifiNative.setNetworkVariableCommand(
977 netId,
978 WifiConfiguration.pskVarName,
979 config.preSharedKey)) {
980 if (DBG) {
981 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
982 }
983 break setVariables;
984 }
985
986 boolean hasSetKey = false;
987 if (config.wepKeys != null) {
988 for (int i = 0; i < config.wepKeys.length; i++) {
989 // Prevent client screw-up by passing in a WifiConfiguration we gave it
990 // by preventing "*" as a key.
991 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
992 if (!WifiNative.setNetworkVariableCommand(
993 netId,
994 WifiConfiguration.wepKeyVarNames[i],
995 config.wepKeys[i])) {
996 if (DBG) {
997 Log.d(TAG,
998 "failed to set wep_key"+i+": " +
999 config.wepKeys[i]);
1000 }
1001 break setVariables;
1002 }
1003 hasSetKey = true;
1004 }
1005 }
1006 }
1007
1008 if (hasSetKey) {
1009 if (!WifiNative.setNetworkVariableCommand(
1010 netId,
1011 WifiConfiguration.wepTxKeyIdxVarName,
1012 Integer.toString(config.wepTxKeyIndex))) {
1013 if (DBG) {
1014 Log.d(TAG,
1015 "failed to set wep_tx_keyidx: "+
1016 config.wepTxKeyIndex);
1017 }
1018 break setVariables;
1019 }
1020 }
1021
1022 if (!WifiNative.setNetworkVariableCommand(
1023 netId,
1024 WifiConfiguration.priorityVarName,
1025 Integer.toString(config.priority))) {
1026 if (DBG) {
1027 Log.d(TAG, config.SSID + ": failed to set priority: "
1028 +config.priority);
1029 }
1030 break setVariables;
1031 }
1032
1033 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
1034 netId,
1035 WifiConfiguration.hiddenSSIDVarName,
1036 Integer.toString(config.hiddenSSID ? 1 : 0))) {
1037 if (DBG) {
1038 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
1039 config.hiddenSSID);
1040 }
1041 break setVariables;
1042 }
1043
1044 return netId;
1045 }
1046
1047 /*
1048 * For an update, if one of the setNetworkVariable operations fails,
1049 * we might want to roll back all the changes already made. But the
1050 * chances are that if anything is going to go wrong, it'll happen
1051 * the first time we try to set one of the variables.
1052 */
1053 if (newNetwork) {
1054 removeNetwork(netId);
1055 if (DBG) {
1056 Log.d(TAG,
1057 "Failed to set a network variable, removed network: "
1058 + netId);
1059 }
1060 }
1061 return -1;
1062 }
1063
1064 private static String makeString(BitSet set, String[] strings) {
1065 StringBuffer buf = new StringBuffer();
1066 int nextSetBit = -1;
1067
1068 /* Make sure all set bits are in [0, strings.length) to avoid
1069 * going out of bounds on strings. (Shouldn't happen, but...) */
1070 set = set.get(0, strings.length);
1071
1072 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1073 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1074 }
1075
1076 // remove trailing space
1077 if (set.cardinality() > 0) {
1078 buf.setLength(buf.length() - 1);
1079 }
1080
1081 return buf.toString();
1082 }
1083
1084 private static int lookupString(String string, String[] strings) {
1085 int size = strings.length;
1086
1087 string = string.replace('-', '_');
1088
1089 for (int i = 0; i < size; i++)
1090 if (string.equals(strings[i]))
1091 return i;
1092
1093 if (DBG) {
1094 // if we ever get here, we should probably add the
1095 // value to WifiConfiguration to reflect that it's
1096 // supported by the WPA supplicant
1097 Log.w(TAG, "Failed to look-up a string: " + string);
1098 }
1099
1100 return -1;
1101 }
1102
1103 /**
1104 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1105 * @param netId the integer that identifies the network configuration
1106 * to the supplicant
1107 * @return {@code true} if the operation succeeded
1108 */
1109 public boolean removeNetwork(int netId) {
1110 enforceChangePermission();
1111
1112 /*
1113 * If we have hidden networks, we may have to change the scan mode
1114 */
1115 removeNetworkIfHidden(netId);
1116
1117 return mWifiStateTracker.removeNetwork(netId);
1118 }
1119
1120 /**
1121 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1122 * @param netId the integer that identifies the network configuration
1123 * to the supplicant
1124 * @param disableOthers if true, disable all other networks.
1125 * @return {@code true} if the operation succeeded
1126 */
1127 public boolean enableNetwork(int netId, boolean disableOthers) {
1128 enforceChangePermission();
1129
1130 /*
1131 * If we have hidden networks, we may have to change the scan mode
1132 */
1133 synchronized(this) {
1134 if (disableOthers) {
1135 markAllHiddenNetworksButOneAsNotPresent(netId);
1136 }
1137 updateNetworkIfHidden(netId, true);
1138 }
1139
1140 synchronized (mWifiStateTracker) {
1141 return WifiNative.enableNetworkCommand(netId, disableOthers);
1142 }
1143 }
1144
1145 /**
1146 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1147 * @param netId the integer that identifies the network configuration
1148 * to the supplicant
1149 * @return {@code true} if the operation succeeded
1150 */
1151 public boolean disableNetwork(int netId) {
1152 enforceChangePermission();
1153
1154 /*
1155 * If we have hidden networks, we may have to change the scan mode
1156 */
1157 updateNetworkIfHidden(netId, false);
1158
1159 synchronized (mWifiStateTracker) {
1160 return WifiNative.disableNetworkCommand(netId);
1161 }
1162 }
1163
1164 /**
1165 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1166 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1167 */
1168 public WifiInfo getConnectionInfo() {
1169 enforceAccessPermission();
1170 /*
1171 * Make sure we have the latest information, by sending
1172 * a status request to the supplicant.
1173 */
1174 return mWifiStateTracker.requestConnectionInfo();
1175 }
1176
1177 /**
1178 * Return the results of the most recent access point scan, in the form of
1179 * a list of {@link ScanResult} objects.
1180 * @return the list of results
1181 */
1182 public List<ScanResult> getScanResults() {
1183 enforceAccessPermission();
1184 String reply;
1185 synchronized (mWifiStateTracker) {
1186 reply = WifiNative.scanResultsCommand();
1187 }
1188 if (reply == null) {
1189 return null;
1190 }
1191
1192 List<ScanResult> scanList = new ArrayList<ScanResult>();
1193
1194 int lineCount = 0;
1195
1196 int replyLen = reply.length();
1197 // Parse the result string, keeping in mind that the last line does
1198 // not end with a newline.
1199 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1200 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1201 ++lineCount;
1202 /*
1203 * Skip the first line, which is a header
1204 */
1205 if (lineCount == 1) {
1206 lineBeg = lineEnd + 1;
1207 continue;
1208 }
1209 int lineLen = lineEnd - lineBeg;
1210 if (0 < lineLen && lineLen <= SCAN_RESULT_BUFFER_SIZE) {
1211 int scanResultLevel = 0;
1212 /*
1213 * At most one thread should have access to the buffer at a time!
1214 */
1215 synchronized(mScanResultBuffer) {
1216 boolean parsingScanResultLevel = false;
1217 for (int i = lineBeg; i < lineEnd; ++i) {
1218 char ch = reply.charAt(i);
1219 /*
1220 * Assume that the signal level starts with a '-'
1221 */
1222 if (ch == '-') {
1223 /*
1224 * Skip whatever instances of '-' we may have
1225 * after we parse the signal level
1226 */
1227 parsingScanResultLevel = (scanResultLevel == 0);
1228 } else if (parsingScanResultLevel) {
1229 int digit = Character.digit(ch, 10);
1230 if (0 <= digit) {
1231 scanResultLevel =
1232 10 * scanResultLevel + digit;
1233 /*
1234 * Replace the signal level number in
1235 * the string with 0's for caching
1236 */
1237 ch = '0';
1238 } else {
1239 /*
1240 * Reset the flag if we meet a non-digit
1241 * character
1242 */
1243 parsingScanResultLevel = false;
1244 }
1245 }
1246 mScanResultBuffer[i - lineBeg] = ch;
1247 }
1248 if (scanResultLevel != 0) {
1249 ScanResult scanResult = parseScanResult(
1250 new String(mScanResultBuffer, 0, lineLen));
1251 if (scanResult != null) {
1252 scanResult.level = -scanResultLevel;
1253 scanList.add(scanResult);
1254 }
1255 } else if (DBG) {
1256 Log.w(TAG,
1257 "ScanResult.level=0: misformatted scan result?");
1258 }
1259 }
1260 } else if (0 < lineLen) {
1261 if (DBG) {
1262 Log.w(TAG, "Scan result line is too long: " +
1263 (lineEnd - lineBeg) + ", skipping the line!");
1264 }
1265 }
1266 lineBeg = lineEnd + 1;
1267 }
1268 }
1269 mWifiStateTracker.setScanResultsList(scanList);
1270 return scanList;
1271 }
1272
1273 /**
1274 * Parse the scan result line passed to us by wpa_supplicant (helper).
1275 * @param line the line to parse
1276 * @return the {@link ScanResult} object
1277 */
1278 private ScanResult parseScanResult(String line) {
1279 ScanResult scanResult = null;
1280 if (line != null) {
1281 /*
1282 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1283 * must synchronized here!
1284 */
1285 synchronized (mScanResultCache) {
1286 scanResult = mScanResultCache.get(line);
1287 if (scanResult == null) {
1288 String[] result = scanResultPattern.split(line);
1289 if (3 <= result.length && result.length <= 5) {
1290 // bssid | frequency | level | flags | ssid
1291 int frequency;
1292 int level;
1293 try {
1294 frequency = Integer.parseInt(result[1]);
1295 level = Integer.parseInt(result[2]);
1296 } catch (NumberFormatException e) {
1297 frequency = 0;
1298 level = 0;
1299 }
1300
1301 /*
1302 * The formatting of the results returned by
1303 * wpa_supplicant is intended to make the fields
1304 * line up nicely when printed,
1305 * not to make them easy to parse. So we have to
1306 * apply some heuristics to figure out which field
1307 * is the SSID and which field is the flags.
1308 */
1309 String ssid;
1310 String flags;
1311 if (result.length == 4) {
1312 if (result[3].charAt(0) == '[') {
1313 flags = result[3];
1314 ssid = "";
1315 } else {
1316 flags = "";
1317 ssid = result[3];
1318 }
1319 } else if (result.length == 5) {
1320 flags = result[3];
1321 ssid = result[4];
1322 } else {
1323 // Here, we must have 3 fields: no flags and ssid
1324 // set
1325 flags = "";
1326 ssid = "";
1327 }
1328
1329 // Do not add scan results that have no SSID set
1330 if (0 < ssid.trim().length()) {
1331 scanResult =
1332 new ScanResult(
1333 ssid, result[0], flags, level, frequency);
1334 mScanResultCache.put(line, scanResult);
1335 }
1336 } else {
1337 Log.w(TAG, "Misformatted scan result text with " +
1338 result.length + " fields: " + line);
1339 }
1340 }
1341 }
1342 }
1343
1344 return scanResult;
1345 }
1346
1347 /**
1348 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1349 * and construct a {@code WifiConfiguration} that describes the encryption,
1350 * key management, and authenticaion capabilities of the access point.
1351 * @param flags the string returned by wpa_supplicant
1352 * @return the {@link WifiConfiguration} object, filled in
1353 */
1354 WifiConfiguration parseScanFlags(String flags) {
1355 WifiConfiguration config = new WifiConfiguration();
1356
1357 if (flags.length() == 0) {
1358 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1359 }
1360 // ... to be implemented
1361 return config;
1362 }
1363
1364 /**
1365 * Tell the supplicant to persist the current list of configured networks.
1366 * @return {@code true} if the operation succeeded
1367 */
1368 public boolean saveConfiguration() {
1369 boolean result;
1370 enforceChangePermission();
1371 synchronized (mWifiStateTracker) {
1372 result = WifiNative.saveConfigCommand();
1373 if (result && mNeedReconfig) {
1374 mNeedReconfig = false;
1375 result = WifiNative.reloadConfigCommand();
1376
1377 if (result) {
1378 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1379 mContext.sendBroadcast(intent);
1380 }
1381 }
1382 }
1383 return result;
1384 }
1385
1386 /**
1387 * Set the number of radio frequency channels that are allowed to be used
1388 * in the current regulatory domain. This method should be used only
1389 * if the correct number of channels cannot be determined automatically
1390 * for some reason. If the operation is successful, the new value is
1391 * persisted as a Secure setting.
1392 * @param numChannels the number of allowed channels. Must be greater than 0
1393 * and less than or equal to 16.
1394 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1395 * {@code numChannels} is outside the valid range.
1396 */
1397 public boolean setNumAllowedChannels(int numChannels) {
1398 enforceChangePermission();
1399 /*
1400 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1401 * but if Wi-Fi isn't currently enabled, that's not possible, and
1402 * we want to persist the setting anyway,so that it will take
1403 * effect when Wi-Fi does become enabled.
1404 */
1405 boolean found = false;
1406 for (int validChan : sValidRegulatoryChannelCounts) {
1407 if (validChan == numChannels) {
1408 found = true;
1409 break;
1410 }
1411 }
1412 if (!found) {
1413 return false;
1414 }
1415
1416 Settings.Secure.putInt(mContext.getContentResolver(),
1417 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1418 numChannels);
1419 mWifiStateTracker.setNumAllowedChannels(numChannels);
1420 return true;
1421 }
1422
1423 /**
1424 * Return the number of frequency channels that are allowed
1425 * to be used in the current regulatory domain.
1426 * @return the number of allowed channels, or {@code -1} if an error occurs
1427 */
1428 public int getNumAllowedChannels() {
1429 int numChannels;
1430
1431 enforceAccessPermission();
1432 synchronized (mWifiStateTracker) {
1433 /*
1434 * If we can't get the value from the driver (e.g., because
1435 * Wi-Fi is not currently enabled), get the value from
1436 * Settings.
1437 */
1438 numChannels = WifiNative.getNumAllowedChannelsCommand();
1439 if (numChannels < 0) {
1440 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1441 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1442 -1);
1443 }
1444 }
1445 return numChannels;
1446 }
1447
1448 /**
1449 * Return the list of valid values for the number of allowed radio channels
1450 * for various regulatory domains.
1451 * @return the list of channel counts
1452 */
1453 public int[] getValidChannelCounts() {
1454 enforceAccessPermission();
1455 return sValidRegulatoryChannelCounts;
1456 }
1457
1458 /**
1459 * Return the DHCP-assigned addresses from the last successful DHCP request,
1460 * if any.
1461 * @return the DHCP information
1462 */
1463 public DhcpInfo getDhcpInfo() {
1464 enforceAccessPermission();
1465 return mWifiStateTracker.getDhcpInfo();
1466 }
1467
1468 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1469 @Override
1470 public void onReceive(Context context, Intent intent) {
1471 String action = intent.getAction();
1472
1473 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1474 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1475 int stayAwakeConditions =
1476 Settings.System.getInt(mContext.getContentResolver(),
1477 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1478 if (action.equals(Intent.ACTION_SCREEN_ON)) {
1479 mAlarmManager.cancel(mIdleIntent);
1480 mDeviceIdle = false;
1481 mScreenOff = false;
1482 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1483 mScreenOff = true;
1484 /*
1485 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1486 * AND the "stay on while plugged in" setting doesn't match the
1487 * current power conditions (i.e, not plugged in, plugged in to USB,
1488 * or plugged in to AC).
1489 */
1490 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
1491 long triggerTime = System.currentTimeMillis() + idleMillis;
1492 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1493 }
1494 /* we can return now -- there's nothing to do until we get the idle intent back */
1495 return;
1496 } else if (action.equals(ACTION_DEVICE_IDLE)) {
1497 mDeviceIdle = true;
1498 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1499 /*
1500 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1501 * AND we are transitioning from a state in which the device was supposed
1502 * to stay awake to a state in which it is not supposed to stay awake.
1503 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1504 * the already-set timer.
1505 */
1506 int pluggedType = intent.getIntExtra("plugged", 0);
1507 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1508 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1509 long triggerTime = System.currentTimeMillis() + idleMillis;
1510 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1511 mPluggedType = pluggedType;
1512 return;
1513 }
1514 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001515 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1516 boolean isBluetoothPlaying =
1517 intent.getIntExtra(
1518 BluetoothA2dp.SINK_STATE,
1519 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1520 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 } else {
1522 return;
1523 }
1524
1525 updateWifiState();
1526 }
1527
1528 /**
1529 * Determines whether the Wi-Fi chipset should stay awake or be put to
1530 * sleep. Looks at the setting for the sleep policy and the current
1531 * conditions.
1532 *
1533 * @see #shouldDeviceStayAwake(int, int)
1534 */
1535 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1536 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1537 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1538
1539 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1540 // Never sleep
1541 return true;
1542 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1543 (pluggedType != 0)) {
1544 // Never sleep while plugged, and we're plugged
1545 return true;
1546 } else {
1547 // Default
1548 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1549 }
1550 }
1551
1552 /**
1553 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1554 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1555 * of {@code 0} isn't really a plugged type, but rather an indication that the
1556 * device isn't plugged in at all, there is no bit value corresponding to a
1557 * {@code pluggedType} value of {@code 0}. That is why we shift by
1558 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1559 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1560 * keep the device (and hence Wi-Fi) awake.
1561 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1562 * being made
1563 * @return {@code true} if {@code pluggedType} indicates that the device is
1564 * supposed to stay awake, {@code false} otherwise.
1565 */
1566 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1567 return (stayAwakeConditions & pluggedType) != 0;
1568 }
1569 };
1570
1571 private void sendEnableMessage(boolean enable, boolean persist) {
1572 Message msg = Message.obtain(mWifiHandler,
1573 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
1574 (persist ? 1 : 0), 0);
1575 msg.sendToTarget();
1576 }
1577
1578 private void sendStartMessage(boolean scanOnlyMode) {
1579 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1580 }
1581
1582 private void updateWifiState() {
1583 boolean wifiEnabled = getPersistedWifiEnabled();
1584 boolean airplaneMode = isAirplaneModeOn();
1585 boolean lockHeld = mLocks.hasLocks();
1586 int strongestLockMode;
1587 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1588 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1589 if (mDeviceIdle && lockHeld) {
1590 strongestLockMode = mLocks.getStrongestLockMode();
1591 } else {
1592 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1593 }
1594
1595 synchronized (mWifiHandler) {
1596 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1597 return;
1598 }
1599 if (wifiShouldBeEnabled) {
1600 if (wifiShouldBeStarted) {
1601 sWakeLock.acquire();
1602 sendEnableMessage(true, false);
1603 sWakeLock.acquire();
1604 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1605 } else {
1606 int wakeLockTimeout =
1607 Settings.Secure.getInt(
1608 mContext.getContentResolver(),
1609 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1610 DEFAULT_WAKELOCK_TIMEOUT);
1611 /*
1612 * The following wakelock is held in order to ensure
1613 * that the connectivity manager has time to fail over
1614 * to the mobile data network. The connectivity manager
1615 * releases it once mobile data connectivity has been
1616 * established. If connectivity cannot be established,
1617 * the wakelock is released after wakeLockTimeout
1618 * milliseconds have elapsed.
1619 */
1620 sDriverStopWakeLock.acquire();
1621 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1622 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1623 }
1624 } else {
1625 sWakeLock.acquire();
1626 sendEnableMessage(false, false);
1627 }
1628 }
1629 }
1630
1631 private void registerForBroadcasts() {
1632 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1634 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1635 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1636 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001637 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 mContext.registerReceiver(mReceiver, intentFilter);
1639 }
1640
1641 private boolean isAirplaneSensitive() {
1642 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1643 Settings.System.AIRPLANE_MODE_RADIOS);
1644 return airplaneModeRadios == null
1645 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1646 }
1647
1648 /**
1649 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1650 * currently on.
1651 * @return {@code true} if airplane mode is on.
1652 */
1653 private boolean isAirplaneModeOn() {
1654 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1655 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1656 }
1657
1658 /**
1659 * Handler that allows posting to the WifiThread.
1660 */
1661 private class WifiHandler extends Handler {
1662 public WifiHandler(Looper looper) {
1663 super(looper);
1664 }
1665
1666 @Override
1667 public void handleMessage(Message msg) {
1668 switch (msg.what) {
1669
1670 case MESSAGE_ENABLE_WIFI:
1671 setWifiEnabledBlocking(true, msg.arg1 == 1);
1672 sWakeLock.release();
1673 break;
1674
1675 case MESSAGE_START_WIFI:
1676 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1677 mWifiStateTracker.restart();
1678 sWakeLock.release();
1679 break;
1680
1681 case MESSAGE_DISABLE_WIFI:
1682 // a non-zero msg.arg1 value means the "enabled" setting
1683 // should be persisted
1684 setWifiEnabledBlocking(false, msg.arg1 == 1);
1685 sWakeLock.release();
1686 break;
1687
1688 case MESSAGE_STOP_WIFI:
1689 mWifiStateTracker.disconnectAndStop();
1690 // don't release wakelock
1691 break;
1692
1693 case MESSAGE_RELEASE_WAKELOCK:
1694 synchronized (sDriverStopWakeLock) {
1695 if (sDriverStopWakeLock.isHeld()) {
1696 sDriverStopWakeLock.release();
1697 }
1698 }
1699 break;
1700 }
1701 }
1702 }
1703
1704 @Override
1705 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1706 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1707 != PackageManager.PERMISSION_GRANTED) {
1708 pw.println("Permission Denial: can't dump WifiService from from pid="
1709 + Binder.getCallingPid()
1710 + ", uid=" + Binder.getCallingUid());
1711 return;
1712 }
1713 pw.println("Wi-Fi is " + stateName(mWifiState));
1714 pw.println("Stay-awake conditions: " +
1715 Settings.System.getInt(mContext.getContentResolver(),
1716 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1717 pw.println();
1718
1719 pw.println("Internal state:");
1720 pw.println(mWifiStateTracker);
1721 pw.println();
1722 pw.println("Latest scan results:");
1723 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1724 if (scanResults != null && scanResults.size() != 0) {
1725 pw.println(" BSSID Frequency RSSI Flags SSID");
1726 for (ScanResult r : scanResults) {
1727 pw.printf(" %17s %9d %5d %-16s %s%n",
1728 r.BSSID,
1729 r.frequency,
1730 r.level,
1731 r.capabilities,
1732 r.SSID == null ? "" : r.SSID);
1733 }
1734 }
1735 pw.println();
1736 pw.println("Locks held:");
1737 mLocks.dump(pw);
1738 }
1739
1740 private static String stateName(int wifiState) {
1741 switch (wifiState) {
1742 case WIFI_STATE_DISABLING:
1743 return "disabling";
1744 case WIFI_STATE_DISABLED:
1745 return "disabled";
1746 case WIFI_STATE_ENABLING:
1747 return "enabling";
1748 case WIFI_STATE_ENABLED:
1749 return "enabled";
1750 case WIFI_STATE_UNKNOWN:
1751 return "unknown state";
1752 default:
1753 return "[invalid state]";
1754 }
1755 }
1756
1757 private class WifiLock implements IBinder.DeathRecipient {
1758 String mTag;
1759 int mLockMode;
1760 IBinder mBinder;
1761
1762 WifiLock(int lockMode, String tag, IBinder binder) {
1763 super();
1764 mTag = tag;
1765 mLockMode = lockMode;
1766 mBinder = binder;
1767 try {
1768 mBinder.linkToDeath(this, 0);
1769 } catch (RemoteException e) {
1770 binderDied();
1771 }
1772 }
1773
1774 public void binderDied() {
1775 synchronized (mLocks) {
1776 releaseWifiLockLocked(mBinder);
1777 }
1778 }
1779
1780 public String toString() {
1781 return "WifiLock{" + mTag + " type=" + mLockMode + " binder=" + mBinder + "}";
1782 }
1783 }
1784
1785 private class LockList {
1786 private List<WifiLock> mList;
1787
1788 private LockList() {
1789 mList = new ArrayList<WifiLock>();
1790 }
1791
1792 private synchronized boolean hasLocks() {
1793 return !mList.isEmpty();
1794 }
1795
1796 private synchronized int getStrongestLockMode() {
1797 if (mList.isEmpty()) {
1798 return WifiManager.WIFI_MODE_FULL;
1799 }
1800 for (WifiLock l : mList) {
1801 if (l.mLockMode == WifiManager.WIFI_MODE_FULL) {
1802 return WifiManager.WIFI_MODE_FULL;
1803 }
1804 }
1805 return WifiManager.WIFI_MODE_SCAN_ONLY;
1806 }
1807
1808 private void addLock(WifiLock lock) {
1809 if (findLockByBinder(lock.mBinder) < 0) {
1810 mList.add(lock);
1811 }
1812 }
1813
1814 private WifiLock removeLock(IBinder binder) {
1815 int index = findLockByBinder(binder);
1816 if (index >= 0) {
1817 return mList.remove(index);
1818 } else {
1819 return null;
1820 }
1821 }
1822
1823 private int findLockByBinder(IBinder binder) {
1824 int size = mList.size();
1825 for (int i = size - 1; i >= 0; i--)
1826 if (mList.get(i).mBinder == binder)
1827 return i;
1828 return -1;
1829 }
1830
1831 private void dump(PrintWriter pw) {
1832 for (WifiLock l : mList) {
1833 pw.print(" ");
1834 pw.println(l);
1835 }
1836 }
1837 }
1838
1839 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1840 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1841 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1842 return false;
1843 }
1844 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1845 synchronized (mLocks) {
1846 return acquireWifiLockLocked(wifiLock);
1847 }
1848 }
1849
1850 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1851 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001852
1853 int uid = Binder.getCallingUid();
1854 long ident = Binder.clearCallingIdentity();
1855 try {
1856 switch(wifiLock.mLockMode) {
1857 case (WifiManager.WIFI_MODE_FULL): mBatteryStats.noteFullWifiLockAcquired(uid);
1858 case (WifiManager.WIFI_MODE_SCAN_ONLY): mBatteryStats.noteScanWifiLockAcquired(uid);
1859 }
1860 } catch (RemoteException e) {
1861 } finally {
1862 Binder.restoreCallingIdentity(ident);
1863 }
1864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 updateWifiState();
1866 return true;
1867 }
1868
1869 public boolean releaseWifiLock(IBinder lock) {
1870 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1871 synchronized (mLocks) {
1872 return releaseWifiLockLocked(lock);
1873 }
1874 }
1875
1876 private boolean releaseWifiLockLocked(IBinder lock) {
1877 boolean result;
The Android Open Source Project10592532009-03-18 17:39:46 -07001878
1879 WifiLock wifiLock = mLocks.removeLock(lock);
1880 result = (wifiLock != null);
1881
1882 int uid = Binder.getCallingUid();
1883 long ident = Binder.clearCallingIdentity();
1884 try {
1885 switch(wifiLock.mLockMode) {
1886 case (WifiManager.WIFI_MODE_FULL): mBatteryStats.noteFullWifiLockReleased(uid);
1887 case (WifiManager.WIFI_MODE_SCAN_ONLY): mBatteryStats.noteScanWifiLockReleased(uid);
1888 }
1889 } catch (RemoteException e) {
1890 } finally {
1891 Binder.restoreCallingIdentity(ident);
1892 }
1893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 updateWifiState();
1895 return result;
1896 }
1897}