blob: 370ee68f7ed7d60ebe257c6f522ae51b8388a625 [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;
Mike Lockwood0900f362009-07-10 17:24:07 -040044import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
46import android.os.Handler;
47import android.os.HandlerThread;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070052import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070054import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.provider.Settings;
56import android.util.Log;
57import android.text.TextUtils;
58
59import java.util.ArrayList;
60import java.util.BitSet;
61import java.util.HashMap;
62import java.util.LinkedHashMap;
63import java.util.List;
64import java.util.Map;
65import java.util.regex.Pattern;
66import java.io.FileDescriptor;
67import java.io.PrintWriter;
68
The Android Open Source Project10592532009-03-18 17:39:46 -070069import com.android.internal.app.IBatteryStats;
Amith Yamasani47873e52009-07-02 12:05:32 -070070import android.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.server.am.BatteryStatsService;
72
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073/**
74 * WifiService handles remote WiFi operation requests by implementing
75 * the IWifiManager interface. It also creates a WifiMonitor to listen
76 * for Wifi-related events.
77 *
78 * @hide
79 */
80public class WifiService extends IWifiManager.Stub {
81 private static final String TAG = "WifiService";
82 private static final boolean DBG = false;
83 private static final Pattern scanResultPattern = Pattern.compile("\t+");
84 private final WifiStateTracker mWifiStateTracker;
85
86 private Context mContext;
87 private int mWifiState;
88
89 private AlarmManager mAlarmManager;
90 private PendingIntent mIdleIntent;
91 private static final int IDLE_REQUEST = 0;
92 private boolean mScreenOff;
93 private boolean mDeviceIdle;
94 private int mPluggedType;
95
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070096 // true if the user enabled Wifi while in airplane mode
97 private boolean mAirplaneModeOverwridden;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700100 // some wifi lock statistics
101 private int mFullLocksAcquired;
102 private int mFullLocksReleased;
103 private int mScanLocksAcquired;
104 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700105
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700106 private final List<Multicaster> mMulticasters =
107 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700108 private int mMulticastEnabled;
109 private int mMulticastDisabled;
110
The Android Open Source Project10592532009-03-18 17:39:46 -0700111 private final IBatteryStats mBatteryStats;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 /**
114 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
115 * Settings.Gservices value is not present. This timeout value is chosen as
116 * the approximate point at which the battery drain caused by Wi-Fi
117 * being enabled but not active exceeds the battery drain caused by
118 * re-establishing a connection to the mobile data network.
119 */
120 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
121
122 private static final String WAKELOCK_TAG = "WifiService";
123
124 /**
125 * The maximum amount of time to hold the wake lock after a disconnect
126 * caused by stopping the driver. Establishing an EDGE connection has been
127 * observed to take about 5 seconds under normal circumstances. This
128 * provides a bit of extra margin.
129 * <p>
130 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
131 * This is the default value if a Settings.Secure value is not present.
132 */
133 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
134
135 // Wake lock used by driver-stop operation
136 private static PowerManager.WakeLock sDriverStopWakeLock;
137 // Wake lock used by other operations
138 private static PowerManager.WakeLock sWakeLock;
139
140 private static final int MESSAGE_ENABLE_WIFI = 0;
141 private static final int MESSAGE_DISABLE_WIFI = 1;
142 private static final int MESSAGE_STOP_WIFI = 2;
143 private static final int MESSAGE_START_WIFI = 3;
144 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
145
146 private final WifiHandler mWifiHandler;
147
148 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 * Cache of scan results objects (size is somewhat arbitrary)
150 */
151 private static final int SCAN_RESULT_CACHE_SIZE = 80;
152 private final LinkedHashMap<String, ScanResult> mScanResultCache;
153
154 /*
155 * Character buffer used to parse scan results (optimization)
156 */
157 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private boolean mNeedReconfig;
159
Dianne Hackborn617f8772009-03-31 15:04:46 -0700160 /*
161 * Last UID that asked to enable WIFI.
162 */
163 private int mLastEnableUid = Process.myUid();
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 /**
166 * Number of allowed radio frequency channels in various regulatory domains.
167 * This list is sufficient for 802.11b/g networks (2.4GHz range).
168 */
169 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
170
171 private static final String ACTION_DEVICE_IDLE =
172 "com.android.server.WifiManager.action.DEVICE_IDLE";
173
174 WifiService(Context context, WifiStateTracker tracker) {
175 mContext = context;
176 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400177 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700178 mBatteryStats = BatteryStatsService.getService();
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 mScanResultCache = new LinkedHashMap<String, ScanResult>(
181 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
182 /*
183 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
184 * elements
185 */
186 public boolean removeEldestEntry(Map.Entry eldest) {
187 return SCAN_RESULT_CACHE_SIZE < this.size();
188 }
189 };
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 HandlerThread wifiThread = new HandlerThread("WifiService");
192 wifiThread.start();
193 mWifiHandler = new WifiHandler(wifiThread.getLooper());
194
195 mWifiState = WIFI_STATE_DISABLED;
196 boolean wifiEnabled = getPersistedWifiEnabled();
197
198 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
199 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
200 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
201
202 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
203 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
204 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
205 mWifiStateTracker.setReleaseWakeLockCallback(
206 new Runnable() {
207 public void run() {
208 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
209 synchronized (sDriverStopWakeLock) {
210 if (sDriverStopWakeLock.isHeld()) {
211 sDriverStopWakeLock.release();
212 }
213 }
214 }
215 }
216 );
217
218 Log.i(TAG, "WifiService starting up with Wi-Fi " +
219 (wifiEnabled ? "enabled" : "disabled"));
220
221 mContext.registerReceiver(
222 new BroadcastReceiver() {
223 @Override
224 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700225 // clear our flag indicating the user has overwridden airplane mode
226 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 updateWifiState();
228 }
229 },
230 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
231
Dianne Hackborn617f8772009-03-31 15:04:46 -0700232 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 }
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private boolean getPersistedWifiEnabled() {
236 final ContentResolver cr = mContext.getContentResolver();
237 try {
238 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
239 } catch (Settings.SettingNotFoundException e) {
240 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
241 return false;
242 }
243 }
244
245 private void persistWifiEnabled(boolean enabled) {
246 final ContentResolver cr = mContext.getContentResolver();
247 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
248 }
249
250 NetworkStateTracker getNetworkStateTracker() {
251 return mWifiStateTracker;
252 }
253
254 /**
255 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
256 * @return {@code true} if the operation succeeds
257 */
258 public boolean pingSupplicant() {
259 enforceChangePermission();
260 synchronized (mWifiStateTracker) {
261 return WifiNative.pingCommand();
262 }
263 }
264
265 /**
266 * see {@link android.net.wifi.WifiManager#startScan()}
267 * @return {@code true} if the operation succeeds
268 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400269 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 enforceChangePermission();
271 synchronized (mWifiStateTracker) {
272 switch (mWifiStateTracker.getSupplicantState()) {
273 case DISCONNECTED:
274 case INACTIVE:
275 case SCANNING:
276 case DORMANT:
277 break;
278 default:
279 WifiNative.setScanResultHandlingCommand(
280 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
281 break;
282 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400283 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 }
286
287 /**
288 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
289 * @param enable {@code true} to enable, {@code false} to disable.
290 * @return {@code true} if the enable/disable operation was
291 * started or is already in the queue.
292 */
293 public boolean setWifiEnabled(boolean enable) {
294 enforceChangePermission();
295 if (mWifiHandler == null) return false;
296
297 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700298 // caller may not have WAKE_LOCK permission - it's not required here
299 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700301 Binder.restoreCallingIdentity(ident);
302
Dianne Hackborn617f8772009-03-31 15:04:46 -0700303 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700304 // set a flag if the user is enabling Wifi while in airplane mode
305 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700306 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 }
308
309 return true;
310 }
311
312 /**
313 * Enables/disables Wi-Fi synchronously.
314 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
315 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700316 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 * @return {@code true} if the operation succeeds (or if the existing state
318 * is the same as the requested state)
319 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700320 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
322
323 if (mWifiState == eventualWifiState) {
324 return true;
325 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700326 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 return false;
328 }
329
Dianne Hackborn617f8772009-03-31 15:04:46 -0700330 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331
332 if (enable) {
333 if (!WifiNative.loadDriver()) {
334 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700335 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 return false;
337 }
338 if (!WifiNative.startSupplicant()) {
339 WifiNative.unloadDriver();
340 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700341 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 return false;
343 }
344 registerForBroadcasts();
345 mWifiStateTracker.startEventLoop();
346 } else {
347
348 mContext.unregisterReceiver(mReceiver);
349 // Remove notification (it will no-op if it isn't visible)
350 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
351
352 boolean failedToStopSupplicantOrUnloadDriver = false;
353 if (!WifiNative.stopSupplicant()) {
354 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700355 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 failedToStopSupplicantOrUnloadDriver = true;
357 }
358
359 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400360 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361
362 if (!WifiNative.unloadDriver()) {
363 Log.e(TAG, "Failed to unload Wi-Fi driver.");
364 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700365 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 failedToStopSupplicantOrUnloadDriver = true;
367 }
368 }
369 if (failedToStopSupplicantOrUnloadDriver) {
370 return false;
371 }
372 }
373
374 // Success!
375
376 if (persist) {
377 persistWifiEnabled(enable);
378 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700379 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 return true;
382 }
383
Dianne Hackborn617f8772009-03-31 15:04:46 -0700384 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 final int previousWifiState = mWifiState;
386
The Android Open Source Project10592532009-03-18 17:39:46 -0700387 long ident = Binder.clearCallingIdentity();
388 try {
389 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700390 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700391 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700392 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700393 }
394 } catch (RemoteException e) {
395 } finally {
396 Binder.restoreCallingIdentity(ident);
397 }
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 // Update state
400 mWifiState = wifiState;
401
402 // Broadcast
403 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
404 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
405 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
406 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
407 mContext.sendStickyBroadcast(intent);
408 }
409
410 private void enforceAccessPermission() {
411 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
412 "WifiService");
413 }
414
415 private void enforceChangePermission() {
416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
417 "WifiService");
418
419 }
420
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700421 private void enforceMulticastChangePermission() {
422 mContext.enforceCallingOrSelfPermission(
423 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
424 "WifiService");
425 }
426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 /**
428 * see {@link WifiManager#getWifiState()}
429 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
430 * {@link WifiManager#WIFI_STATE_DISABLING},
431 * {@link WifiManager#WIFI_STATE_ENABLED},
432 * {@link WifiManager#WIFI_STATE_ENABLING},
433 * {@link WifiManager#WIFI_STATE_UNKNOWN}
434 */
435 public int getWifiEnabledState() {
436 enforceAccessPermission();
437 return mWifiState;
438 }
439
440 /**
441 * see {@link android.net.wifi.WifiManager#disconnect()}
442 * @return {@code true} if the operation succeeds
443 */
444 public boolean disconnect() {
445 enforceChangePermission();
446 synchronized (mWifiStateTracker) {
447 return WifiNative.disconnectCommand();
448 }
449 }
450
451 /**
452 * see {@link android.net.wifi.WifiManager#reconnect()}
453 * @return {@code true} if the operation succeeds
454 */
455 public boolean reconnect() {
456 enforceChangePermission();
457 synchronized (mWifiStateTracker) {
458 return WifiNative.reconnectCommand();
459 }
460 }
461
462 /**
463 * see {@link android.net.wifi.WifiManager#reassociate()}
464 * @return {@code true} if the operation succeeds
465 */
466 public boolean reassociate() {
467 enforceChangePermission();
468 synchronized (mWifiStateTracker) {
469 return WifiNative.reassociateCommand();
470 }
471 }
472
473 /**
474 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
475 * @return the list of configured networks
476 */
477 public List<WifiConfiguration> getConfiguredNetworks() {
478 enforceAccessPermission();
479 String listStr;
480 /*
481 * We don't cache the list, because we want to allow
482 * for the possibility that the configuration file
483 * has been modified through some external means,
484 * such as the wpa_cli command line program.
485 */
486 synchronized (mWifiStateTracker) {
487 listStr = WifiNative.listNetworksCommand();
488 }
489 List<WifiConfiguration> networks =
490 new ArrayList<WifiConfiguration>();
491 if (listStr == null)
492 return networks;
493
494 String[] lines = listStr.split("\n");
495 // Skip the first line, which is a header
496 for (int i = 1; i < lines.length; i++) {
497 String[] result = lines[i].split("\t");
498 // network-id | ssid | bssid | flags
499 WifiConfiguration config = new WifiConfiguration();
500 try {
501 config.networkId = Integer.parseInt(result[0]);
502 } catch(NumberFormatException e) {
503 continue;
504 }
505 if (result.length > 3) {
506 if (result[3].indexOf("[CURRENT]") != -1)
507 config.status = WifiConfiguration.Status.CURRENT;
508 else if (result[3].indexOf("[DISABLED]") != -1)
509 config.status = WifiConfiguration.Status.DISABLED;
510 else
511 config.status = WifiConfiguration.Status.ENABLED;
512 } else
513 config.status = WifiConfiguration.Status.ENABLED;
514 synchronized (mWifiStateTracker) {
515 readNetworkVariables(config);
516 }
517 networks.add(config);
518 }
519
520 return networks;
521 }
522
523 /**
524 * Read the variables from the supplicant daemon that are needed to
525 * fill in the WifiConfiguration object.
526 * <p/>
527 * The caller must hold the synchronization monitor.
528 * @param config the {@link WifiConfiguration} object to be filled in.
529 */
530 private static void readNetworkVariables(WifiConfiguration config) {
531
532 int netId = config.networkId;
533 if (netId < 0)
534 return;
535
536 /*
537 * TODO: maybe should have a native method that takes an array of
538 * variable names and returns an array of values. But we'd still
539 * be doing a round trip to the supplicant daemon for each variable.
540 */
541 String value;
542
543 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
544 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800545 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 } else {
547 config.SSID = null;
548 }
549
550 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
551 if (!TextUtils.isEmpty(value)) {
552 config.BSSID = value;
553 } else {
554 config.BSSID = null;
555 }
556
557 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
558 config.priority = -1;
559 if (!TextUtils.isEmpty(value)) {
560 try {
561 config.priority = Integer.parseInt(value);
562 } catch (NumberFormatException ignore) {
563 }
564 }
565
566 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
567 config.hiddenSSID = false;
568 if (!TextUtils.isEmpty(value)) {
569 try {
570 config.hiddenSSID = Integer.parseInt(value) != 0;
571 } catch (NumberFormatException ignore) {
572 }
573 }
574
575 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
576 config.wepTxKeyIndex = -1;
577 if (!TextUtils.isEmpty(value)) {
578 try {
579 config.wepTxKeyIndex = Integer.parseInt(value);
580 } catch (NumberFormatException ignore) {
581 }
582 }
583
584 /*
585 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
586 * just a "*" if the key is set, or the null string otherwise.
587 */
588 for (int i = 0; i < 4; i++) {
589 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
590 if (!TextUtils.isEmpty(value)) {
591 config.wepKeys[i] = value;
592 } else {
593 config.wepKeys[i] = null;
594 }
595 }
596
597 /*
598 * Get the private shared key. Note that the actual keys are not passed back,
599 * just a "*" if the key is set, or the null string otherwise.
600 */
601 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
602 if (!TextUtils.isEmpty(value)) {
603 config.preSharedKey = value;
604 } else {
605 config.preSharedKey = null;
606 }
607
608 value = WifiNative.getNetworkVariableCommand(config.networkId,
609 WifiConfiguration.Protocol.varName);
610 if (!TextUtils.isEmpty(value)) {
611 String vals[] = value.split(" ");
612 for (String val : vals) {
613 int index =
614 lookupString(val, WifiConfiguration.Protocol.strings);
615 if (0 <= index) {
616 config.allowedProtocols.set(index);
617 }
618 }
619 }
620
621 value = WifiNative.getNetworkVariableCommand(config.networkId,
622 WifiConfiguration.KeyMgmt.varName);
623 if (!TextUtils.isEmpty(value)) {
624 String vals[] = value.split(" ");
625 for (String val : vals) {
626 int index =
627 lookupString(val, WifiConfiguration.KeyMgmt.strings);
628 if (0 <= index) {
629 config.allowedKeyManagement.set(index);
630 }
631 }
632 }
633
634 value = WifiNative.getNetworkVariableCommand(config.networkId,
635 WifiConfiguration.AuthAlgorithm.varName);
636 if (!TextUtils.isEmpty(value)) {
637 String vals[] = value.split(" ");
638 for (String val : vals) {
639 int index =
640 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
641 if (0 <= index) {
642 config.allowedAuthAlgorithms.set(index);
643 }
644 }
645 }
646
647 value = WifiNative.getNetworkVariableCommand(config.networkId,
648 WifiConfiguration.PairwiseCipher.varName);
649 if (!TextUtils.isEmpty(value)) {
650 String vals[] = value.split(" ");
651 for (String val : vals) {
652 int index =
653 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
654 if (0 <= index) {
655 config.allowedPairwiseCiphers.set(index);
656 }
657 }
658 }
659
660 value = WifiNative.getNetworkVariableCommand(config.networkId,
661 WifiConfiguration.GroupCipher.varName);
662 if (!TextUtils.isEmpty(value)) {
663 String vals[] = value.split(" ");
664 for (String val : vals) {
665 int index =
666 lookupString(val, WifiConfiguration.GroupCipher.strings);
667 if (0 <= index) {
668 config.allowedGroupCiphers.set(index);
669 }
670 }
671 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800672
673 for (WifiConfiguration.EnterpriseField field :
674 config.enterpriseFields) {
675 value = WifiNative.getNetworkVariableCommand(netId,
676 field.varName());
677 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800678 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800679 field.setValue(value);
680 }
681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 }
683
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800684 private static String removeDoubleQuotes(String string) {
685 if (string.length() <= 2) return "";
686 return string.substring(1, string.length() - 1);
687 }
688
689 private static String convertToQuotedString(String string) {
690 return "\"" + string + "\"";
691 }
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 /**
694 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
695 * @return the supplicant-assigned identifier for the new or updated
696 * network if the operation succeeds, or {@code -1} if it fails
697 */
698 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
699 enforceChangePermission();
700 /*
701 * If the supplied networkId is -1, we create a new empty
702 * network configuration. Otherwise, the networkId should
703 * refer to an existing configuration.
704 */
705 int netId = config.networkId;
706 boolean newNetwork = netId == -1;
707 boolean doReconfig;
708 int currentPriority;
709 // networkId of -1 means we want to create a new network
710 if (newNetwork) {
711 netId = WifiNative.addNetworkCommand();
712 if (netId < 0) {
713 if (DBG) {
714 Log.d(TAG, "Failed to add a network!");
715 }
716 return -1;
717 }
718 doReconfig = true;
719 } else {
720 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
721 currentPriority = -1;
722 if (!TextUtils.isEmpty(priorityVal)) {
723 try {
724 currentPriority = Integer.parseInt(priorityVal);
725 } catch (NumberFormatException ignore) {
726 }
727 }
728 doReconfig = currentPriority != config.priority;
729 }
730 mNeedReconfig = mNeedReconfig || doReconfig;
731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 setVariables: {
733 /*
734 * Note that if a networkId for a non-existent network
735 * was supplied, then the first setNetworkVariableCommand()
736 * will fail, so we don't bother to make a separate check
737 * for the validity of the ID up front.
738 */
739
740 if (config.SSID != null &&
741 !WifiNative.setNetworkVariableCommand(
742 netId,
743 WifiConfiguration.ssidVarName,
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800744 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 if (DBG) {
746 Log.d(TAG, "failed to set SSID: "+config.SSID);
747 }
748 break setVariables;
749 }
750
751 if (config.BSSID != null &&
752 !WifiNative.setNetworkVariableCommand(
753 netId,
754 WifiConfiguration.bssidVarName,
755 config.BSSID)) {
756 if (DBG) {
757 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
758 }
759 break setVariables;
760 }
761
762 String allowedKeyManagementString =
763 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
764 if (config.allowedKeyManagement.cardinality() != 0 &&
765 !WifiNative.setNetworkVariableCommand(
766 netId,
767 WifiConfiguration.KeyMgmt.varName,
768 allowedKeyManagementString)) {
769 if (DBG) {
770 Log.d(TAG, "failed to set key_mgmt: "+
771 allowedKeyManagementString);
772 }
773 break setVariables;
774 }
775
776 String allowedProtocolsString =
777 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
778 if (config.allowedProtocols.cardinality() != 0 &&
779 !WifiNative.setNetworkVariableCommand(
780 netId,
781 WifiConfiguration.Protocol.varName,
782 allowedProtocolsString)) {
783 if (DBG) {
784 Log.d(TAG, "failed to set proto: "+
785 allowedProtocolsString);
786 }
787 break setVariables;
788 }
789
790 String allowedAuthAlgorithmsString =
791 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
792 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
793 !WifiNative.setNetworkVariableCommand(
794 netId,
795 WifiConfiguration.AuthAlgorithm.varName,
796 allowedAuthAlgorithmsString)) {
797 if (DBG) {
798 Log.d(TAG, "failed to set auth_alg: "+
799 allowedAuthAlgorithmsString);
800 }
801 break setVariables;
802 }
803
804 String allowedPairwiseCiphersString =
805 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
806 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
807 !WifiNative.setNetworkVariableCommand(
808 netId,
809 WifiConfiguration.PairwiseCipher.varName,
810 allowedPairwiseCiphersString)) {
811 if (DBG) {
812 Log.d(TAG, "failed to set pairwise: "+
813 allowedPairwiseCiphersString);
814 }
815 break setVariables;
816 }
817
818 String allowedGroupCiphersString =
819 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
820 if (config.allowedGroupCiphers.cardinality() != 0 &&
821 !WifiNative.setNetworkVariableCommand(
822 netId,
823 WifiConfiguration.GroupCipher.varName,
824 allowedGroupCiphersString)) {
825 if (DBG) {
826 Log.d(TAG, "failed to set group: "+
827 allowedGroupCiphersString);
828 }
829 break setVariables;
830 }
831
832 // Prevent client screw-up by passing in a WifiConfiguration we gave it
833 // by preventing "*" as a key.
834 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
835 !WifiNative.setNetworkVariableCommand(
836 netId,
837 WifiConfiguration.pskVarName,
838 config.preSharedKey)) {
839 if (DBG) {
840 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
841 }
842 break setVariables;
843 }
844
845 boolean hasSetKey = false;
846 if (config.wepKeys != null) {
847 for (int i = 0; i < config.wepKeys.length; i++) {
848 // Prevent client screw-up by passing in a WifiConfiguration we gave it
849 // by preventing "*" as a key.
850 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
851 if (!WifiNative.setNetworkVariableCommand(
852 netId,
853 WifiConfiguration.wepKeyVarNames[i],
854 config.wepKeys[i])) {
855 if (DBG) {
856 Log.d(TAG,
857 "failed to set wep_key"+i+": " +
858 config.wepKeys[i]);
859 }
860 break setVariables;
861 }
862 hasSetKey = true;
863 }
864 }
865 }
866
867 if (hasSetKey) {
868 if (!WifiNative.setNetworkVariableCommand(
869 netId,
870 WifiConfiguration.wepTxKeyIdxVarName,
871 Integer.toString(config.wepTxKeyIndex))) {
872 if (DBG) {
873 Log.d(TAG,
874 "failed to set wep_tx_keyidx: "+
875 config.wepTxKeyIndex);
876 }
877 break setVariables;
878 }
879 }
880
881 if (!WifiNative.setNetworkVariableCommand(
882 netId,
883 WifiConfiguration.priorityVarName,
884 Integer.toString(config.priority))) {
885 if (DBG) {
886 Log.d(TAG, config.SSID + ": failed to set priority: "
887 +config.priority);
888 }
889 break setVariables;
890 }
891
892 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
893 netId,
894 WifiConfiguration.hiddenSSIDVarName,
895 Integer.toString(config.hiddenSSID ? 1 : 0))) {
896 if (DBG) {
897 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
898 config.hiddenSSID);
899 }
900 break setVariables;
901 }
902
Chung-yih Wang43374762009-09-16 14:28:42 +0800903 for (WifiConfiguration.EnterpriseField field
904 : config.enterpriseFields) {
905 String varName = field.varName();
906 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800907 if (value != null) {
908 if (field != config.eap) {
909 value = convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800910 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800911 if (!WifiNative.setNetworkVariableCommand(
912 netId,
913 varName,
914 value)) {
915 if (DBG) {
916 Log.d(TAG, config.SSID + ": failed to set " + varName +
917 ": " + value);
918 }
919 break setVariables;
920 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800921 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 return netId;
924 }
925
926 /*
927 * For an update, if one of the setNetworkVariable operations fails,
928 * we might want to roll back all the changes already made. But the
929 * chances are that if anything is going to go wrong, it'll happen
930 * the first time we try to set one of the variables.
931 */
932 if (newNetwork) {
933 removeNetwork(netId);
934 if (DBG) {
935 Log.d(TAG,
936 "Failed to set a network variable, removed network: "
937 + netId);
938 }
939 }
940 return -1;
941 }
942
943 private static String makeString(BitSet set, String[] strings) {
944 StringBuffer buf = new StringBuffer();
945 int nextSetBit = -1;
946
947 /* Make sure all set bits are in [0, strings.length) to avoid
948 * going out of bounds on strings. (Shouldn't happen, but...) */
949 set = set.get(0, strings.length);
950
951 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
952 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
953 }
954
955 // remove trailing space
956 if (set.cardinality() > 0) {
957 buf.setLength(buf.length() - 1);
958 }
959
960 return buf.toString();
961 }
962
963 private static int lookupString(String string, String[] strings) {
964 int size = strings.length;
965
966 string = string.replace('-', '_');
967
968 for (int i = 0; i < size; i++)
969 if (string.equals(strings[i]))
970 return i;
971
972 if (DBG) {
973 // if we ever get here, we should probably add the
974 // value to WifiConfiguration to reflect that it's
975 // supported by the WPA supplicant
976 Log.w(TAG, "Failed to look-up a string: " + string);
977 }
978
979 return -1;
980 }
981
982 /**
983 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
984 * @param netId the integer that identifies the network configuration
985 * to the supplicant
986 * @return {@code true} if the operation succeeded
987 */
988 public boolean removeNetwork(int netId) {
989 enforceChangePermission();
990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 return mWifiStateTracker.removeNetwork(netId);
992 }
993
994 /**
995 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
996 * @param netId the integer that identifies the network configuration
997 * to the supplicant
998 * @param disableOthers if true, disable all other networks.
999 * @return {@code true} if the operation succeeded
1000 */
1001 public boolean enableNetwork(int netId, boolean disableOthers) {
1002 enforceChangePermission();
1003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001005 String ifname = mWifiStateTracker.getInterfaceName();
1006 NetworkUtils.enableInterface(ifname);
1007 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1008 if (!result) {
1009 NetworkUtils.disableInterface(ifname);
1010 }
1011 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013 }
1014
1015 /**
1016 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1017 * @param netId the integer that identifies the network configuration
1018 * to the supplicant
1019 * @return {@code true} if the operation succeeded
1020 */
1021 public boolean disableNetwork(int netId) {
1022 enforceChangePermission();
1023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 synchronized (mWifiStateTracker) {
1025 return WifiNative.disableNetworkCommand(netId);
1026 }
1027 }
1028
1029 /**
1030 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1031 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1032 */
1033 public WifiInfo getConnectionInfo() {
1034 enforceAccessPermission();
1035 /*
1036 * Make sure we have the latest information, by sending
1037 * a status request to the supplicant.
1038 */
1039 return mWifiStateTracker.requestConnectionInfo();
1040 }
1041
1042 /**
1043 * Return the results of the most recent access point scan, in the form of
1044 * a list of {@link ScanResult} objects.
1045 * @return the list of results
1046 */
1047 public List<ScanResult> getScanResults() {
1048 enforceAccessPermission();
1049 String reply;
1050 synchronized (mWifiStateTracker) {
1051 reply = WifiNative.scanResultsCommand();
1052 }
1053 if (reply == null) {
1054 return null;
1055 }
1056
1057 List<ScanResult> scanList = new ArrayList<ScanResult>();
1058
1059 int lineCount = 0;
1060
1061 int replyLen = reply.length();
1062 // Parse the result string, keeping in mind that the last line does
1063 // not end with a newline.
1064 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1065 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1066 ++lineCount;
1067 /*
1068 * Skip the first line, which is a header
1069 */
1070 if (lineCount == 1) {
1071 lineBeg = lineEnd + 1;
1072 continue;
1073 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001074 if (lineEnd > lineBeg) {
1075 String line = reply.substring(lineBeg, lineEnd);
1076 ScanResult scanResult = parseScanResult(line);
1077 if (scanResult != null) {
1078 scanList.add(scanResult);
1079 } else if (DBG) {
1080 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 }
1083 lineBeg = lineEnd + 1;
1084 }
1085 }
1086 mWifiStateTracker.setScanResultsList(scanList);
1087 return scanList;
1088 }
1089
1090 /**
1091 * Parse the scan result line passed to us by wpa_supplicant (helper).
1092 * @param line the line to parse
1093 * @return the {@link ScanResult} object
1094 */
1095 private ScanResult parseScanResult(String line) {
1096 ScanResult scanResult = null;
1097 if (line != null) {
1098 /*
1099 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1100 * must synchronized here!
1101 */
1102 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001103 String[] result = scanResultPattern.split(line);
1104 if (3 <= result.length && result.length <= 5) {
1105 String bssid = result[0];
1106 // bssid | frequency | level | flags | ssid
1107 int frequency;
1108 int level;
1109 try {
1110 frequency = Integer.parseInt(result[1]);
1111 level = Integer.parseInt(result[2]);
1112 /* some implementations avoid negative values by adding 256
1113 * so we need to adjust for that here.
1114 */
1115 if (level > 0) level -= 256;
1116 } catch (NumberFormatException e) {
1117 frequency = 0;
1118 level = 0;
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120
Mike Lockwood1a645052009-06-25 13:01:12 -04001121 /*
1122 * The formatting of the results returned by
1123 * wpa_supplicant is intended to make the fields
1124 * line up nicely when printed,
1125 * not to make them easy to parse. So we have to
1126 * apply some heuristics to figure out which field
1127 * is the SSID and which field is the flags.
1128 */
1129 String ssid;
1130 String flags;
1131 if (result.length == 4) {
1132 if (result[3].charAt(0) == '[') {
1133 flags = result[3];
1134 ssid = "";
1135 } else {
1136 flags = "";
1137 ssid = result[3];
1138 }
1139 } else if (result.length == 5) {
1140 flags = result[3];
1141 ssid = result[4];
1142 } else {
1143 // Here, we must have 3 fields: no flags and ssid
1144 // set
1145 flags = "";
1146 ssid = "";
1147 }
1148
Mike Lockwood00717e22009-08-17 10:09:36 -04001149 // bssid + ssid is the hash key
1150 String key = bssid + ssid;
1151 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001152 if (scanResult != null) {
1153 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001154 scanResult.SSID = ssid;
1155 scanResult.capabilities = flags;
1156 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001157 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 // Do not add scan results that have no SSID set
1159 if (0 < ssid.trim().length()) {
1160 scanResult =
1161 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001162 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001163 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001166 } else {
1167 Log.w(TAG, "Misformatted scan result text with " +
1168 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170 }
1171 }
1172
1173 return scanResult;
1174 }
1175
1176 /**
1177 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1178 * and construct a {@code WifiConfiguration} that describes the encryption,
1179 * key management, and authenticaion capabilities of the access point.
1180 * @param flags the string returned by wpa_supplicant
1181 * @return the {@link WifiConfiguration} object, filled in
1182 */
1183 WifiConfiguration parseScanFlags(String flags) {
1184 WifiConfiguration config = new WifiConfiguration();
1185
1186 if (flags.length() == 0) {
1187 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1188 }
1189 // ... to be implemented
1190 return config;
1191 }
1192
1193 /**
1194 * Tell the supplicant to persist the current list of configured networks.
1195 * @return {@code true} if the operation succeeded
1196 */
1197 public boolean saveConfiguration() {
1198 boolean result;
1199 enforceChangePermission();
1200 synchronized (mWifiStateTracker) {
1201 result = WifiNative.saveConfigCommand();
1202 if (result && mNeedReconfig) {
1203 mNeedReconfig = false;
1204 result = WifiNative.reloadConfigCommand();
1205
1206 if (result) {
1207 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1208 mContext.sendBroadcast(intent);
1209 }
1210 }
1211 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001212 // Inform the backup manager about a data change
1213 IBackupManager ibm = IBackupManager.Stub.asInterface(
1214 ServiceManager.getService(Context.BACKUP_SERVICE));
1215 if (ibm != null) {
1216 try {
1217 ibm.dataChanged("com.android.providers.settings");
1218 } catch (Exception e) {
1219 // Try again later
1220 }
1221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 return result;
1223 }
1224
1225 /**
1226 * Set the number of radio frequency channels that are allowed to be used
1227 * in the current regulatory domain. This method should be used only
1228 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001229 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 * persisted as a Secure setting.
1231 * @param numChannels the number of allowed channels. Must be greater than 0
1232 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001233 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1235 * {@code numChannels} is outside the valid range.
1236 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001237 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1238 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1239 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 enforceChangePermission();
1241 /*
1242 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1243 * but if Wi-Fi isn't currently enabled, that's not possible, and
1244 * we want to persist the setting anyway,so that it will take
1245 * effect when Wi-Fi does become enabled.
1246 */
1247 boolean found = false;
1248 for (int validChan : sValidRegulatoryChannelCounts) {
1249 if (validChan == numChannels) {
1250 found = true;
1251 break;
1252 }
1253 }
1254 if (!found) {
1255 return false;
1256 }
1257
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001258 if (persist) {
1259 Settings.Secure.putInt(mContext.getContentResolver(),
1260 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1261 numChannels);
1262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 mWifiStateTracker.setNumAllowedChannels(numChannels);
1264 return true;
1265 }
1266
1267 /**
1268 * Return the number of frequency channels that are allowed
1269 * to be used in the current regulatory domain.
1270 * @return the number of allowed channels, or {@code -1} if an error occurs
1271 */
1272 public int getNumAllowedChannels() {
1273 int numChannels;
1274
1275 enforceAccessPermission();
1276 synchronized (mWifiStateTracker) {
1277 /*
1278 * If we can't get the value from the driver (e.g., because
1279 * Wi-Fi is not currently enabled), get the value from
1280 * Settings.
1281 */
1282 numChannels = WifiNative.getNumAllowedChannelsCommand();
1283 if (numChannels < 0) {
1284 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1285 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1286 -1);
1287 }
1288 }
1289 return numChannels;
1290 }
1291
1292 /**
1293 * Return the list of valid values for the number of allowed radio channels
1294 * for various regulatory domains.
1295 * @return the list of channel counts
1296 */
1297 public int[] getValidChannelCounts() {
1298 enforceAccessPermission();
1299 return sValidRegulatoryChannelCounts;
1300 }
1301
1302 /**
1303 * Return the DHCP-assigned addresses from the last successful DHCP request,
1304 * if any.
1305 * @return the DHCP information
1306 */
1307 public DhcpInfo getDhcpInfo() {
1308 enforceAccessPermission();
1309 return mWifiStateTracker.getDhcpInfo();
1310 }
1311
1312 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1313 @Override
1314 public void onReceive(Context context, Intent intent) {
1315 String action = intent.getAction();
1316
1317 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1318 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1319 int stayAwakeConditions =
1320 Settings.System.getInt(mContext.getContentResolver(),
1321 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1322 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001323 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 mAlarmManager.cancel(mIdleIntent);
1325 mDeviceIdle = false;
1326 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001327 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001329 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001331 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 /*
1333 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1334 * AND the "stay on while plugged in" setting doesn't match the
1335 * current power conditions (i.e, not plugged in, plugged in to USB,
1336 * or plugged in to AC).
1337 */
1338 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001339 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1340 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001341 // we used to go to sleep immediately, but this caused some race conditions
1342 // we don't have time to track down for this release. Delay instead, but not
1343 // as long as we would if connected (below)
1344 // TODO - fix the race conditions and switch back to the immediate turn-off
1345 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
1346 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
1347 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1348 // // do not keep Wifi awake when screen is off if Wifi is not associated
1349 // mDeviceIdle = true;
1350 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001351 } else {
1352 long triggerTime = System.currentTimeMillis() + idleMillis;
1353 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1354 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 /* we can return now -- there's nothing to do until we get the idle intent back */
1358 return;
1359 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001360 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 mDeviceIdle = true;
1362 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1363 /*
1364 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1365 * AND we are transitioning from a state in which the device was supposed
1366 * to stay awake to a state in which it is not supposed to stay awake.
1367 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1368 * the already-set timer.
1369 */
1370 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001371 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1373 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1374 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001375 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1377 mPluggedType = pluggedType;
1378 return;
1379 }
1380 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001381 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001382 boolean isBluetoothPlaying =
1383 intent.getIntExtra(
Nick Pelly005b2282009-09-10 10:21:56 -07001384 BluetoothA2dp.EXTRA_SINK_STATE,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001385 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1386 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 } else {
1388 return;
1389 }
1390
1391 updateWifiState();
1392 }
1393
1394 /**
1395 * Determines whether the Wi-Fi chipset should stay awake or be put to
1396 * sleep. Looks at the setting for the sleep policy and the current
1397 * conditions.
1398 *
1399 * @see #shouldDeviceStayAwake(int, int)
1400 */
1401 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1402 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1403 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1404
1405 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1406 // Never sleep
1407 return true;
1408 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1409 (pluggedType != 0)) {
1410 // Never sleep while plugged, and we're plugged
1411 return true;
1412 } else {
1413 // Default
1414 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1415 }
1416 }
1417
1418 /**
1419 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1420 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1421 * of {@code 0} isn't really a plugged type, but rather an indication that the
1422 * device isn't plugged in at all, there is no bit value corresponding to a
1423 * {@code pluggedType} value of {@code 0}. That is why we shift by
1424 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1425 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1426 * keep the device (and hence Wi-Fi) awake.
1427 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1428 * being made
1429 * @return {@code true} if {@code pluggedType} indicates that the device is
1430 * supposed to stay awake, {@code false} otherwise.
1431 */
1432 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1433 return (stayAwakeConditions & pluggedType) != 0;
1434 }
1435 };
1436
Dianne Hackborn617f8772009-03-31 15:04:46 -07001437 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 Message msg = Message.obtain(mWifiHandler,
1439 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001440 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 msg.sendToTarget();
1442 }
1443
1444 private void sendStartMessage(boolean scanOnlyMode) {
1445 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1446 }
1447
1448 private void updateWifiState() {
1449 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001450 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 boolean lockHeld = mLocks.hasLocks();
1452 int strongestLockMode;
1453 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1454 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1455 if (mDeviceIdle && lockHeld) {
1456 strongestLockMode = mLocks.getStrongestLockMode();
1457 } else {
1458 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1459 }
1460
1461 synchronized (mWifiHandler) {
1462 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1463 return;
1464 }
1465 if (wifiShouldBeEnabled) {
1466 if (wifiShouldBeStarted) {
1467 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001468 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 sWakeLock.acquire();
1470 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1471 } else {
1472 int wakeLockTimeout =
1473 Settings.Secure.getInt(
1474 mContext.getContentResolver(),
1475 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1476 DEFAULT_WAKELOCK_TIMEOUT);
1477 /*
1478 * The following wakelock is held in order to ensure
1479 * that the connectivity manager has time to fail over
1480 * to the mobile data network. The connectivity manager
1481 * releases it once mobile data connectivity has been
1482 * established. If connectivity cannot be established,
1483 * the wakelock is released after wakeLockTimeout
1484 * milliseconds have elapsed.
1485 */
1486 sDriverStopWakeLock.acquire();
1487 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1488 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1489 }
1490 } else {
1491 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001492 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494 }
1495 }
1496
1497 private void registerForBroadcasts() {
1498 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1500 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1501 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1502 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001503 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 mContext.registerReceiver(mReceiver, intentFilter);
1505 }
1506
1507 private boolean isAirplaneSensitive() {
1508 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1509 Settings.System.AIRPLANE_MODE_RADIOS);
1510 return airplaneModeRadios == null
1511 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1512 }
1513
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001514 private boolean isAirplaneToggleable() {
1515 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1516 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1517 return toggleableRadios != null
1518 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1519 }
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 /**
1522 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1523 * currently on.
1524 * @return {@code true} if airplane mode is on.
1525 */
1526 private boolean isAirplaneModeOn() {
1527 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1528 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1529 }
1530
1531 /**
1532 * Handler that allows posting to the WifiThread.
1533 */
1534 private class WifiHandler extends Handler {
1535 public WifiHandler(Looper looper) {
1536 super(looper);
1537 }
1538
1539 @Override
1540 public void handleMessage(Message msg) {
1541 switch (msg.what) {
1542
1543 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001544 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 sWakeLock.release();
1546 break;
1547
1548 case MESSAGE_START_WIFI:
1549 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1550 mWifiStateTracker.restart();
1551 sWakeLock.release();
1552 break;
1553
1554 case MESSAGE_DISABLE_WIFI:
1555 // a non-zero msg.arg1 value means the "enabled" setting
1556 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001557 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 sWakeLock.release();
1559 break;
1560
1561 case MESSAGE_STOP_WIFI:
1562 mWifiStateTracker.disconnectAndStop();
1563 // don't release wakelock
1564 break;
1565
1566 case MESSAGE_RELEASE_WAKELOCK:
1567 synchronized (sDriverStopWakeLock) {
1568 if (sDriverStopWakeLock.isHeld()) {
1569 sDriverStopWakeLock.release();
1570 }
1571 }
1572 break;
1573 }
1574 }
1575 }
1576
1577 @Override
1578 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1579 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1580 != PackageManager.PERMISSION_GRANTED) {
1581 pw.println("Permission Denial: can't dump WifiService from from pid="
1582 + Binder.getCallingPid()
1583 + ", uid=" + Binder.getCallingUid());
1584 return;
1585 }
1586 pw.println("Wi-Fi is " + stateName(mWifiState));
1587 pw.println("Stay-awake conditions: " +
1588 Settings.System.getInt(mContext.getContentResolver(),
1589 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1590 pw.println();
1591
1592 pw.println("Internal state:");
1593 pw.println(mWifiStateTracker);
1594 pw.println();
1595 pw.println("Latest scan results:");
1596 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1597 if (scanResults != null && scanResults.size() != 0) {
1598 pw.println(" BSSID Frequency RSSI Flags SSID");
1599 for (ScanResult r : scanResults) {
1600 pw.printf(" %17s %9d %5d %-16s %s%n",
1601 r.BSSID,
1602 r.frequency,
1603 r.level,
1604 r.capabilities,
1605 r.SSID == null ? "" : r.SSID);
1606 }
1607 }
1608 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001609 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1610 mScanLocksAcquired + " scan");
1611 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1612 mScanLocksReleased + " scan");
1613 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 pw.println("Locks held:");
1615 mLocks.dump(pw);
1616 }
1617
1618 private static String stateName(int wifiState) {
1619 switch (wifiState) {
1620 case WIFI_STATE_DISABLING:
1621 return "disabling";
1622 case WIFI_STATE_DISABLED:
1623 return "disabled";
1624 case WIFI_STATE_ENABLING:
1625 return "enabling";
1626 case WIFI_STATE_ENABLED:
1627 return "enabled";
1628 case WIFI_STATE_UNKNOWN:
1629 return "unknown state";
1630 default:
1631 return "[invalid state]";
1632 }
1633 }
1634
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001635 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001637 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639
1640 public void binderDied() {
1641 synchronized (mLocks) {
1642 releaseWifiLockLocked(mBinder);
1643 }
1644 }
1645
1646 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001647 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650
1651 private class LockList {
1652 private List<WifiLock> mList;
1653
1654 private LockList() {
1655 mList = new ArrayList<WifiLock>();
1656 }
1657
1658 private synchronized boolean hasLocks() {
1659 return !mList.isEmpty();
1660 }
1661
1662 private synchronized int getStrongestLockMode() {
1663 if (mList.isEmpty()) {
1664 return WifiManager.WIFI_MODE_FULL;
1665 }
1666 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001667 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 return WifiManager.WIFI_MODE_FULL;
1669 }
1670 }
1671 return WifiManager.WIFI_MODE_SCAN_ONLY;
1672 }
1673
1674 private void addLock(WifiLock lock) {
1675 if (findLockByBinder(lock.mBinder) < 0) {
1676 mList.add(lock);
1677 }
1678 }
1679
1680 private WifiLock removeLock(IBinder binder) {
1681 int index = findLockByBinder(binder);
1682 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001683 WifiLock ret = mList.remove(index);
1684 ret.unlinkDeathRecipient();
1685 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 } else {
1687 return null;
1688 }
1689 }
1690
1691 private int findLockByBinder(IBinder binder) {
1692 int size = mList.size();
1693 for (int i = size - 1; i >= 0; i--)
1694 if (mList.get(i).mBinder == binder)
1695 return i;
1696 return -1;
1697 }
1698
1699 private void dump(PrintWriter pw) {
1700 for (WifiLock l : mList) {
1701 pw.print(" ");
1702 pw.println(l);
1703 }
1704 }
1705 }
1706
1707 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1708 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1709 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1710 return false;
1711 }
1712 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1713 synchronized (mLocks) {
1714 return acquireWifiLockLocked(wifiLock);
1715 }
1716 }
1717
1718 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001719 Log.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001722
The Android Open Source Project10592532009-03-18 17:39:46 -07001723 int uid = Binder.getCallingUid();
1724 long ident = Binder.clearCallingIdentity();
1725 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001726 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001727 case WifiManager.WIFI_MODE_FULL:
1728 ++mFullLocksAcquired;
1729 mBatteryStats.noteFullWifiLockAcquired(uid);
1730 break;
1731 case WifiManager.WIFI_MODE_SCAN_ONLY:
1732 ++mScanLocksAcquired;
1733 mBatteryStats.noteScanWifiLockAcquired(uid);
1734 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001735 }
1736 } catch (RemoteException e) {
1737 } finally {
1738 Binder.restoreCallingIdentity(ident);
1739 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 updateWifiState();
1742 return true;
1743 }
1744
1745 public boolean releaseWifiLock(IBinder lock) {
1746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1747 synchronized (mLocks) {
1748 return releaseWifiLockLocked(lock);
1749 }
1750 }
1751
1752 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001753 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001754
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001756
1757 Log.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1758
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001759 hadLock = (wifiLock != null);
1760
1761 if (hadLock) {
1762 int uid = Binder.getCallingUid();
1763 long ident = Binder.clearCallingIdentity();
1764 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001765 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001766 case WifiManager.WIFI_MODE_FULL:
1767 ++mFullLocksReleased;
1768 mBatteryStats.noteFullWifiLockReleased(uid);
1769 break;
1770 case WifiManager.WIFI_MODE_SCAN_ONLY:
1771 ++mScanLocksReleased;
1772 mBatteryStats.noteScanWifiLockReleased(uid);
1773 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001774 }
1775 } catch (RemoteException e) {
1776 } finally {
1777 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001778 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001779 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001780 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001782 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001784
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001785 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001786 implements IBinder.DeathRecipient {
1787 String mTag;
1788 int mMode;
1789 IBinder mBinder;
1790
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001791 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001792 super();
1793 mTag = tag;
1794 mMode = mode;
1795 mBinder = binder;
1796 try {
1797 mBinder.linkToDeath(this, 0);
1798 } catch (RemoteException e) {
1799 binderDied();
1800 }
1801 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001802
1803 void unlinkDeathRecipient() {
1804 mBinder.unlinkToDeath(this, 0);
1805 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001806 }
1807
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001808 private class Multicaster extends DeathRecipient {
1809 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001810 super(Binder.getCallingUid(), tag, binder);
1811 }
1812
1813 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001814 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001815 synchronized (mMulticasters) {
1816 int i = mMulticasters.indexOf(this);
1817 if (i != -1) {
1818 removeMulticasterLocked(i, mMode);
1819 }
1820 }
1821 }
1822
1823 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001824 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001825 }
1826
1827 public int getUid() {
1828 return mMode;
1829 }
1830 }
1831
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001832 public void initializeMulticastFiltering() {
1833 enforceMulticastChangePermission();
1834
1835 synchronized (mMulticasters) {
1836 // if anybody had requested filters be off, leave off
1837 if (mMulticasters.size() != 0) {
1838 return;
1839 } else {
1840 WifiNative.startPacketFiltering();
1841 }
1842 }
1843 }
1844
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001845 public void acquireMulticastLock(IBinder binder, String tag) {
1846 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001847
1848 synchronized (mMulticasters) {
1849 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001850 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001851 // Note that we could call stopPacketFiltering only when
1852 // our new size == 1 (first call), but this function won't
1853 // be called often and by making the stopPacket call each
1854 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001855 synchronized (mWifiStateTracker) {
1856 WifiNative.stopPacketFiltering();
1857 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001858 }
1859
1860 int uid = Binder.getCallingUid();
1861 Long ident = Binder.clearCallingIdentity();
1862 try {
1863 mBatteryStats.noteWifiMulticastEnabled(uid);
1864 } catch (RemoteException e) {
1865 } finally {
1866 Binder.restoreCallingIdentity(ident);
1867 }
1868 }
1869
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001870 public void releaseMulticastLock() {
1871 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001872
1873 int uid = Binder.getCallingUid();
1874 synchronized (mMulticasters) {
1875 mMulticastDisabled++;
1876 int size = mMulticasters.size();
1877 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001878 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001879 if ((m != null) && (m.getUid() == uid)) {
1880 removeMulticasterLocked(i, uid);
1881 }
1882 }
1883 }
1884 }
1885
1886 private void removeMulticasterLocked(int i, int uid)
1887 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001888 Multicaster removed = mMulticasters.remove(i);
1889 if (removed != null) {
1890 removed.unlinkDeathRecipient();
1891 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001892 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001893 synchronized (mWifiStateTracker) {
1894 WifiNative.startPacketFiltering();
1895 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001896 }
1897
1898 Long ident = Binder.clearCallingIdentity();
1899 try {
1900 mBatteryStats.noteWifiMulticastDisabled(uid);
1901 } catch (RemoteException e) {
1902 } finally {
1903 Binder.restoreCallingIdentity(ident);
1904 }
1905 }
1906
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001907 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001908 enforceAccessPermission();
1909
1910 synchronized (mMulticasters) {
1911 return (mMulticasters.size() > 0);
1912 }
1913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914}