blob: 987a24ec609734d26e289002f1c167f4992338f7 [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;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080028import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.BroadcastReceiver;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
35import android.net.wifi.IWifiManager;
36import android.net.wifi.WifiInfo;
37import android.net.wifi.WifiManager;
38import android.net.wifi.WifiNative;
39import android.net.wifi.WifiStateTracker;
40import android.net.wifi.ScanResult;
41import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070042import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.NetworkStateTracker;
44import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040045import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Binder;
47import android.os.Handler;
48import android.os.HandlerThread;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070053import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070055import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
57import android.util.Log;
58import android.text.TextUtils;
59
60import java.util.ArrayList;
61import java.util.BitSet;
62import java.util.HashMap;
63import java.util.LinkedHashMap;
64import java.util.List;
65import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080066import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.regex.Pattern;
68import java.io.FileDescriptor;
69import java.io.PrintWriter;
70
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.internal.app.IBatteryStats;
Amith Yamasani47873e52009-07-02 12:05:32 -070072import android.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070073import com.android.server.am.BatteryStatsService;
74
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075/**
76 * WifiService handles remote WiFi operation requests by implementing
77 * the IWifiManager interface. It also creates a WifiMonitor to listen
78 * for Wifi-related events.
79 *
80 * @hide
81 */
82public class WifiService extends IWifiManager.Stub {
83 private static final String TAG = "WifiService";
84 private static final boolean DBG = false;
85 private static final Pattern scanResultPattern = Pattern.compile("\t+");
86 private final WifiStateTracker mWifiStateTracker;
87
88 private Context mContext;
89 private int mWifiState;
90
91 private AlarmManager mAlarmManager;
92 private PendingIntent mIdleIntent;
93 private static final int IDLE_REQUEST = 0;
94 private boolean mScreenOff;
95 private boolean mDeviceIdle;
96 private int mPluggedType;
97
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070098 // true if the user enabled Wifi while in airplane mode
99 private boolean mAirplaneModeOverwridden;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700102 // some wifi lock statistics
103 private int mFullLocksAcquired;
104 private int mFullLocksReleased;
105 private int mScanLocksAcquired;
106 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700107
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700108 private final List<Multicaster> mMulticasters =
109 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700110 private int mMulticastEnabled;
111 private int mMulticastDisabled;
112
The Android Open Source Project10592532009-03-18 17:39:46 -0700113 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 /**
116 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
117 * Settings.Gservices value is not present. This timeout value is chosen as
118 * the approximate point at which the battery drain caused by Wi-Fi
119 * being enabled but not active exceeds the battery drain caused by
120 * re-establishing a connection to the mobile data network.
121 */
122 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
123
124 private static final String WAKELOCK_TAG = "WifiService";
125
126 /**
127 * The maximum amount of time to hold the wake lock after a disconnect
128 * caused by stopping the driver. Establishing an EDGE connection has been
129 * observed to take about 5 seconds under normal circumstances. This
130 * provides a bit of extra margin.
131 * <p>
132 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
133 * This is the default value if a Settings.Secure value is not present.
134 */
135 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
136
137 // Wake lock used by driver-stop operation
138 private static PowerManager.WakeLock sDriverStopWakeLock;
139 // Wake lock used by other operations
140 private static PowerManager.WakeLock sWakeLock;
141
142 private static final int MESSAGE_ENABLE_WIFI = 0;
143 private static final int MESSAGE_DISABLE_WIFI = 1;
144 private static final int MESSAGE_STOP_WIFI = 2;
145 private static final int MESSAGE_START_WIFI = 3;
146 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -0700147 private static final int MESSAGE_UPDATE_STATE = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 private final WifiHandler mWifiHandler;
150
151 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 * Cache of scan results objects (size is somewhat arbitrary)
153 */
154 private static final int SCAN_RESULT_CACHE_SIZE = 80;
155 private final LinkedHashMap<String, ScanResult> mScanResultCache;
156
157 /*
158 * Character buffer used to parse scan results (optimization)
159 */
160 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private boolean mNeedReconfig;
162
Dianne Hackborn617f8772009-03-31 15:04:46 -0700163 /*
164 * Last UID that asked to enable WIFI.
165 */
166 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 /**
169 * Number of allowed radio frequency channels in various regulatory domains.
170 * This list is sufficient for 802.11b/g networks (2.4GHz range).
171 */
172 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
173
174 private static final String ACTION_DEVICE_IDLE =
175 "com.android.server.WifiManager.action.DEVICE_IDLE";
176
177 WifiService(Context context, WifiStateTracker tracker) {
178 mContext = context;
179 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400180 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 mScanResultCache = new LinkedHashMap<String, ScanResult>(
184 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
185 /*
186 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
187 * elements
188 */
189 public boolean removeEldestEntry(Map.Entry eldest) {
190 return SCAN_RESULT_CACHE_SIZE < this.size();
191 }
192 };
193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 HandlerThread wifiThread = new HandlerThread("WifiService");
195 wifiThread.start();
196 mWifiHandler = new WifiHandler(wifiThread.getLooper());
197
198 mWifiState = WIFI_STATE_DISABLED;
199 boolean wifiEnabled = getPersistedWifiEnabled();
200
201 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
202 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
203 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
204
205 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
206 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
207 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
208 mWifiStateTracker.setReleaseWakeLockCallback(
209 new Runnable() {
210 public void run() {
211 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
212 synchronized (sDriverStopWakeLock) {
213 if (sDriverStopWakeLock.isHeld()) {
214 sDriverStopWakeLock.release();
215 }
216 }
217 }
218 }
219 );
220
221 Log.i(TAG, "WifiService starting up with Wi-Fi " +
222 (wifiEnabled ? "enabled" : "disabled"));
223
224 mContext.registerReceiver(
225 new BroadcastReceiver() {
226 @Override
227 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700228 // clear our flag indicating the user has overwridden airplane mode
229 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 updateWifiState();
231 }
232 },
233 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
234
Dianne Hackborn617f8772009-03-31 15:04:46 -0700235 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 }
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 private boolean getPersistedWifiEnabled() {
239 final ContentResolver cr = mContext.getContentResolver();
240 try {
241 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
242 } catch (Settings.SettingNotFoundException e) {
243 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
244 return false;
245 }
246 }
247
248 private void persistWifiEnabled(boolean enabled) {
249 final ContentResolver cr = mContext.getContentResolver();
250 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
251 }
252
253 NetworkStateTracker getNetworkStateTracker() {
254 return mWifiStateTracker;
255 }
256
257 /**
258 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
259 * @return {@code true} if the operation succeeds
260 */
261 public boolean pingSupplicant() {
262 enforceChangePermission();
263 synchronized (mWifiStateTracker) {
264 return WifiNative.pingCommand();
265 }
266 }
267
268 /**
269 * see {@link android.net.wifi.WifiManager#startScan()}
270 * @return {@code true} if the operation succeeds
271 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400272 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 enforceChangePermission();
274 synchronized (mWifiStateTracker) {
275 switch (mWifiStateTracker.getSupplicantState()) {
276 case DISCONNECTED:
277 case INACTIVE:
278 case SCANNING:
279 case DORMANT:
280 break;
281 default:
282 WifiNative.setScanResultHandlingCommand(
283 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
284 break;
285 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400286 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 }
289
290 /**
291 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
292 * @param enable {@code true} to enable, {@code false} to disable.
293 * @return {@code true} if the enable/disable operation was
294 * started or is already in the queue.
295 */
296 public boolean setWifiEnabled(boolean enable) {
297 enforceChangePermission();
298 if (mWifiHandler == null) return false;
299
300 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700301 // caller may not have WAKE_LOCK permission - it's not required here
302 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700304 Binder.restoreCallingIdentity(ident);
305
Dianne Hackborn617f8772009-03-31 15:04:46 -0700306 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700307 // set a flag if the user is enabling Wifi while in airplane mode
308 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700309 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311
312 return true;
313 }
314
315 /**
316 * Enables/disables Wi-Fi synchronously.
317 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
318 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700319 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * @return {@code true} if the operation succeeds (or if the existing state
321 * is the same as the requested state)
322 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700323 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
325
326 if (mWifiState == eventualWifiState) {
327 return true;
328 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700329 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 return false;
331 }
332
Dianne Hackborn617f8772009-03-31 15:04:46 -0700333 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 if (enable) {
336 if (!WifiNative.loadDriver()) {
337 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700338 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 return false;
340 }
341 if (!WifiNative.startSupplicant()) {
342 WifiNative.unloadDriver();
343 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700344 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 return false;
346 }
347 registerForBroadcasts();
348 mWifiStateTracker.startEventLoop();
349 } else {
350
351 mContext.unregisterReceiver(mReceiver);
352 // Remove notification (it will no-op if it isn't visible)
353 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
354
355 boolean failedToStopSupplicantOrUnloadDriver = false;
356 if (!WifiNative.stopSupplicant()) {
357 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700358 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 failedToStopSupplicantOrUnloadDriver = true;
360 }
361
362 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400363 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 if (!WifiNative.unloadDriver()) {
366 Log.e(TAG, "Failed to unload Wi-Fi driver.");
367 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700368 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 failedToStopSupplicantOrUnloadDriver = true;
370 }
371 }
372 if (failedToStopSupplicantOrUnloadDriver) {
373 return false;
374 }
375 }
376
377 // Success!
378
379 if (persist) {
380 persistWifiEnabled(enable);
381 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700382 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 return true;
385 }
386
Dianne Hackborn617f8772009-03-31 15:04:46 -0700387 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 final int previousWifiState = mWifiState;
389
The Android Open Source Project10592532009-03-18 17:39:46 -0700390 long ident = Binder.clearCallingIdentity();
391 try {
392 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700393 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700394 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700395 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700396 }
397 } catch (RemoteException e) {
398 } finally {
399 Binder.restoreCallingIdentity(ident);
400 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 // Update state
403 mWifiState = wifiState;
404
405 // Broadcast
406 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
407 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
408 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
409 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
410 mContext.sendStickyBroadcast(intent);
411 }
412
413 private void enforceAccessPermission() {
414 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
415 "WifiService");
416 }
417
418 private void enforceChangePermission() {
419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
420 "WifiService");
421
422 }
423
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700424 private void enforceMulticastChangePermission() {
425 mContext.enforceCallingOrSelfPermission(
426 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
427 "WifiService");
428 }
429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 /**
431 * see {@link WifiManager#getWifiState()}
432 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
433 * {@link WifiManager#WIFI_STATE_DISABLING},
434 * {@link WifiManager#WIFI_STATE_ENABLED},
435 * {@link WifiManager#WIFI_STATE_ENABLING},
436 * {@link WifiManager#WIFI_STATE_UNKNOWN}
437 */
438 public int getWifiEnabledState() {
439 enforceAccessPermission();
440 return mWifiState;
441 }
442
443 /**
444 * see {@link android.net.wifi.WifiManager#disconnect()}
445 * @return {@code true} if the operation succeeds
446 */
447 public boolean disconnect() {
448 enforceChangePermission();
449 synchronized (mWifiStateTracker) {
450 return WifiNative.disconnectCommand();
451 }
452 }
453
454 /**
455 * see {@link android.net.wifi.WifiManager#reconnect()}
456 * @return {@code true} if the operation succeeds
457 */
458 public boolean reconnect() {
459 enforceChangePermission();
460 synchronized (mWifiStateTracker) {
461 return WifiNative.reconnectCommand();
462 }
463 }
464
465 /**
466 * see {@link android.net.wifi.WifiManager#reassociate()}
467 * @return {@code true} if the operation succeeds
468 */
469 public boolean reassociate() {
470 enforceChangePermission();
471 synchronized (mWifiStateTracker) {
472 return WifiNative.reassociateCommand();
473 }
474 }
475
476 /**
477 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
478 * @return the list of configured networks
479 */
480 public List<WifiConfiguration> getConfiguredNetworks() {
481 enforceAccessPermission();
482 String listStr;
483 /*
484 * We don't cache the list, because we want to allow
485 * for the possibility that the configuration file
486 * has been modified through some external means,
487 * such as the wpa_cli command line program.
488 */
489 synchronized (mWifiStateTracker) {
490 listStr = WifiNative.listNetworksCommand();
491 }
492 List<WifiConfiguration> networks =
493 new ArrayList<WifiConfiguration>();
494 if (listStr == null)
495 return networks;
496
497 String[] lines = listStr.split("\n");
498 // Skip the first line, which is a header
499 for (int i = 1; i < lines.length; i++) {
500 String[] result = lines[i].split("\t");
501 // network-id | ssid | bssid | flags
502 WifiConfiguration config = new WifiConfiguration();
503 try {
504 config.networkId = Integer.parseInt(result[0]);
505 } catch(NumberFormatException e) {
506 continue;
507 }
508 if (result.length > 3) {
509 if (result[3].indexOf("[CURRENT]") != -1)
510 config.status = WifiConfiguration.Status.CURRENT;
511 else if (result[3].indexOf("[DISABLED]") != -1)
512 config.status = WifiConfiguration.Status.DISABLED;
513 else
514 config.status = WifiConfiguration.Status.ENABLED;
515 } else
516 config.status = WifiConfiguration.Status.ENABLED;
517 synchronized (mWifiStateTracker) {
518 readNetworkVariables(config);
519 }
520 networks.add(config);
521 }
522
523 return networks;
524 }
525
526 /**
527 * Read the variables from the supplicant daemon that are needed to
528 * fill in the WifiConfiguration object.
529 * <p/>
530 * The caller must hold the synchronization monitor.
531 * @param config the {@link WifiConfiguration} object to be filled in.
532 */
533 private static void readNetworkVariables(WifiConfiguration config) {
534
535 int netId = config.networkId;
536 if (netId < 0)
537 return;
538
539 /*
540 * TODO: maybe should have a native method that takes an array of
541 * variable names and returns an array of values. But we'd still
542 * be doing a round trip to the supplicant daemon for each variable.
543 */
544 String value;
545
546 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
547 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800548 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 } else {
550 config.SSID = null;
551 }
552
553 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
554 if (!TextUtils.isEmpty(value)) {
555 config.BSSID = value;
556 } else {
557 config.BSSID = null;
558 }
559
560 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
561 config.priority = -1;
562 if (!TextUtils.isEmpty(value)) {
563 try {
564 config.priority = Integer.parseInt(value);
565 } catch (NumberFormatException ignore) {
566 }
567 }
568
569 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
570 config.hiddenSSID = false;
571 if (!TextUtils.isEmpty(value)) {
572 try {
573 config.hiddenSSID = Integer.parseInt(value) != 0;
574 } catch (NumberFormatException ignore) {
575 }
576 }
577
578 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
579 config.wepTxKeyIndex = -1;
580 if (!TextUtils.isEmpty(value)) {
581 try {
582 config.wepTxKeyIndex = Integer.parseInt(value);
583 } catch (NumberFormatException ignore) {
584 }
585 }
586
587 /*
588 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
589 * just a "*" if the key is set, or the null string otherwise.
590 */
591 for (int i = 0; i < 4; i++) {
592 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
593 if (!TextUtils.isEmpty(value)) {
594 config.wepKeys[i] = value;
595 } else {
596 config.wepKeys[i] = null;
597 }
598 }
599
600 /*
601 * Get the private shared key. Note that the actual keys are not passed back,
602 * just a "*" if the key is set, or the null string otherwise.
603 */
604 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
605 if (!TextUtils.isEmpty(value)) {
606 config.preSharedKey = value;
607 } else {
608 config.preSharedKey = null;
609 }
610
611 value = WifiNative.getNetworkVariableCommand(config.networkId,
612 WifiConfiguration.Protocol.varName);
613 if (!TextUtils.isEmpty(value)) {
614 String vals[] = value.split(" ");
615 for (String val : vals) {
616 int index =
617 lookupString(val, WifiConfiguration.Protocol.strings);
618 if (0 <= index) {
619 config.allowedProtocols.set(index);
620 }
621 }
622 }
623
624 value = WifiNative.getNetworkVariableCommand(config.networkId,
625 WifiConfiguration.KeyMgmt.varName);
626 if (!TextUtils.isEmpty(value)) {
627 String vals[] = value.split(" ");
628 for (String val : vals) {
629 int index =
630 lookupString(val, WifiConfiguration.KeyMgmt.strings);
631 if (0 <= index) {
632 config.allowedKeyManagement.set(index);
633 }
634 }
635 }
636
637 value = WifiNative.getNetworkVariableCommand(config.networkId,
638 WifiConfiguration.AuthAlgorithm.varName);
639 if (!TextUtils.isEmpty(value)) {
640 String vals[] = value.split(" ");
641 for (String val : vals) {
642 int index =
643 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
644 if (0 <= index) {
645 config.allowedAuthAlgorithms.set(index);
646 }
647 }
648 }
649
650 value = WifiNative.getNetworkVariableCommand(config.networkId,
651 WifiConfiguration.PairwiseCipher.varName);
652 if (!TextUtils.isEmpty(value)) {
653 String vals[] = value.split(" ");
654 for (String val : vals) {
655 int index =
656 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
657 if (0 <= index) {
658 config.allowedPairwiseCiphers.set(index);
659 }
660 }
661 }
662
663 value = WifiNative.getNetworkVariableCommand(config.networkId,
664 WifiConfiguration.GroupCipher.varName);
665 if (!TextUtils.isEmpty(value)) {
666 String vals[] = value.split(" ");
667 for (String val : vals) {
668 int index =
669 lookupString(val, WifiConfiguration.GroupCipher.strings);
670 if (0 <= index) {
671 config.allowedGroupCiphers.set(index);
672 }
673 }
674 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800675
676 for (WifiConfiguration.EnterpriseField field :
677 config.enterpriseFields) {
678 value = WifiNative.getNetworkVariableCommand(netId,
679 field.varName());
680 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800681 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800682 field.setValue(value);
683 }
684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800687 private static String removeDoubleQuotes(String string) {
688 if (string.length() <= 2) return "";
689 return string.substring(1, string.length() - 1);
690 }
691
692 private static String convertToQuotedString(String string) {
693 return "\"" + string + "\"";
694 }
695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 /**
697 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
698 * @return the supplicant-assigned identifier for the new or updated
699 * network if the operation succeeds, or {@code -1} if it fails
700 */
701 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
702 enforceChangePermission();
703 /*
704 * If the supplied networkId is -1, we create a new empty
705 * network configuration. Otherwise, the networkId should
706 * refer to an existing configuration.
707 */
708 int netId = config.networkId;
709 boolean newNetwork = netId == -1;
710 boolean doReconfig;
711 int currentPriority;
712 // networkId of -1 means we want to create a new network
713 if (newNetwork) {
714 netId = WifiNative.addNetworkCommand();
715 if (netId < 0) {
716 if (DBG) {
717 Log.d(TAG, "Failed to add a network!");
718 }
719 return -1;
720 }
721 doReconfig = true;
722 } else {
723 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
724 currentPriority = -1;
725 if (!TextUtils.isEmpty(priorityVal)) {
726 try {
727 currentPriority = Integer.parseInt(priorityVal);
728 } catch (NumberFormatException ignore) {
729 }
730 }
731 doReconfig = currentPriority != config.priority;
732 }
733 mNeedReconfig = mNeedReconfig || doReconfig;
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 setVariables: {
736 /*
737 * Note that if a networkId for a non-existent network
738 * was supplied, then the first setNetworkVariableCommand()
739 * will fail, so we don't bother to make a separate check
740 * for the validity of the ID up front.
741 */
742
743 if (config.SSID != null &&
744 !WifiNative.setNetworkVariableCommand(
745 netId,
746 WifiConfiguration.ssidVarName,
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800747 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 if (DBG) {
749 Log.d(TAG, "failed to set SSID: "+config.SSID);
750 }
751 break setVariables;
752 }
753
754 if (config.BSSID != null &&
755 !WifiNative.setNetworkVariableCommand(
756 netId,
757 WifiConfiguration.bssidVarName,
758 config.BSSID)) {
759 if (DBG) {
760 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
761 }
762 break setVariables;
763 }
764
765 String allowedKeyManagementString =
766 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
767 if (config.allowedKeyManagement.cardinality() != 0 &&
768 !WifiNative.setNetworkVariableCommand(
769 netId,
770 WifiConfiguration.KeyMgmt.varName,
771 allowedKeyManagementString)) {
772 if (DBG) {
773 Log.d(TAG, "failed to set key_mgmt: "+
774 allowedKeyManagementString);
775 }
776 break setVariables;
777 }
778
779 String allowedProtocolsString =
780 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
781 if (config.allowedProtocols.cardinality() != 0 &&
782 !WifiNative.setNetworkVariableCommand(
783 netId,
784 WifiConfiguration.Protocol.varName,
785 allowedProtocolsString)) {
786 if (DBG) {
787 Log.d(TAG, "failed to set proto: "+
788 allowedProtocolsString);
789 }
790 break setVariables;
791 }
792
793 String allowedAuthAlgorithmsString =
794 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
795 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
796 !WifiNative.setNetworkVariableCommand(
797 netId,
798 WifiConfiguration.AuthAlgorithm.varName,
799 allowedAuthAlgorithmsString)) {
800 if (DBG) {
801 Log.d(TAG, "failed to set auth_alg: "+
802 allowedAuthAlgorithmsString);
803 }
804 break setVariables;
805 }
806
807 String allowedPairwiseCiphersString =
808 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
809 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
810 !WifiNative.setNetworkVariableCommand(
811 netId,
812 WifiConfiguration.PairwiseCipher.varName,
813 allowedPairwiseCiphersString)) {
814 if (DBG) {
815 Log.d(TAG, "failed to set pairwise: "+
816 allowedPairwiseCiphersString);
817 }
818 break setVariables;
819 }
820
821 String allowedGroupCiphersString =
822 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
823 if (config.allowedGroupCiphers.cardinality() != 0 &&
824 !WifiNative.setNetworkVariableCommand(
825 netId,
826 WifiConfiguration.GroupCipher.varName,
827 allowedGroupCiphersString)) {
828 if (DBG) {
829 Log.d(TAG, "failed to set group: "+
830 allowedGroupCiphersString);
831 }
832 break setVariables;
833 }
834
835 // Prevent client screw-up by passing in a WifiConfiguration we gave it
836 // by preventing "*" as a key.
837 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
838 !WifiNative.setNetworkVariableCommand(
839 netId,
840 WifiConfiguration.pskVarName,
841 config.preSharedKey)) {
842 if (DBG) {
843 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
844 }
845 break setVariables;
846 }
847
848 boolean hasSetKey = false;
849 if (config.wepKeys != null) {
850 for (int i = 0; i < config.wepKeys.length; i++) {
851 // Prevent client screw-up by passing in a WifiConfiguration we gave it
852 // by preventing "*" as a key.
853 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
854 if (!WifiNative.setNetworkVariableCommand(
855 netId,
856 WifiConfiguration.wepKeyVarNames[i],
857 config.wepKeys[i])) {
858 if (DBG) {
859 Log.d(TAG,
860 "failed to set wep_key"+i+": " +
861 config.wepKeys[i]);
862 }
863 break setVariables;
864 }
865 hasSetKey = true;
866 }
867 }
868 }
869
870 if (hasSetKey) {
871 if (!WifiNative.setNetworkVariableCommand(
872 netId,
873 WifiConfiguration.wepTxKeyIdxVarName,
874 Integer.toString(config.wepTxKeyIndex))) {
875 if (DBG) {
876 Log.d(TAG,
877 "failed to set wep_tx_keyidx: "+
878 config.wepTxKeyIndex);
879 }
880 break setVariables;
881 }
882 }
883
884 if (!WifiNative.setNetworkVariableCommand(
885 netId,
886 WifiConfiguration.priorityVarName,
887 Integer.toString(config.priority))) {
888 if (DBG) {
889 Log.d(TAG, config.SSID + ": failed to set priority: "
890 +config.priority);
891 }
892 break setVariables;
893 }
894
895 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
896 netId,
897 WifiConfiguration.hiddenSSIDVarName,
898 Integer.toString(config.hiddenSSID ? 1 : 0))) {
899 if (DBG) {
900 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
901 config.hiddenSSID);
902 }
903 break setVariables;
904 }
905
Chung-yih Wang43374762009-09-16 14:28:42 +0800906 for (WifiConfiguration.EnterpriseField field
907 : config.enterpriseFields) {
908 String varName = field.varName();
909 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800910 if (value != null) {
911 if (field != config.eap) {
912 value = convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800913 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800914 if (!WifiNative.setNetworkVariableCommand(
915 netId,
916 varName,
917 value)) {
918 if (DBG) {
919 Log.d(TAG, config.SSID + ": failed to set " + varName +
920 ": " + value);
921 }
922 break setVariables;
923 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800924 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 return netId;
927 }
928
929 /*
930 * For an update, if one of the setNetworkVariable operations fails,
931 * we might want to roll back all the changes already made. But the
932 * chances are that if anything is going to go wrong, it'll happen
933 * the first time we try to set one of the variables.
934 */
935 if (newNetwork) {
936 removeNetwork(netId);
937 if (DBG) {
938 Log.d(TAG,
939 "Failed to set a network variable, removed network: "
940 + netId);
941 }
942 }
943 return -1;
944 }
945
946 private static String makeString(BitSet set, String[] strings) {
947 StringBuffer buf = new StringBuffer();
948 int nextSetBit = -1;
949
950 /* Make sure all set bits are in [0, strings.length) to avoid
951 * going out of bounds on strings. (Shouldn't happen, but...) */
952 set = set.get(0, strings.length);
953
954 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
955 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
956 }
957
958 // remove trailing space
959 if (set.cardinality() > 0) {
960 buf.setLength(buf.length() - 1);
961 }
962
963 return buf.toString();
964 }
965
966 private static int lookupString(String string, String[] strings) {
967 int size = strings.length;
968
969 string = string.replace('-', '_');
970
971 for (int i = 0; i < size; i++)
972 if (string.equals(strings[i]))
973 return i;
974
975 if (DBG) {
976 // if we ever get here, we should probably add the
977 // value to WifiConfiguration to reflect that it's
978 // supported by the WPA supplicant
979 Log.w(TAG, "Failed to look-up a string: " + string);
980 }
981
982 return -1;
983 }
984
985 /**
986 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
987 * @param netId the integer that identifies the network configuration
988 * to the supplicant
989 * @return {@code true} if the operation succeeded
990 */
991 public boolean removeNetwork(int netId) {
992 enforceChangePermission();
993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 return mWifiStateTracker.removeNetwork(netId);
995 }
996
997 /**
998 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
999 * @param netId the integer that identifies the network configuration
1000 * to the supplicant
1001 * @param disableOthers if true, disable all other networks.
1002 * @return {@code true} if the operation succeeded
1003 */
1004 public boolean enableNetwork(int netId, boolean disableOthers) {
1005 enforceChangePermission();
1006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001008 String ifname = mWifiStateTracker.getInterfaceName();
1009 NetworkUtils.enableInterface(ifname);
1010 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1011 if (!result) {
1012 NetworkUtils.disableInterface(ifname);
1013 }
1014 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016 }
1017
1018 /**
1019 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1020 * @param netId the integer that identifies the network configuration
1021 * to the supplicant
1022 * @return {@code true} if the operation succeeded
1023 */
1024 public boolean disableNetwork(int netId) {
1025 enforceChangePermission();
1026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 synchronized (mWifiStateTracker) {
1028 return WifiNative.disableNetworkCommand(netId);
1029 }
1030 }
1031
1032 /**
1033 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1034 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1035 */
1036 public WifiInfo getConnectionInfo() {
1037 enforceAccessPermission();
1038 /*
1039 * Make sure we have the latest information, by sending
1040 * a status request to the supplicant.
1041 */
1042 return mWifiStateTracker.requestConnectionInfo();
1043 }
1044
1045 /**
1046 * Return the results of the most recent access point scan, in the form of
1047 * a list of {@link ScanResult} objects.
1048 * @return the list of results
1049 */
1050 public List<ScanResult> getScanResults() {
1051 enforceAccessPermission();
1052 String reply;
1053 synchronized (mWifiStateTracker) {
1054 reply = WifiNative.scanResultsCommand();
1055 }
1056 if (reply == null) {
1057 return null;
1058 }
1059
1060 List<ScanResult> scanList = new ArrayList<ScanResult>();
1061
1062 int lineCount = 0;
1063
1064 int replyLen = reply.length();
1065 // Parse the result string, keeping in mind that the last line does
1066 // not end with a newline.
1067 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1068 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1069 ++lineCount;
1070 /*
1071 * Skip the first line, which is a header
1072 */
1073 if (lineCount == 1) {
1074 lineBeg = lineEnd + 1;
1075 continue;
1076 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001077 if (lineEnd > lineBeg) {
1078 String line = reply.substring(lineBeg, lineEnd);
1079 ScanResult scanResult = parseScanResult(line);
1080 if (scanResult != null) {
1081 scanList.add(scanResult);
1082 } else if (DBG) {
1083 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086 lineBeg = lineEnd + 1;
1087 }
1088 }
1089 mWifiStateTracker.setScanResultsList(scanList);
1090 return scanList;
1091 }
1092
1093 /**
1094 * Parse the scan result line passed to us by wpa_supplicant (helper).
1095 * @param line the line to parse
1096 * @return the {@link ScanResult} object
1097 */
1098 private ScanResult parseScanResult(String line) {
1099 ScanResult scanResult = null;
1100 if (line != null) {
1101 /*
1102 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1103 * must synchronized here!
1104 */
1105 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001106 String[] result = scanResultPattern.split(line);
1107 if (3 <= result.length && result.length <= 5) {
1108 String bssid = result[0];
1109 // bssid | frequency | level | flags | ssid
1110 int frequency;
1111 int level;
1112 try {
1113 frequency = Integer.parseInt(result[1]);
1114 level = Integer.parseInt(result[2]);
1115 /* some implementations avoid negative values by adding 256
1116 * so we need to adjust for that here.
1117 */
1118 if (level > 0) level -= 256;
1119 } catch (NumberFormatException e) {
1120 frequency = 0;
1121 level = 0;
1122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
Mike Lockwood1a645052009-06-25 13:01:12 -04001124 /*
1125 * The formatting of the results returned by
1126 * wpa_supplicant is intended to make the fields
1127 * line up nicely when printed,
1128 * not to make them easy to parse. So we have to
1129 * apply some heuristics to figure out which field
1130 * is the SSID and which field is the flags.
1131 */
1132 String ssid;
1133 String flags;
1134 if (result.length == 4) {
1135 if (result[3].charAt(0) == '[') {
1136 flags = result[3];
1137 ssid = "";
1138 } else {
1139 flags = "";
1140 ssid = result[3];
1141 }
1142 } else if (result.length == 5) {
1143 flags = result[3];
1144 ssid = result[4];
1145 } else {
1146 // Here, we must have 3 fields: no flags and ssid
1147 // set
1148 flags = "";
1149 ssid = "";
1150 }
1151
Mike Lockwood00717e22009-08-17 10:09:36 -04001152 // bssid + ssid is the hash key
1153 String key = bssid + ssid;
1154 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001155 if (scanResult != null) {
1156 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001157 scanResult.SSID = ssid;
1158 scanResult.capabilities = flags;
1159 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001160 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 // Do not add scan results that have no SSID set
1162 if (0 < ssid.trim().length()) {
1163 scanResult =
1164 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001165 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001166 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001169 } else {
1170 Log.w(TAG, "Misformatted scan result text with " +
1171 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
1173 }
1174 }
1175
1176 return scanResult;
1177 }
1178
1179 /**
1180 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1181 * and construct a {@code WifiConfiguration} that describes the encryption,
1182 * key management, and authenticaion capabilities of the access point.
1183 * @param flags the string returned by wpa_supplicant
1184 * @return the {@link WifiConfiguration} object, filled in
1185 */
1186 WifiConfiguration parseScanFlags(String flags) {
1187 WifiConfiguration config = new WifiConfiguration();
1188
1189 if (flags.length() == 0) {
1190 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1191 }
1192 // ... to be implemented
1193 return config;
1194 }
1195
1196 /**
1197 * Tell the supplicant to persist the current list of configured networks.
1198 * @return {@code true} if the operation succeeded
1199 */
1200 public boolean saveConfiguration() {
1201 boolean result;
1202 enforceChangePermission();
1203 synchronized (mWifiStateTracker) {
1204 result = WifiNative.saveConfigCommand();
1205 if (result && mNeedReconfig) {
1206 mNeedReconfig = false;
1207 result = WifiNative.reloadConfigCommand();
1208
1209 if (result) {
1210 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1211 mContext.sendBroadcast(intent);
1212 }
1213 }
1214 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001215 // Inform the backup manager about a data change
1216 IBackupManager ibm = IBackupManager.Stub.asInterface(
1217 ServiceManager.getService(Context.BACKUP_SERVICE));
1218 if (ibm != null) {
1219 try {
1220 ibm.dataChanged("com.android.providers.settings");
1221 } catch (Exception e) {
1222 // Try again later
1223 }
1224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 return result;
1226 }
1227
1228 /**
1229 * Set the number of radio frequency channels that are allowed to be used
1230 * in the current regulatory domain. This method should be used only
1231 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001232 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * persisted as a Secure setting.
1234 * @param numChannels the number of allowed channels. Must be greater than 0
1235 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001236 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1238 * {@code numChannels} is outside the valid range.
1239 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001240 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1241 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1242 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 enforceChangePermission();
1244 /*
1245 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1246 * but if Wi-Fi isn't currently enabled, that's not possible, and
1247 * we want to persist the setting anyway,so that it will take
1248 * effect when Wi-Fi does become enabled.
1249 */
1250 boolean found = false;
1251 for (int validChan : sValidRegulatoryChannelCounts) {
1252 if (validChan == numChannels) {
1253 found = true;
1254 break;
1255 }
1256 }
1257 if (!found) {
1258 return false;
1259 }
1260
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001261 if (persist) {
1262 Settings.Secure.putInt(mContext.getContentResolver(),
1263 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1264 numChannels);
1265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 mWifiStateTracker.setNumAllowedChannels(numChannels);
1267 return true;
1268 }
1269
1270 /**
1271 * Return the number of frequency channels that are allowed
1272 * to be used in the current regulatory domain.
1273 * @return the number of allowed channels, or {@code -1} if an error occurs
1274 */
1275 public int getNumAllowedChannels() {
1276 int numChannels;
1277
1278 enforceAccessPermission();
1279 synchronized (mWifiStateTracker) {
1280 /*
1281 * If we can't get the value from the driver (e.g., because
1282 * Wi-Fi is not currently enabled), get the value from
1283 * Settings.
1284 */
1285 numChannels = WifiNative.getNumAllowedChannelsCommand();
1286 if (numChannels < 0) {
1287 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1288 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1289 -1);
1290 }
1291 }
1292 return numChannels;
1293 }
1294
1295 /**
1296 * Return the list of valid values for the number of allowed radio channels
1297 * for various regulatory domains.
1298 * @return the list of channel counts
1299 */
1300 public int[] getValidChannelCounts() {
1301 enforceAccessPermission();
1302 return sValidRegulatoryChannelCounts;
1303 }
1304
1305 /**
1306 * Return the DHCP-assigned addresses from the last successful DHCP request,
1307 * if any.
1308 * @return the DHCP information
1309 */
1310 public DhcpInfo getDhcpInfo() {
1311 enforceAccessPermission();
1312 return mWifiStateTracker.getDhcpInfo();
1313 }
1314
1315 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1316 @Override
1317 public void onReceive(Context context, Intent intent) {
1318 String action = intent.getAction();
1319
1320 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1321 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1322 int stayAwakeConditions =
1323 Settings.System.getInt(mContext.getContentResolver(),
1324 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1325 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001326 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 mAlarmManager.cancel(mIdleIntent);
1328 mDeviceIdle = false;
1329 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001330 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001332 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001334 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 /*
1336 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1337 * AND the "stay on while plugged in" setting doesn't match the
1338 * current power conditions (i.e, not plugged in, plugged in to USB,
1339 * or plugged in to AC).
1340 */
1341 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001342 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1343 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001344 // we used to go to sleep immediately, but this caused some race conditions
1345 // we don't have time to track down for this release. Delay instead, but not
1346 // as long as we would if connected (below)
1347 // TODO - fix the race conditions and switch back to the immediate turn-off
1348 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
1349 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
1350 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1351 // // do not keep Wifi awake when screen is off if Wifi is not associated
1352 // mDeviceIdle = true;
1353 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001354 } else {
1355 long triggerTime = System.currentTimeMillis() + idleMillis;
1356 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1357 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
1360 /* we can return now -- there's nothing to do until we get the idle intent back */
1361 return;
1362 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001363 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 mDeviceIdle = true;
1365 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1366 /*
1367 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1368 * AND we are transitioning from a state in which the device was supposed
1369 * to stay awake to a state in which it is not supposed to stay awake.
1370 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1371 * the already-set timer.
1372 */
1373 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001374 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1376 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1377 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001378 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1380 mPluggedType = pluggedType;
1381 return;
1382 }
1383 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001384 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001385 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1386 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1387 boolean isBluetoothPlaying = false;
1388 for (BluetoothDevice sink : sinks) {
1389 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1390 isBluetoothPlaying = true;
1391 }
1392 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001393 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 } else {
1396 return;
1397 }
1398
1399 updateWifiState();
1400 }
1401
1402 /**
1403 * Determines whether the Wi-Fi chipset should stay awake or be put to
1404 * sleep. Looks at the setting for the sleep policy and the current
1405 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001406 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 * @see #shouldDeviceStayAwake(int, int)
1408 */
1409 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1410 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1411 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1412
1413 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1414 // Never sleep
1415 return true;
1416 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1417 (pluggedType != 0)) {
1418 // Never sleep while plugged, and we're plugged
1419 return true;
1420 } else {
1421 // Default
1422 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1423 }
1424 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 /**
1427 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1428 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1429 * of {@code 0} isn't really a plugged type, but rather an indication that the
1430 * device isn't plugged in at all, there is no bit value corresponding to a
1431 * {@code pluggedType} value of {@code 0}. That is why we shift by
1432 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1433 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1434 * keep the device (and hence Wi-Fi) awake.
1435 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1436 * being made
1437 * @return {@code true} if {@code pluggedType} indicates that the device is
1438 * supposed to stay awake, {@code false} otherwise.
1439 */
1440 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1441 return (stayAwakeConditions & pluggedType) != 0;
1442 }
1443 };
1444
Dianne Hackborn617f8772009-03-31 15:04:46 -07001445 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 Message msg = Message.obtain(mWifiHandler,
1447 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001448 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 msg.sendToTarget();
1450 }
1451
1452 private void sendStartMessage(boolean scanOnlyMode) {
1453 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1454 }
1455
1456 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001457 // send a message so it's all serialized
1458 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1459 }
1460
1461 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001463 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 boolean lockHeld = mLocks.hasLocks();
1465 int strongestLockMode;
1466 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1467 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1468 if (mDeviceIdle && lockHeld) {
1469 strongestLockMode = mLocks.getStrongestLockMode();
1470 } else {
1471 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1472 }
1473
1474 synchronized (mWifiHandler) {
1475 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1476 return;
1477 }
1478 if (wifiShouldBeEnabled) {
1479 if (wifiShouldBeStarted) {
1480 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001481 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 sWakeLock.acquire();
1483 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1484 } else {
1485 int wakeLockTimeout =
1486 Settings.Secure.getInt(
1487 mContext.getContentResolver(),
1488 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1489 DEFAULT_WAKELOCK_TIMEOUT);
1490 /*
1491 * The following wakelock is held in order to ensure
1492 * that the connectivity manager has time to fail over
1493 * to the mobile data network. The connectivity manager
1494 * releases it once mobile data connectivity has been
1495 * established. If connectivity cannot be established,
1496 * the wakelock is released after wakeLockTimeout
1497 * milliseconds have elapsed.
1498 */
1499 sDriverStopWakeLock.acquire();
1500 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1501 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1502 }
1503 } else {
1504 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001505 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
1508 }
1509
1510 private void registerForBroadcasts() {
1511 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1513 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1514 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1515 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001516 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 mContext.registerReceiver(mReceiver, intentFilter);
1518 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 private boolean isAirplaneSensitive() {
1521 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1522 Settings.System.AIRPLANE_MODE_RADIOS);
1523 return airplaneModeRadios == null
1524 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1525 }
1526
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001527 private boolean isAirplaneToggleable() {
1528 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1529 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1530 return toggleableRadios != null
1531 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1532 }
1533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 /**
1535 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1536 * currently on.
1537 * @return {@code true} if airplane mode is on.
1538 */
1539 private boolean isAirplaneModeOn() {
1540 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1541 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1542 }
1543
1544 /**
1545 * Handler that allows posting to the WifiThread.
1546 */
1547 private class WifiHandler extends Handler {
1548 public WifiHandler(Looper looper) {
1549 super(looper);
1550 }
1551
1552 @Override
1553 public void handleMessage(Message msg) {
1554 switch (msg.what) {
1555
1556 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001557 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 sWakeLock.release();
1559 break;
1560
1561 case MESSAGE_START_WIFI:
1562 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1563 mWifiStateTracker.restart();
1564 sWakeLock.release();
1565 break;
1566
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001567 case MESSAGE_UPDATE_STATE:
1568 doUpdateWifiState();
1569 break;
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 case MESSAGE_DISABLE_WIFI:
1572 // a non-zero msg.arg1 value means the "enabled" setting
1573 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001574 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 sWakeLock.release();
1576 break;
1577
1578 case MESSAGE_STOP_WIFI:
1579 mWifiStateTracker.disconnectAndStop();
1580 // don't release wakelock
1581 break;
1582
1583 case MESSAGE_RELEASE_WAKELOCK:
1584 synchronized (sDriverStopWakeLock) {
1585 if (sDriverStopWakeLock.isHeld()) {
1586 sDriverStopWakeLock.release();
1587 }
1588 }
1589 break;
1590 }
1591 }
1592 }
1593
1594 @Override
1595 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1596 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1597 != PackageManager.PERMISSION_GRANTED) {
1598 pw.println("Permission Denial: can't dump WifiService from from pid="
1599 + Binder.getCallingPid()
1600 + ", uid=" + Binder.getCallingUid());
1601 return;
1602 }
1603 pw.println("Wi-Fi is " + stateName(mWifiState));
1604 pw.println("Stay-awake conditions: " +
1605 Settings.System.getInt(mContext.getContentResolver(),
1606 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1607 pw.println();
1608
1609 pw.println("Internal state:");
1610 pw.println(mWifiStateTracker);
1611 pw.println();
1612 pw.println("Latest scan results:");
1613 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1614 if (scanResults != null && scanResults.size() != 0) {
1615 pw.println(" BSSID Frequency RSSI Flags SSID");
1616 for (ScanResult r : scanResults) {
1617 pw.printf(" %17s %9d %5d %-16s %s%n",
1618 r.BSSID,
1619 r.frequency,
1620 r.level,
1621 r.capabilities,
1622 r.SSID == null ? "" : r.SSID);
1623 }
1624 }
1625 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001626 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1627 mScanLocksAcquired + " scan");
1628 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1629 mScanLocksReleased + " scan");
1630 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 pw.println("Locks held:");
1632 mLocks.dump(pw);
1633 }
1634
1635 private static String stateName(int wifiState) {
1636 switch (wifiState) {
1637 case WIFI_STATE_DISABLING:
1638 return "disabling";
1639 case WIFI_STATE_DISABLED:
1640 return "disabled";
1641 case WIFI_STATE_ENABLING:
1642 return "enabling";
1643 case WIFI_STATE_ENABLED:
1644 return "enabled";
1645 case WIFI_STATE_UNKNOWN:
1646 return "unknown state";
1647 default:
1648 return "[invalid state]";
1649 }
1650 }
1651
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001652 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001654 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656
1657 public void binderDied() {
1658 synchronized (mLocks) {
1659 releaseWifiLockLocked(mBinder);
1660 }
1661 }
1662
1663 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001664 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
1667
1668 private class LockList {
1669 private List<WifiLock> mList;
1670
1671 private LockList() {
1672 mList = new ArrayList<WifiLock>();
1673 }
1674
1675 private synchronized boolean hasLocks() {
1676 return !mList.isEmpty();
1677 }
1678
1679 private synchronized int getStrongestLockMode() {
1680 if (mList.isEmpty()) {
1681 return WifiManager.WIFI_MODE_FULL;
1682 }
1683 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001684 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 return WifiManager.WIFI_MODE_FULL;
1686 }
1687 }
1688 return WifiManager.WIFI_MODE_SCAN_ONLY;
1689 }
1690
1691 private void addLock(WifiLock lock) {
1692 if (findLockByBinder(lock.mBinder) < 0) {
1693 mList.add(lock);
1694 }
1695 }
1696
1697 private WifiLock removeLock(IBinder binder) {
1698 int index = findLockByBinder(binder);
1699 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001700 WifiLock ret = mList.remove(index);
1701 ret.unlinkDeathRecipient();
1702 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 } else {
1704 return null;
1705 }
1706 }
1707
1708 private int findLockByBinder(IBinder binder) {
1709 int size = mList.size();
1710 for (int i = size - 1; i >= 0; i--)
1711 if (mList.get(i).mBinder == binder)
1712 return i;
1713 return -1;
1714 }
1715
1716 private void dump(PrintWriter pw) {
1717 for (WifiLock l : mList) {
1718 pw.print(" ");
1719 pw.println(l);
1720 }
1721 }
1722 }
1723
1724 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1725 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1726 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1727 return false;
1728 }
1729 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1730 synchronized (mLocks) {
1731 return acquireWifiLockLocked(wifiLock);
1732 }
1733 }
1734
1735 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001736 Log.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001739
The Android Open Source Project10592532009-03-18 17:39:46 -07001740 int uid = Binder.getCallingUid();
1741 long ident = Binder.clearCallingIdentity();
1742 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001743 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001744 case WifiManager.WIFI_MODE_FULL:
1745 ++mFullLocksAcquired;
1746 mBatteryStats.noteFullWifiLockAcquired(uid);
1747 break;
1748 case WifiManager.WIFI_MODE_SCAN_ONLY:
1749 ++mScanLocksAcquired;
1750 mBatteryStats.noteScanWifiLockAcquired(uid);
1751 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001752 }
1753 } catch (RemoteException e) {
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 updateWifiState();
1759 return true;
1760 }
1761
1762 public boolean releaseWifiLock(IBinder lock) {
1763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1764 synchronized (mLocks) {
1765 return releaseWifiLockLocked(lock);
1766 }
1767 }
1768
1769 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001770 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001771
The Android Open Source Project10592532009-03-18 17:39:46 -07001772 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001773
1774 Log.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1775
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001776 hadLock = (wifiLock != null);
1777
1778 if (hadLock) {
1779 int uid = Binder.getCallingUid();
1780 long ident = Binder.clearCallingIdentity();
1781 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001782 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001783 case WifiManager.WIFI_MODE_FULL:
1784 ++mFullLocksReleased;
1785 mBatteryStats.noteFullWifiLockReleased(uid);
1786 break;
1787 case WifiManager.WIFI_MODE_SCAN_ONLY:
1788 ++mScanLocksReleased;
1789 mBatteryStats.noteScanWifiLockReleased(uid);
1790 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001791 }
1792 } catch (RemoteException e) {
1793 } finally {
1794 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001795 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001796 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001797 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001799 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001801
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001802 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001803 implements IBinder.DeathRecipient {
1804 String mTag;
1805 int mMode;
1806 IBinder mBinder;
1807
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001808 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001809 super();
1810 mTag = tag;
1811 mMode = mode;
1812 mBinder = binder;
1813 try {
1814 mBinder.linkToDeath(this, 0);
1815 } catch (RemoteException e) {
1816 binderDied();
1817 }
1818 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001819
1820 void unlinkDeathRecipient() {
1821 mBinder.unlinkToDeath(this, 0);
1822 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001823 }
1824
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001825 private class Multicaster extends DeathRecipient {
1826 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001827 super(Binder.getCallingUid(), tag, binder);
1828 }
1829
1830 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001831 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001832 synchronized (mMulticasters) {
1833 int i = mMulticasters.indexOf(this);
1834 if (i != -1) {
1835 removeMulticasterLocked(i, mMode);
1836 }
1837 }
1838 }
1839
1840 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001841 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001842 }
1843
1844 public int getUid() {
1845 return mMode;
1846 }
1847 }
1848
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001849 public void initializeMulticastFiltering() {
1850 enforceMulticastChangePermission();
1851
1852 synchronized (mMulticasters) {
1853 // if anybody had requested filters be off, leave off
1854 if (mMulticasters.size() != 0) {
1855 return;
1856 } else {
1857 WifiNative.startPacketFiltering();
1858 }
1859 }
1860 }
1861
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001862 public void acquireMulticastLock(IBinder binder, String tag) {
1863 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001864
1865 synchronized (mMulticasters) {
1866 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001867 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001868 // Note that we could call stopPacketFiltering only when
1869 // our new size == 1 (first call), but this function won't
1870 // be called often and by making the stopPacket call each
1871 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001872 synchronized (mWifiStateTracker) {
1873 WifiNative.stopPacketFiltering();
1874 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001875 }
1876
1877 int uid = Binder.getCallingUid();
1878 Long ident = Binder.clearCallingIdentity();
1879 try {
1880 mBatteryStats.noteWifiMulticastEnabled(uid);
1881 } catch (RemoteException e) {
1882 } finally {
1883 Binder.restoreCallingIdentity(ident);
1884 }
1885 }
1886
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001887 public void releaseMulticastLock() {
1888 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001889
1890 int uid = Binder.getCallingUid();
1891 synchronized (mMulticasters) {
1892 mMulticastDisabled++;
1893 int size = mMulticasters.size();
1894 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001895 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001896 if ((m != null) && (m.getUid() == uid)) {
1897 removeMulticasterLocked(i, uid);
1898 }
1899 }
1900 }
1901 }
1902
1903 private void removeMulticasterLocked(int i, int uid)
1904 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001905 Multicaster removed = mMulticasters.remove(i);
1906 if (removed != null) {
1907 removed.unlinkDeathRecipient();
1908 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001909 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001910 synchronized (mWifiStateTracker) {
1911 WifiNative.startPacketFiltering();
1912 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001913 }
1914
1915 Long ident = Binder.clearCallingIdentity();
1916 try {
1917 mBatteryStats.noteWifiMulticastDisabled(uid);
1918 } catch (RemoteException e) {
1919 } finally {
1920 Binder.restoreCallingIdentity(ident);
1921 }
1922 }
1923
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001924 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001925 enforceAccessPermission();
1926
1927 synchronized (mMulticasters) {
1928 return (mMulticasters.size() > 0);
1929 }
1930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931}