blob: cc1b6977c8061d42718d2574c4093940e12b5fb7 [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)) {
545 config.SSID = value;
546 } 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)) {
678 field.setValue(value);
679 }
680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682
683 /**
684 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
685 * @return the supplicant-assigned identifier for the new or updated
686 * network if the operation succeeds, or {@code -1} if it fails
687 */
688 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
689 enforceChangePermission();
690 /*
691 * If the supplied networkId is -1, we create a new empty
692 * network configuration. Otherwise, the networkId should
693 * refer to an existing configuration.
694 */
695 int netId = config.networkId;
696 boolean newNetwork = netId == -1;
697 boolean doReconfig;
698 int currentPriority;
699 // networkId of -1 means we want to create a new network
700 if (newNetwork) {
701 netId = WifiNative.addNetworkCommand();
702 if (netId < 0) {
703 if (DBG) {
704 Log.d(TAG, "Failed to add a network!");
705 }
706 return -1;
707 }
708 doReconfig = true;
709 } else {
710 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
711 currentPriority = -1;
712 if (!TextUtils.isEmpty(priorityVal)) {
713 try {
714 currentPriority = Integer.parseInt(priorityVal);
715 } catch (NumberFormatException ignore) {
716 }
717 }
718 doReconfig = currentPriority != config.priority;
719 }
720 mNeedReconfig = mNeedReconfig || doReconfig;
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 setVariables: {
723 /*
724 * Note that if a networkId for a non-existent network
725 * was supplied, then the first setNetworkVariableCommand()
726 * will fail, so we don't bother to make a separate check
727 * for the validity of the ID up front.
728 */
729
730 if (config.SSID != null &&
731 !WifiNative.setNetworkVariableCommand(
732 netId,
733 WifiConfiguration.ssidVarName,
734 config.SSID)) {
735 if (DBG) {
736 Log.d(TAG, "failed to set SSID: "+config.SSID);
737 }
738 break setVariables;
739 }
740
741 if (config.BSSID != null &&
742 !WifiNative.setNetworkVariableCommand(
743 netId,
744 WifiConfiguration.bssidVarName,
745 config.BSSID)) {
746 if (DBG) {
747 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
748 }
749 break setVariables;
750 }
751
752 String allowedKeyManagementString =
753 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
754 if (config.allowedKeyManagement.cardinality() != 0 &&
755 !WifiNative.setNetworkVariableCommand(
756 netId,
757 WifiConfiguration.KeyMgmt.varName,
758 allowedKeyManagementString)) {
759 if (DBG) {
760 Log.d(TAG, "failed to set key_mgmt: "+
761 allowedKeyManagementString);
762 }
763 break setVariables;
764 }
765
766 String allowedProtocolsString =
767 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
768 if (config.allowedProtocols.cardinality() != 0 &&
769 !WifiNative.setNetworkVariableCommand(
770 netId,
771 WifiConfiguration.Protocol.varName,
772 allowedProtocolsString)) {
773 if (DBG) {
774 Log.d(TAG, "failed to set proto: "+
775 allowedProtocolsString);
776 }
777 break setVariables;
778 }
779
780 String allowedAuthAlgorithmsString =
781 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
782 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
783 !WifiNative.setNetworkVariableCommand(
784 netId,
785 WifiConfiguration.AuthAlgorithm.varName,
786 allowedAuthAlgorithmsString)) {
787 if (DBG) {
788 Log.d(TAG, "failed to set auth_alg: "+
789 allowedAuthAlgorithmsString);
790 }
791 break setVariables;
792 }
793
794 String allowedPairwiseCiphersString =
795 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
796 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
797 !WifiNative.setNetworkVariableCommand(
798 netId,
799 WifiConfiguration.PairwiseCipher.varName,
800 allowedPairwiseCiphersString)) {
801 if (DBG) {
802 Log.d(TAG, "failed to set pairwise: "+
803 allowedPairwiseCiphersString);
804 }
805 break setVariables;
806 }
807
808 String allowedGroupCiphersString =
809 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
810 if (config.allowedGroupCiphers.cardinality() != 0 &&
811 !WifiNative.setNetworkVariableCommand(
812 netId,
813 WifiConfiguration.GroupCipher.varName,
814 allowedGroupCiphersString)) {
815 if (DBG) {
816 Log.d(TAG, "failed to set group: "+
817 allowedGroupCiphersString);
818 }
819 break setVariables;
820 }
821
822 // Prevent client screw-up by passing in a WifiConfiguration we gave it
823 // by preventing "*" as a key.
824 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
825 !WifiNative.setNetworkVariableCommand(
826 netId,
827 WifiConfiguration.pskVarName,
828 config.preSharedKey)) {
829 if (DBG) {
830 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
831 }
832 break setVariables;
833 }
834
835 boolean hasSetKey = false;
836 if (config.wepKeys != null) {
837 for (int i = 0; i < config.wepKeys.length; i++) {
838 // Prevent client screw-up by passing in a WifiConfiguration we gave it
839 // by preventing "*" as a key.
840 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
841 if (!WifiNative.setNetworkVariableCommand(
842 netId,
843 WifiConfiguration.wepKeyVarNames[i],
844 config.wepKeys[i])) {
845 if (DBG) {
846 Log.d(TAG,
847 "failed to set wep_key"+i+": " +
848 config.wepKeys[i]);
849 }
850 break setVariables;
851 }
852 hasSetKey = true;
853 }
854 }
855 }
856
857 if (hasSetKey) {
858 if (!WifiNative.setNetworkVariableCommand(
859 netId,
860 WifiConfiguration.wepTxKeyIdxVarName,
861 Integer.toString(config.wepTxKeyIndex))) {
862 if (DBG) {
863 Log.d(TAG,
864 "failed to set wep_tx_keyidx: "+
865 config.wepTxKeyIndex);
866 }
867 break setVariables;
868 }
869 }
870
871 if (!WifiNative.setNetworkVariableCommand(
872 netId,
873 WifiConfiguration.priorityVarName,
874 Integer.toString(config.priority))) {
875 if (DBG) {
876 Log.d(TAG, config.SSID + ": failed to set priority: "
877 +config.priority);
878 }
879 break setVariables;
880 }
881
882 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
883 netId,
884 WifiConfiguration.hiddenSSIDVarName,
885 Integer.toString(config.hiddenSSID ? 1 : 0))) {
886 if (DBG) {
887 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
888 config.hiddenSSID);
889 }
890 break setVariables;
891 }
892
Chung-yih Wang43374762009-09-16 14:28:42 +0800893 for (WifiConfiguration.EnterpriseField field
894 : config.enterpriseFields) {
895 String varName = field.varName();
896 String value = field.value();
897 if ((value != null) && !WifiNative.setNetworkVariableCommand(
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800898 netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800899 varName,
900 value)) {
901 if (DBG) {
902 Log.d(TAG, config.SSID + ": failed to set " + varName +
903 ": " + value);
904 }
905 break setVariables;
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800906 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800907 }
908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 return netId;
910 }
911
912 /*
913 * For an update, if one of the setNetworkVariable operations fails,
914 * we might want to roll back all the changes already made. But the
915 * chances are that if anything is going to go wrong, it'll happen
916 * the first time we try to set one of the variables.
917 */
918 if (newNetwork) {
919 removeNetwork(netId);
920 if (DBG) {
921 Log.d(TAG,
922 "Failed to set a network variable, removed network: "
923 + netId);
924 }
925 }
926 return -1;
927 }
928
929 private static String makeString(BitSet set, String[] strings) {
930 StringBuffer buf = new StringBuffer();
931 int nextSetBit = -1;
932
933 /* Make sure all set bits are in [0, strings.length) to avoid
934 * going out of bounds on strings. (Shouldn't happen, but...) */
935 set = set.get(0, strings.length);
936
937 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
938 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
939 }
940
941 // remove trailing space
942 if (set.cardinality() > 0) {
943 buf.setLength(buf.length() - 1);
944 }
945
946 return buf.toString();
947 }
948
949 private static int lookupString(String string, String[] strings) {
950 int size = strings.length;
951
952 string = string.replace('-', '_');
953
954 for (int i = 0; i < size; i++)
955 if (string.equals(strings[i]))
956 return i;
957
958 if (DBG) {
959 // if we ever get here, we should probably add the
960 // value to WifiConfiguration to reflect that it's
961 // supported by the WPA supplicant
962 Log.w(TAG, "Failed to look-up a string: " + string);
963 }
964
965 return -1;
966 }
967
968 /**
969 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
970 * @param netId the integer that identifies the network configuration
971 * to the supplicant
972 * @return {@code true} if the operation succeeded
973 */
974 public boolean removeNetwork(int netId) {
975 enforceChangePermission();
976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 return mWifiStateTracker.removeNetwork(netId);
978 }
979
980 /**
981 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
982 * @param netId the integer that identifies the network configuration
983 * to the supplicant
984 * @param disableOthers if true, disable all other networks.
985 * @return {@code true} if the operation succeeded
986 */
987 public boolean enableNetwork(int netId, boolean disableOthers) {
988 enforceChangePermission();
989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -0400991 String ifname = mWifiStateTracker.getInterfaceName();
992 NetworkUtils.enableInterface(ifname);
993 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
994 if (!result) {
995 NetworkUtils.disableInterface(ifname);
996 }
997 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999 }
1000
1001 /**
1002 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1003 * @param netId the integer that identifies the network configuration
1004 * to the supplicant
1005 * @return {@code true} if the operation succeeded
1006 */
1007 public boolean disableNetwork(int netId) {
1008 enforceChangePermission();
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 synchronized (mWifiStateTracker) {
1011 return WifiNative.disableNetworkCommand(netId);
1012 }
1013 }
1014
1015 /**
1016 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1017 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1018 */
1019 public WifiInfo getConnectionInfo() {
1020 enforceAccessPermission();
1021 /*
1022 * Make sure we have the latest information, by sending
1023 * a status request to the supplicant.
1024 */
1025 return mWifiStateTracker.requestConnectionInfo();
1026 }
1027
1028 /**
1029 * Return the results of the most recent access point scan, in the form of
1030 * a list of {@link ScanResult} objects.
1031 * @return the list of results
1032 */
1033 public List<ScanResult> getScanResults() {
1034 enforceAccessPermission();
1035 String reply;
1036 synchronized (mWifiStateTracker) {
1037 reply = WifiNative.scanResultsCommand();
1038 }
1039 if (reply == null) {
1040 return null;
1041 }
1042
1043 List<ScanResult> scanList = new ArrayList<ScanResult>();
1044
1045 int lineCount = 0;
1046
1047 int replyLen = reply.length();
1048 // Parse the result string, keeping in mind that the last line does
1049 // not end with a newline.
1050 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1051 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1052 ++lineCount;
1053 /*
1054 * Skip the first line, which is a header
1055 */
1056 if (lineCount == 1) {
1057 lineBeg = lineEnd + 1;
1058 continue;
1059 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001060 if (lineEnd > lineBeg) {
1061 String line = reply.substring(lineBeg, lineEnd);
1062 ScanResult scanResult = parseScanResult(line);
1063 if (scanResult != null) {
1064 scanList.add(scanResult);
1065 } else if (DBG) {
1066 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 }
1069 lineBeg = lineEnd + 1;
1070 }
1071 }
1072 mWifiStateTracker.setScanResultsList(scanList);
1073 return scanList;
1074 }
1075
1076 /**
1077 * Parse the scan result line passed to us by wpa_supplicant (helper).
1078 * @param line the line to parse
1079 * @return the {@link ScanResult} object
1080 */
1081 private ScanResult parseScanResult(String line) {
1082 ScanResult scanResult = null;
1083 if (line != null) {
1084 /*
1085 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1086 * must synchronized here!
1087 */
1088 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001089 String[] result = scanResultPattern.split(line);
1090 if (3 <= result.length && result.length <= 5) {
1091 String bssid = result[0];
1092 // bssid | frequency | level | flags | ssid
1093 int frequency;
1094 int level;
1095 try {
1096 frequency = Integer.parseInt(result[1]);
1097 level = Integer.parseInt(result[2]);
1098 /* some implementations avoid negative values by adding 256
1099 * so we need to adjust for that here.
1100 */
1101 if (level > 0) level -= 256;
1102 } catch (NumberFormatException e) {
1103 frequency = 0;
1104 level = 0;
1105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106
Mike Lockwood1a645052009-06-25 13:01:12 -04001107 /*
1108 * The formatting of the results returned by
1109 * wpa_supplicant is intended to make the fields
1110 * line up nicely when printed,
1111 * not to make them easy to parse. So we have to
1112 * apply some heuristics to figure out which field
1113 * is the SSID and which field is the flags.
1114 */
1115 String ssid;
1116 String flags;
1117 if (result.length == 4) {
1118 if (result[3].charAt(0) == '[') {
1119 flags = result[3];
1120 ssid = "";
1121 } else {
1122 flags = "";
1123 ssid = result[3];
1124 }
1125 } else if (result.length == 5) {
1126 flags = result[3];
1127 ssid = result[4];
1128 } else {
1129 // Here, we must have 3 fields: no flags and ssid
1130 // set
1131 flags = "";
1132 ssid = "";
1133 }
1134
Mike Lockwood00717e22009-08-17 10:09:36 -04001135 // bssid + ssid is the hash key
1136 String key = bssid + ssid;
1137 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001138 if (scanResult != null) {
1139 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001140 scanResult.SSID = ssid;
1141 scanResult.capabilities = flags;
1142 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001143 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 // Do not add scan results that have no SSID set
1145 if (0 < ssid.trim().length()) {
1146 scanResult =
1147 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001148 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001149 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001152 } else {
1153 Log.w(TAG, "Misformatted scan result text with " +
1154 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156 }
1157 }
1158
1159 return scanResult;
1160 }
1161
1162 /**
1163 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1164 * and construct a {@code WifiConfiguration} that describes the encryption,
1165 * key management, and authenticaion capabilities of the access point.
1166 * @param flags the string returned by wpa_supplicant
1167 * @return the {@link WifiConfiguration} object, filled in
1168 */
1169 WifiConfiguration parseScanFlags(String flags) {
1170 WifiConfiguration config = new WifiConfiguration();
1171
1172 if (flags.length() == 0) {
1173 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1174 }
1175 // ... to be implemented
1176 return config;
1177 }
1178
1179 /**
1180 * Tell the supplicant to persist the current list of configured networks.
1181 * @return {@code true} if the operation succeeded
1182 */
1183 public boolean saveConfiguration() {
1184 boolean result;
1185 enforceChangePermission();
1186 synchronized (mWifiStateTracker) {
1187 result = WifiNative.saveConfigCommand();
1188 if (result && mNeedReconfig) {
1189 mNeedReconfig = false;
1190 result = WifiNative.reloadConfigCommand();
1191
1192 if (result) {
1193 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1194 mContext.sendBroadcast(intent);
1195 }
1196 }
1197 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001198 // Inform the backup manager about a data change
1199 IBackupManager ibm = IBackupManager.Stub.asInterface(
1200 ServiceManager.getService(Context.BACKUP_SERVICE));
1201 if (ibm != null) {
1202 try {
1203 ibm.dataChanged("com.android.providers.settings");
1204 } catch (Exception e) {
1205 // Try again later
1206 }
1207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 return result;
1209 }
1210
1211 /**
1212 * Set the number of radio frequency channels that are allowed to be used
1213 * in the current regulatory domain. This method should be used only
1214 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001215 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 * persisted as a Secure setting.
1217 * @param numChannels the number of allowed channels. Must be greater than 0
1218 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001219 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1221 * {@code numChannels} is outside the valid range.
1222 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001223 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1224 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1225 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 enforceChangePermission();
1227 /*
1228 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1229 * but if Wi-Fi isn't currently enabled, that's not possible, and
1230 * we want to persist the setting anyway,so that it will take
1231 * effect when Wi-Fi does become enabled.
1232 */
1233 boolean found = false;
1234 for (int validChan : sValidRegulatoryChannelCounts) {
1235 if (validChan == numChannels) {
1236 found = true;
1237 break;
1238 }
1239 }
1240 if (!found) {
1241 return false;
1242 }
1243
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001244 if (persist) {
1245 Settings.Secure.putInt(mContext.getContentResolver(),
1246 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1247 numChannels);
1248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 mWifiStateTracker.setNumAllowedChannels(numChannels);
1250 return true;
1251 }
1252
1253 /**
1254 * Return the number of frequency channels that are allowed
1255 * to be used in the current regulatory domain.
1256 * @return the number of allowed channels, or {@code -1} if an error occurs
1257 */
1258 public int getNumAllowedChannels() {
1259 int numChannels;
1260
1261 enforceAccessPermission();
1262 synchronized (mWifiStateTracker) {
1263 /*
1264 * If we can't get the value from the driver (e.g., because
1265 * Wi-Fi is not currently enabled), get the value from
1266 * Settings.
1267 */
1268 numChannels = WifiNative.getNumAllowedChannelsCommand();
1269 if (numChannels < 0) {
1270 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1271 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1272 -1);
1273 }
1274 }
1275 return numChannels;
1276 }
1277
1278 /**
1279 * Return the list of valid values for the number of allowed radio channels
1280 * for various regulatory domains.
1281 * @return the list of channel counts
1282 */
1283 public int[] getValidChannelCounts() {
1284 enforceAccessPermission();
1285 return sValidRegulatoryChannelCounts;
1286 }
1287
1288 /**
1289 * Return the DHCP-assigned addresses from the last successful DHCP request,
1290 * if any.
1291 * @return the DHCP information
1292 */
1293 public DhcpInfo getDhcpInfo() {
1294 enforceAccessPermission();
1295 return mWifiStateTracker.getDhcpInfo();
1296 }
1297
1298 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1299 @Override
1300 public void onReceive(Context context, Intent intent) {
1301 String action = intent.getAction();
1302
1303 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1304 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1305 int stayAwakeConditions =
1306 Settings.System.getInt(mContext.getContentResolver(),
1307 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1308 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001309 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 mAlarmManager.cancel(mIdleIntent);
1311 mDeviceIdle = false;
1312 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001313 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001315 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001317 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 /*
1319 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1320 * AND the "stay on while plugged in" setting doesn't match the
1321 * current power conditions (i.e, not plugged in, plugged in to USB,
1322 * or plugged in to AC).
1323 */
1324 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001325 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1326 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1327 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001328 mDeviceIdle = true;
1329 updateWifiState();
1330 } else {
1331 long triggerTime = System.currentTimeMillis() + idleMillis;
1332 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1333 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 /* we can return now -- there's nothing to do until we get the idle intent back */
1337 return;
1338 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001339 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 mDeviceIdle = true;
1341 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1342 /*
1343 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1344 * AND we are transitioning from a state in which the device was supposed
1345 * to stay awake to a state in which it is not supposed to stay awake.
1346 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1347 * the already-set timer.
1348 */
1349 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001350 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1352 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1353 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001354 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1356 mPluggedType = pluggedType;
1357 return;
1358 }
1359 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001360 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001361 boolean isBluetoothPlaying =
1362 intent.getIntExtra(
Nick Pelly005b2282009-09-10 10:21:56 -07001363 BluetoothA2dp.EXTRA_SINK_STATE,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001364 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1365 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 } else {
1367 return;
1368 }
1369
1370 updateWifiState();
1371 }
1372
1373 /**
1374 * Determines whether the Wi-Fi chipset should stay awake or be put to
1375 * sleep. Looks at the setting for the sleep policy and the current
1376 * conditions.
1377 *
1378 * @see #shouldDeviceStayAwake(int, int)
1379 */
1380 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1381 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1382 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1383
1384 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1385 // Never sleep
1386 return true;
1387 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1388 (pluggedType != 0)) {
1389 // Never sleep while plugged, and we're plugged
1390 return true;
1391 } else {
1392 // Default
1393 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1394 }
1395 }
1396
1397 /**
1398 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1399 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1400 * of {@code 0} isn't really a plugged type, but rather an indication that the
1401 * device isn't plugged in at all, there is no bit value corresponding to a
1402 * {@code pluggedType} value of {@code 0}. That is why we shift by
1403 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1404 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1405 * keep the device (and hence Wi-Fi) awake.
1406 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1407 * being made
1408 * @return {@code true} if {@code pluggedType} indicates that the device is
1409 * supposed to stay awake, {@code false} otherwise.
1410 */
1411 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1412 return (stayAwakeConditions & pluggedType) != 0;
1413 }
1414 };
1415
Dianne Hackborn617f8772009-03-31 15:04:46 -07001416 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 Message msg = Message.obtain(mWifiHandler,
1418 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001419 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 msg.sendToTarget();
1421 }
1422
1423 private void sendStartMessage(boolean scanOnlyMode) {
1424 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1425 }
1426
1427 private void updateWifiState() {
1428 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001429 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 boolean lockHeld = mLocks.hasLocks();
1431 int strongestLockMode;
1432 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1433 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1434 if (mDeviceIdle && lockHeld) {
1435 strongestLockMode = mLocks.getStrongestLockMode();
1436 } else {
1437 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1438 }
1439
1440 synchronized (mWifiHandler) {
1441 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1442 return;
1443 }
1444 if (wifiShouldBeEnabled) {
1445 if (wifiShouldBeStarted) {
1446 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001447 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 sWakeLock.acquire();
1449 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1450 } else {
1451 int wakeLockTimeout =
1452 Settings.Secure.getInt(
1453 mContext.getContentResolver(),
1454 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1455 DEFAULT_WAKELOCK_TIMEOUT);
1456 /*
1457 * The following wakelock is held in order to ensure
1458 * that the connectivity manager has time to fail over
1459 * to the mobile data network. The connectivity manager
1460 * releases it once mobile data connectivity has been
1461 * established. If connectivity cannot be established,
1462 * the wakelock is released after wakeLockTimeout
1463 * milliseconds have elapsed.
1464 */
1465 sDriverStopWakeLock.acquire();
1466 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1467 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1468 }
1469 } else {
1470 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001471 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
1473 }
1474 }
1475
1476 private void registerForBroadcasts() {
1477 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1479 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1480 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1481 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001482 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 mContext.registerReceiver(mReceiver, intentFilter);
1484 }
1485
1486 private boolean isAirplaneSensitive() {
1487 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1488 Settings.System.AIRPLANE_MODE_RADIOS);
1489 return airplaneModeRadios == null
1490 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1491 }
1492
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001493 private boolean isAirplaneToggleable() {
1494 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1495 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1496 return toggleableRadios != null
1497 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1498 }
1499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 /**
1501 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1502 * currently on.
1503 * @return {@code true} if airplane mode is on.
1504 */
1505 private boolean isAirplaneModeOn() {
1506 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1507 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1508 }
1509
1510 /**
1511 * Handler that allows posting to the WifiThread.
1512 */
1513 private class WifiHandler extends Handler {
1514 public WifiHandler(Looper looper) {
1515 super(looper);
1516 }
1517
1518 @Override
1519 public void handleMessage(Message msg) {
1520 switch (msg.what) {
1521
1522 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001523 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 sWakeLock.release();
1525 break;
1526
1527 case MESSAGE_START_WIFI:
1528 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1529 mWifiStateTracker.restart();
1530 sWakeLock.release();
1531 break;
1532
1533 case MESSAGE_DISABLE_WIFI:
1534 // a non-zero msg.arg1 value means the "enabled" setting
1535 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001536 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 sWakeLock.release();
1538 break;
1539
1540 case MESSAGE_STOP_WIFI:
1541 mWifiStateTracker.disconnectAndStop();
1542 // don't release wakelock
1543 break;
1544
1545 case MESSAGE_RELEASE_WAKELOCK:
1546 synchronized (sDriverStopWakeLock) {
1547 if (sDriverStopWakeLock.isHeld()) {
1548 sDriverStopWakeLock.release();
1549 }
1550 }
1551 break;
1552 }
1553 }
1554 }
1555
1556 @Override
1557 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1558 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1559 != PackageManager.PERMISSION_GRANTED) {
1560 pw.println("Permission Denial: can't dump WifiService from from pid="
1561 + Binder.getCallingPid()
1562 + ", uid=" + Binder.getCallingUid());
1563 return;
1564 }
1565 pw.println("Wi-Fi is " + stateName(mWifiState));
1566 pw.println("Stay-awake conditions: " +
1567 Settings.System.getInt(mContext.getContentResolver(),
1568 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1569 pw.println();
1570
1571 pw.println("Internal state:");
1572 pw.println(mWifiStateTracker);
1573 pw.println();
1574 pw.println("Latest scan results:");
1575 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1576 if (scanResults != null && scanResults.size() != 0) {
1577 pw.println(" BSSID Frequency RSSI Flags SSID");
1578 for (ScanResult r : scanResults) {
1579 pw.printf(" %17s %9d %5d %-16s %s%n",
1580 r.BSSID,
1581 r.frequency,
1582 r.level,
1583 r.capabilities,
1584 r.SSID == null ? "" : r.SSID);
1585 }
1586 }
1587 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001588 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1589 mScanLocksAcquired + " scan");
1590 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1591 mScanLocksReleased + " scan");
1592 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 pw.println("Locks held:");
1594 mLocks.dump(pw);
1595 }
1596
1597 private static String stateName(int wifiState) {
1598 switch (wifiState) {
1599 case WIFI_STATE_DISABLING:
1600 return "disabling";
1601 case WIFI_STATE_DISABLED:
1602 return "disabled";
1603 case WIFI_STATE_ENABLING:
1604 return "enabling";
1605 case WIFI_STATE_ENABLED:
1606 return "enabled";
1607 case WIFI_STATE_UNKNOWN:
1608 return "unknown state";
1609 default:
1610 return "[invalid state]";
1611 }
1612 }
1613
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001614 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001616 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
1619 public void binderDied() {
1620 synchronized (mLocks) {
1621 releaseWifiLockLocked(mBinder);
1622 }
1623 }
1624
1625 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001626 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628 }
1629
1630 private class LockList {
1631 private List<WifiLock> mList;
1632
1633 private LockList() {
1634 mList = new ArrayList<WifiLock>();
1635 }
1636
1637 private synchronized boolean hasLocks() {
1638 return !mList.isEmpty();
1639 }
1640
1641 private synchronized int getStrongestLockMode() {
1642 if (mList.isEmpty()) {
1643 return WifiManager.WIFI_MODE_FULL;
1644 }
1645 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001646 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 return WifiManager.WIFI_MODE_FULL;
1648 }
1649 }
1650 return WifiManager.WIFI_MODE_SCAN_ONLY;
1651 }
1652
1653 private void addLock(WifiLock lock) {
1654 if (findLockByBinder(lock.mBinder) < 0) {
1655 mList.add(lock);
1656 }
1657 }
1658
1659 private WifiLock removeLock(IBinder binder) {
1660 int index = findLockByBinder(binder);
1661 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001662 WifiLock ret = mList.remove(index);
1663 ret.unlinkDeathRecipient();
1664 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 } else {
1666 return null;
1667 }
1668 }
1669
1670 private int findLockByBinder(IBinder binder) {
1671 int size = mList.size();
1672 for (int i = size - 1; i >= 0; i--)
1673 if (mList.get(i).mBinder == binder)
1674 return i;
1675 return -1;
1676 }
1677
1678 private void dump(PrintWriter pw) {
1679 for (WifiLock l : mList) {
1680 pw.print(" ");
1681 pw.println(l);
1682 }
1683 }
1684 }
1685
1686 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1687 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1688 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1689 return false;
1690 }
1691 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1692 synchronized (mLocks) {
1693 return acquireWifiLockLocked(wifiLock);
1694 }
1695 }
1696
1697 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1698 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001699
1700 int uid = Binder.getCallingUid();
1701 long ident = Binder.clearCallingIdentity();
1702 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001703 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001704 case WifiManager.WIFI_MODE_FULL:
1705 ++mFullLocksAcquired;
1706 mBatteryStats.noteFullWifiLockAcquired(uid);
1707 break;
1708 case WifiManager.WIFI_MODE_SCAN_ONLY:
1709 ++mScanLocksAcquired;
1710 mBatteryStats.noteScanWifiLockAcquired(uid);
1711 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001712 }
1713 } catch (RemoteException e) {
1714 } finally {
1715 Binder.restoreCallingIdentity(ident);
1716 }
1717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 updateWifiState();
1719 return true;
1720 }
1721
1722 public boolean releaseWifiLock(IBinder lock) {
1723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1724 synchronized (mLocks) {
1725 return releaseWifiLockLocked(lock);
1726 }
1727 }
1728
1729 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001730 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001731
1732 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001733 hadLock = (wifiLock != null);
1734
1735 if (hadLock) {
1736 int uid = Binder.getCallingUid();
1737 long ident = Binder.clearCallingIdentity();
1738 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001739 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001740 case WifiManager.WIFI_MODE_FULL:
1741 ++mFullLocksReleased;
1742 mBatteryStats.noteFullWifiLockReleased(uid);
1743 break;
1744 case WifiManager.WIFI_MODE_SCAN_ONLY:
1745 ++mScanLocksReleased;
1746 mBatteryStats.noteScanWifiLockReleased(uid);
1747 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001748 }
1749 } catch (RemoteException e) {
1750 } finally {
1751 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001752 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001756 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001758
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001759 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001760 implements IBinder.DeathRecipient {
1761 String mTag;
1762 int mMode;
1763 IBinder mBinder;
1764
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001765 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001766 super();
1767 mTag = tag;
1768 mMode = mode;
1769 mBinder = binder;
1770 try {
1771 mBinder.linkToDeath(this, 0);
1772 } catch (RemoteException e) {
1773 binderDied();
1774 }
1775 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001776
1777 void unlinkDeathRecipient() {
1778 mBinder.unlinkToDeath(this, 0);
1779 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001780 }
1781
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001782 private class Multicaster extends DeathRecipient {
1783 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001784 super(Binder.getCallingUid(), tag, binder);
1785 }
1786
1787 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001788 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001789 synchronized (mMulticasters) {
1790 int i = mMulticasters.indexOf(this);
1791 if (i != -1) {
1792 removeMulticasterLocked(i, mMode);
1793 }
1794 }
1795 }
1796
1797 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001798 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001799 }
1800
1801 public int getUid() {
1802 return mMode;
1803 }
1804 }
1805
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001806 public void acquireMulticastLock(IBinder binder, String tag) {
1807 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001808
1809 synchronized (mMulticasters) {
1810 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001811 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001812 // Note that we could call stopPacketFiltering only when
1813 // our new size == 1 (first call), but this function won't
1814 // be called often and by making the stopPacket call each
1815 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001816 synchronized (mWifiStateTracker) {
1817 WifiNative.stopPacketFiltering();
1818 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001819 }
1820
1821 int uid = Binder.getCallingUid();
1822 Long ident = Binder.clearCallingIdentity();
1823 try {
1824 mBatteryStats.noteWifiMulticastEnabled(uid);
1825 } catch (RemoteException e) {
1826 } finally {
1827 Binder.restoreCallingIdentity(ident);
1828 }
1829 }
1830
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001831 public void releaseMulticastLock() {
1832 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001833
1834 int uid = Binder.getCallingUid();
1835 synchronized (mMulticasters) {
1836 mMulticastDisabled++;
1837 int size = mMulticasters.size();
1838 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001839 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001840 if ((m != null) && (m.getUid() == uid)) {
1841 removeMulticasterLocked(i, uid);
1842 }
1843 }
1844 }
1845 }
1846
1847 private void removeMulticasterLocked(int i, int uid)
1848 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001849 Multicaster removed = mMulticasters.remove(i);
1850 if (removed != null) {
1851 removed.unlinkDeathRecipient();
1852 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001853 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001854 synchronized (mWifiStateTracker) {
1855 WifiNative.startPacketFiltering();
1856 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001857 }
1858
1859 Long ident = Binder.clearCallingIdentity();
1860 try {
1861 mBatteryStats.noteWifiMulticastDisabled(uid);
1862 } catch (RemoteException e) {
1863 } finally {
1864 Binder.restoreCallingIdentity(ident);
1865 }
1866 }
1867
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001868 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001869 enforceAccessPermission();
1870
1871 synchronized (mMulticasters) {
1872 return (mMulticasters.size() > 0);
1873 }
1874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875}