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