blob: 63bef54b8d853fd3765080f0b246094794379b6d [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) {
298 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700299 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700300 // set a flag if the user is enabling Wifi while in airplane mode
301 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700302 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 }
304
305 return true;
306 }
307
308 /**
309 * Enables/disables Wi-Fi synchronously.
310 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
311 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700312 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 * @return {@code true} if the operation succeeds (or if the existing state
314 * is the same as the requested state)
315 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700316 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
318
319 if (mWifiState == eventualWifiState) {
320 return true;
321 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700322 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 return false;
324 }
325
Dianne Hackborn617f8772009-03-31 15:04:46 -0700326 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327
328 if (enable) {
329 if (!WifiNative.loadDriver()) {
330 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700331 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 return false;
333 }
334 if (!WifiNative.startSupplicant()) {
335 WifiNative.unloadDriver();
336 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700337 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 return false;
339 }
340 registerForBroadcasts();
341 mWifiStateTracker.startEventLoop();
342 } else {
343
344 mContext.unregisterReceiver(mReceiver);
345 // Remove notification (it will no-op if it isn't visible)
346 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
347
348 boolean failedToStopSupplicantOrUnloadDriver = false;
349 if (!WifiNative.stopSupplicant()) {
350 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700351 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 failedToStopSupplicantOrUnloadDriver = true;
353 }
354
355 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400356 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
358 if (!WifiNative.unloadDriver()) {
359 Log.e(TAG, "Failed to unload Wi-Fi driver.");
360 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700361 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 failedToStopSupplicantOrUnloadDriver = true;
363 }
364 }
365 if (failedToStopSupplicantOrUnloadDriver) {
366 return false;
367 }
368 }
369
370 // Success!
371
372 if (persist) {
373 persistWifiEnabled(enable);
374 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700375 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 return true;
378 }
379
Dianne Hackborn617f8772009-03-31 15:04:46 -0700380 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 final int previousWifiState = mWifiState;
382
The Android Open Source Project10592532009-03-18 17:39:46 -0700383 long ident = Binder.clearCallingIdentity();
384 try {
385 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700386 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700387 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700388 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700389 }
390 } catch (RemoteException e) {
391 } finally {
392 Binder.restoreCallingIdentity(ident);
393 }
394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 // Update state
396 mWifiState = wifiState;
397
398 // Broadcast
399 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
401 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
402 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
403 mContext.sendStickyBroadcast(intent);
404 }
405
406 private void enforceAccessPermission() {
407 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
408 "WifiService");
409 }
410
411 private void enforceChangePermission() {
412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
413 "WifiService");
414
415 }
416
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700417 private void enforceMulticastChangePermission() {
418 mContext.enforceCallingOrSelfPermission(
419 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
420 "WifiService");
421 }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 /**
424 * see {@link WifiManager#getWifiState()}
425 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
426 * {@link WifiManager#WIFI_STATE_DISABLING},
427 * {@link WifiManager#WIFI_STATE_ENABLED},
428 * {@link WifiManager#WIFI_STATE_ENABLING},
429 * {@link WifiManager#WIFI_STATE_UNKNOWN}
430 */
431 public int getWifiEnabledState() {
432 enforceAccessPermission();
433 return mWifiState;
434 }
435
436 /**
437 * see {@link android.net.wifi.WifiManager#disconnect()}
438 * @return {@code true} if the operation succeeds
439 */
440 public boolean disconnect() {
441 enforceChangePermission();
442 synchronized (mWifiStateTracker) {
443 return WifiNative.disconnectCommand();
444 }
445 }
446
447 /**
448 * see {@link android.net.wifi.WifiManager#reconnect()}
449 * @return {@code true} if the operation succeeds
450 */
451 public boolean reconnect() {
452 enforceChangePermission();
453 synchronized (mWifiStateTracker) {
454 return WifiNative.reconnectCommand();
455 }
456 }
457
458 /**
459 * see {@link android.net.wifi.WifiManager#reassociate()}
460 * @return {@code true} if the operation succeeds
461 */
462 public boolean reassociate() {
463 enforceChangePermission();
464 synchronized (mWifiStateTracker) {
465 return WifiNative.reassociateCommand();
466 }
467 }
468
469 /**
470 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
471 * @return the list of configured networks
472 */
473 public List<WifiConfiguration> getConfiguredNetworks() {
474 enforceAccessPermission();
475 String listStr;
476 /*
477 * We don't cache the list, because we want to allow
478 * for the possibility that the configuration file
479 * has been modified through some external means,
480 * such as the wpa_cli command line program.
481 */
482 synchronized (mWifiStateTracker) {
483 listStr = WifiNative.listNetworksCommand();
484 }
485 List<WifiConfiguration> networks =
486 new ArrayList<WifiConfiguration>();
487 if (listStr == null)
488 return networks;
489
490 String[] lines = listStr.split("\n");
491 // Skip the first line, which is a header
492 for (int i = 1; i < lines.length; i++) {
493 String[] result = lines[i].split("\t");
494 // network-id | ssid | bssid | flags
495 WifiConfiguration config = new WifiConfiguration();
496 try {
497 config.networkId = Integer.parseInt(result[0]);
498 } catch(NumberFormatException e) {
499 continue;
500 }
501 if (result.length > 3) {
502 if (result[3].indexOf("[CURRENT]") != -1)
503 config.status = WifiConfiguration.Status.CURRENT;
504 else if (result[3].indexOf("[DISABLED]") != -1)
505 config.status = WifiConfiguration.Status.DISABLED;
506 else
507 config.status = WifiConfiguration.Status.ENABLED;
508 } else
509 config.status = WifiConfiguration.Status.ENABLED;
510 synchronized (mWifiStateTracker) {
511 readNetworkVariables(config);
512 }
513 networks.add(config);
514 }
515
516 return networks;
517 }
518
519 /**
520 * Read the variables from the supplicant daemon that are needed to
521 * fill in the WifiConfiguration object.
522 * <p/>
523 * The caller must hold the synchronization monitor.
524 * @param config the {@link WifiConfiguration} object to be filled in.
525 */
526 private static void readNetworkVariables(WifiConfiguration config) {
527
528 int netId = config.networkId;
529 if (netId < 0)
530 return;
531
532 /*
533 * TODO: maybe should have a native method that takes an array of
534 * variable names and returns an array of values. But we'd still
535 * be doing a round trip to the supplicant daemon for each variable.
536 */
537 String value;
538
539 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
540 if (!TextUtils.isEmpty(value)) {
541 config.SSID = value;
542 } else {
543 config.SSID = null;
544 }
545
546 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
547 if (!TextUtils.isEmpty(value)) {
548 config.BSSID = value;
549 } else {
550 config.BSSID = null;
551 }
552
553 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
554 config.priority = -1;
555 if (!TextUtils.isEmpty(value)) {
556 try {
557 config.priority = Integer.parseInt(value);
558 } catch (NumberFormatException ignore) {
559 }
560 }
561
562 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
563 config.hiddenSSID = false;
564 if (!TextUtils.isEmpty(value)) {
565 try {
566 config.hiddenSSID = Integer.parseInt(value) != 0;
567 } catch (NumberFormatException ignore) {
568 }
569 }
570
571 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
572 config.wepTxKeyIndex = -1;
573 if (!TextUtils.isEmpty(value)) {
574 try {
575 config.wepTxKeyIndex = Integer.parseInt(value);
576 } catch (NumberFormatException ignore) {
577 }
578 }
579
580 /*
581 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
582 * just a "*" if the key is set, or the null string otherwise.
583 */
584 for (int i = 0; i < 4; i++) {
585 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
586 if (!TextUtils.isEmpty(value)) {
587 config.wepKeys[i] = value;
588 } else {
589 config.wepKeys[i] = null;
590 }
591 }
592
593 /*
594 * Get the private shared key. Note that the actual keys are not passed back,
595 * just a "*" if the key is set, or the null string otherwise.
596 */
597 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
598 if (!TextUtils.isEmpty(value)) {
599 config.preSharedKey = value;
600 } else {
601 config.preSharedKey = null;
602 }
603
604 value = WifiNative.getNetworkVariableCommand(config.networkId,
605 WifiConfiguration.Protocol.varName);
606 if (!TextUtils.isEmpty(value)) {
607 String vals[] = value.split(" ");
608 for (String val : vals) {
609 int index =
610 lookupString(val, WifiConfiguration.Protocol.strings);
611 if (0 <= index) {
612 config.allowedProtocols.set(index);
613 }
614 }
615 }
616
617 value = WifiNative.getNetworkVariableCommand(config.networkId,
618 WifiConfiguration.KeyMgmt.varName);
619 if (!TextUtils.isEmpty(value)) {
620 String vals[] = value.split(" ");
621 for (String val : vals) {
622 int index =
623 lookupString(val, WifiConfiguration.KeyMgmt.strings);
624 if (0 <= index) {
625 config.allowedKeyManagement.set(index);
626 }
627 }
628 }
629
630 value = WifiNative.getNetworkVariableCommand(config.networkId,
631 WifiConfiguration.AuthAlgorithm.varName);
632 if (!TextUtils.isEmpty(value)) {
633 String vals[] = value.split(" ");
634 for (String val : vals) {
635 int index =
636 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
637 if (0 <= index) {
638 config.allowedAuthAlgorithms.set(index);
639 }
640 }
641 }
642
643 value = WifiNative.getNetworkVariableCommand(config.networkId,
644 WifiConfiguration.PairwiseCipher.varName);
645 if (!TextUtils.isEmpty(value)) {
646 String vals[] = value.split(" ");
647 for (String val : vals) {
648 int index =
649 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
650 if (0 <= index) {
651 config.allowedPairwiseCiphers.set(index);
652 }
653 }
654 }
655
656 value = WifiNative.getNetworkVariableCommand(config.networkId,
657 WifiConfiguration.GroupCipher.varName);
658 if (!TextUtils.isEmpty(value)) {
659 String vals[] = value.split(" ");
660 for (String val : vals) {
661 int index =
662 lookupString(val, WifiConfiguration.GroupCipher.strings);
663 if (0 <= index) {
664 config.allowedGroupCiphers.set(index);
665 }
666 }
667 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800668
669 for (WifiConfiguration.EnterpriseField field :
670 config.enterpriseFields) {
671 value = WifiNative.getNetworkVariableCommand(netId,
672 field.varName());
673 if (!TextUtils.isEmpty(value)) {
674 field.setValue(value);
675 }
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
678
679 /**
680 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
681 * @return the supplicant-assigned identifier for the new or updated
682 * network if the operation succeeds, or {@code -1} if it fails
683 */
684 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
685 enforceChangePermission();
686 /*
687 * If the supplied networkId is -1, we create a new empty
688 * network configuration. Otherwise, the networkId should
689 * refer to an existing configuration.
690 */
691 int netId = config.networkId;
692 boolean newNetwork = netId == -1;
693 boolean doReconfig;
694 int currentPriority;
695 // networkId of -1 means we want to create a new network
696 if (newNetwork) {
697 netId = WifiNative.addNetworkCommand();
698 if (netId < 0) {
699 if (DBG) {
700 Log.d(TAG, "Failed to add a network!");
701 }
702 return -1;
703 }
704 doReconfig = true;
705 } else {
706 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
707 currentPriority = -1;
708 if (!TextUtils.isEmpty(priorityVal)) {
709 try {
710 currentPriority = Integer.parseInt(priorityVal);
711 } catch (NumberFormatException ignore) {
712 }
713 }
714 doReconfig = currentPriority != config.priority;
715 }
716 mNeedReconfig = mNeedReconfig || doReconfig;
717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 setVariables: {
719 /*
720 * Note that if a networkId for a non-existent network
721 * was supplied, then the first setNetworkVariableCommand()
722 * will fail, so we don't bother to make a separate check
723 * for the validity of the ID up front.
724 */
725
726 if (config.SSID != null &&
727 !WifiNative.setNetworkVariableCommand(
728 netId,
729 WifiConfiguration.ssidVarName,
730 config.SSID)) {
731 if (DBG) {
732 Log.d(TAG, "failed to set SSID: "+config.SSID);
733 }
734 break setVariables;
735 }
736
737 if (config.BSSID != null &&
738 !WifiNative.setNetworkVariableCommand(
739 netId,
740 WifiConfiguration.bssidVarName,
741 config.BSSID)) {
742 if (DBG) {
743 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
744 }
745 break setVariables;
746 }
747
748 String allowedKeyManagementString =
749 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
750 if (config.allowedKeyManagement.cardinality() != 0 &&
751 !WifiNative.setNetworkVariableCommand(
752 netId,
753 WifiConfiguration.KeyMgmt.varName,
754 allowedKeyManagementString)) {
755 if (DBG) {
756 Log.d(TAG, "failed to set key_mgmt: "+
757 allowedKeyManagementString);
758 }
759 break setVariables;
760 }
761
762 String allowedProtocolsString =
763 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
764 if (config.allowedProtocols.cardinality() != 0 &&
765 !WifiNative.setNetworkVariableCommand(
766 netId,
767 WifiConfiguration.Protocol.varName,
768 allowedProtocolsString)) {
769 if (DBG) {
770 Log.d(TAG, "failed to set proto: "+
771 allowedProtocolsString);
772 }
773 break setVariables;
774 }
775
776 String allowedAuthAlgorithmsString =
777 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
778 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
779 !WifiNative.setNetworkVariableCommand(
780 netId,
781 WifiConfiguration.AuthAlgorithm.varName,
782 allowedAuthAlgorithmsString)) {
783 if (DBG) {
784 Log.d(TAG, "failed to set auth_alg: "+
785 allowedAuthAlgorithmsString);
786 }
787 break setVariables;
788 }
789
790 String allowedPairwiseCiphersString =
791 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
792 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
793 !WifiNative.setNetworkVariableCommand(
794 netId,
795 WifiConfiguration.PairwiseCipher.varName,
796 allowedPairwiseCiphersString)) {
797 if (DBG) {
798 Log.d(TAG, "failed to set pairwise: "+
799 allowedPairwiseCiphersString);
800 }
801 break setVariables;
802 }
803
804 String allowedGroupCiphersString =
805 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
806 if (config.allowedGroupCiphers.cardinality() != 0 &&
807 !WifiNative.setNetworkVariableCommand(
808 netId,
809 WifiConfiguration.GroupCipher.varName,
810 allowedGroupCiphersString)) {
811 if (DBG) {
812 Log.d(TAG, "failed to set group: "+
813 allowedGroupCiphersString);
814 }
815 break setVariables;
816 }
817
818 // Prevent client screw-up by passing in a WifiConfiguration we gave it
819 // by preventing "*" as a key.
820 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
821 !WifiNative.setNetworkVariableCommand(
822 netId,
823 WifiConfiguration.pskVarName,
824 config.preSharedKey)) {
825 if (DBG) {
826 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
827 }
828 break setVariables;
829 }
830
831 boolean hasSetKey = false;
832 if (config.wepKeys != null) {
833 for (int i = 0; i < config.wepKeys.length; i++) {
834 // Prevent client screw-up by passing in a WifiConfiguration we gave it
835 // by preventing "*" as a key.
836 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
837 if (!WifiNative.setNetworkVariableCommand(
838 netId,
839 WifiConfiguration.wepKeyVarNames[i],
840 config.wepKeys[i])) {
841 if (DBG) {
842 Log.d(TAG,
843 "failed to set wep_key"+i+": " +
844 config.wepKeys[i]);
845 }
846 break setVariables;
847 }
848 hasSetKey = true;
849 }
850 }
851 }
852
853 if (hasSetKey) {
854 if (!WifiNative.setNetworkVariableCommand(
855 netId,
856 WifiConfiguration.wepTxKeyIdxVarName,
857 Integer.toString(config.wepTxKeyIndex))) {
858 if (DBG) {
859 Log.d(TAG,
860 "failed to set wep_tx_keyidx: "+
861 config.wepTxKeyIndex);
862 }
863 break setVariables;
864 }
865 }
866
867 if (!WifiNative.setNetworkVariableCommand(
868 netId,
869 WifiConfiguration.priorityVarName,
870 Integer.toString(config.priority))) {
871 if (DBG) {
872 Log.d(TAG, config.SSID + ": failed to set priority: "
873 +config.priority);
874 }
875 break setVariables;
876 }
877
878 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
879 netId,
880 WifiConfiguration.hiddenSSIDVarName,
881 Integer.toString(config.hiddenSSID ? 1 : 0))) {
882 if (DBG) {
883 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
884 config.hiddenSSID);
885 }
886 break setVariables;
887 }
888
Chung-yih Wang43374762009-09-16 14:28:42 +0800889 for (WifiConfiguration.EnterpriseField field
890 : config.enterpriseFields) {
891 String varName = field.varName();
892 String value = field.value();
893 if ((value != null) && !WifiNative.setNetworkVariableCommand(
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800894 netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800895 varName,
896 value)) {
897 if (DBG) {
898 Log.d(TAG, config.SSID + ": failed to set " + varName +
899 ": " + value);
900 }
901 break setVariables;
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800902 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800903 }
904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return netId;
906 }
907
908 /*
909 * For an update, if one of the setNetworkVariable operations fails,
910 * we might want to roll back all the changes already made. But the
911 * chances are that if anything is going to go wrong, it'll happen
912 * the first time we try to set one of the variables.
913 */
914 if (newNetwork) {
915 removeNetwork(netId);
916 if (DBG) {
917 Log.d(TAG,
918 "Failed to set a network variable, removed network: "
919 + netId);
920 }
921 }
922 return -1;
923 }
924
925 private static String makeString(BitSet set, String[] strings) {
926 StringBuffer buf = new StringBuffer();
927 int nextSetBit = -1;
928
929 /* Make sure all set bits are in [0, strings.length) to avoid
930 * going out of bounds on strings. (Shouldn't happen, but...) */
931 set = set.get(0, strings.length);
932
933 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
934 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
935 }
936
937 // remove trailing space
938 if (set.cardinality() > 0) {
939 buf.setLength(buf.length() - 1);
940 }
941
942 return buf.toString();
943 }
944
945 private static int lookupString(String string, String[] strings) {
946 int size = strings.length;
947
948 string = string.replace('-', '_');
949
950 for (int i = 0; i < size; i++)
951 if (string.equals(strings[i]))
952 return i;
953
954 if (DBG) {
955 // if we ever get here, we should probably add the
956 // value to WifiConfiguration to reflect that it's
957 // supported by the WPA supplicant
958 Log.w(TAG, "Failed to look-up a string: " + string);
959 }
960
961 return -1;
962 }
963
964 /**
965 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
966 * @param netId the integer that identifies the network configuration
967 * to the supplicant
968 * @return {@code true} if the operation succeeded
969 */
970 public boolean removeNetwork(int netId) {
971 enforceChangePermission();
972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 return mWifiStateTracker.removeNetwork(netId);
974 }
975
976 /**
977 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
978 * @param netId the integer that identifies the network configuration
979 * to the supplicant
980 * @param disableOthers if true, disable all other networks.
981 * @return {@code true} if the operation succeeded
982 */
983 public boolean enableNetwork(int netId, boolean disableOthers) {
984 enforceChangePermission();
985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -0400987 String ifname = mWifiStateTracker.getInterfaceName();
988 NetworkUtils.enableInterface(ifname);
989 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
990 if (!result) {
991 NetworkUtils.disableInterface(ifname);
992 }
993 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995 }
996
997 /**
998 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
999 * @param netId the integer that identifies the network configuration
1000 * to the supplicant
1001 * @return {@code true} if the operation succeeded
1002 */
1003 public boolean disableNetwork(int netId) {
1004 enforceChangePermission();
1005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 synchronized (mWifiStateTracker) {
1007 return WifiNative.disableNetworkCommand(netId);
1008 }
1009 }
1010
1011 /**
1012 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1013 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1014 */
1015 public WifiInfo getConnectionInfo() {
1016 enforceAccessPermission();
1017 /*
1018 * Make sure we have the latest information, by sending
1019 * a status request to the supplicant.
1020 */
1021 return mWifiStateTracker.requestConnectionInfo();
1022 }
1023
1024 /**
1025 * Return the results of the most recent access point scan, in the form of
1026 * a list of {@link ScanResult} objects.
1027 * @return the list of results
1028 */
1029 public List<ScanResult> getScanResults() {
1030 enforceAccessPermission();
1031 String reply;
1032 synchronized (mWifiStateTracker) {
1033 reply = WifiNative.scanResultsCommand();
1034 }
1035 if (reply == null) {
1036 return null;
1037 }
1038
1039 List<ScanResult> scanList = new ArrayList<ScanResult>();
1040
1041 int lineCount = 0;
1042
1043 int replyLen = reply.length();
1044 // Parse the result string, keeping in mind that the last line does
1045 // not end with a newline.
1046 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1047 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1048 ++lineCount;
1049 /*
1050 * Skip the first line, which is a header
1051 */
1052 if (lineCount == 1) {
1053 lineBeg = lineEnd + 1;
1054 continue;
1055 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001056 if (lineEnd > lineBeg) {
1057 String line = reply.substring(lineBeg, lineEnd);
1058 ScanResult scanResult = parseScanResult(line);
1059 if (scanResult != null) {
1060 scanList.add(scanResult);
1061 } else if (DBG) {
1062 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
1064 }
1065 lineBeg = lineEnd + 1;
1066 }
1067 }
1068 mWifiStateTracker.setScanResultsList(scanList);
1069 return scanList;
1070 }
1071
1072 /**
1073 * Parse the scan result line passed to us by wpa_supplicant (helper).
1074 * @param line the line to parse
1075 * @return the {@link ScanResult} object
1076 */
1077 private ScanResult parseScanResult(String line) {
1078 ScanResult scanResult = null;
1079 if (line != null) {
1080 /*
1081 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1082 * must synchronized here!
1083 */
1084 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001085 String[] result = scanResultPattern.split(line);
1086 if (3 <= result.length && result.length <= 5) {
1087 String bssid = result[0];
1088 // bssid | frequency | level | flags | ssid
1089 int frequency;
1090 int level;
1091 try {
1092 frequency = Integer.parseInt(result[1]);
1093 level = Integer.parseInt(result[2]);
1094 /* some implementations avoid negative values by adding 256
1095 * so we need to adjust for that here.
1096 */
1097 if (level > 0) level -= 256;
1098 } catch (NumberFormatException e) {
1099 frequency = 0;
1100 level = 0;
1101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102
Mike Lockwood1a645052009-06-25 13:01:12 -04001103 /*
1104 * The formatting of the results returned by
1105 * wpa_supplicant is intended to make the fields
1106 * line up nicely when printed,
1107 * not to make them easy to parse. So we have to
1108 * apply some heuristics to figure out which field
1109 * is the SSID and which field is the flags.
1110 */
1111 String ssid;
1112 String flags;
1113 if (result.length == 4) {
1114 if (result[3].charAt(0) == '[') {
1115 flags = result[3];
1116 ssid = "";
1117 } else {
1118 flags = "";
1119 ssid = result[3];
1120 }
1121 } else if (result.length == 5) {
1122 flags = result[3];
1123 ssid = result[4];
1124 } else {
1125 // Here, we must have 3 fields: no flags and ssid
1126 // set
1127 flags = "";
1128 ssid = "";
1129 }
1130
Mike Lockwood00717e22009-08-17 10:09:36 -04001131 // bssid + ssid is the hash key
1132 String key = bssid + ssid;
1133 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001134 if (scanResult != null) {
1135 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001136 scanResult.SSID = ssid;
1137 scanResult.capabilities = flags;
1138 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001139 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 // Do not add scan results that have no SSID set
1141 if (0 < ssid.trim().length()) {
1142 scanResult =
1143 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001144 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001145 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001148 } else {
1149 Log.w(TAG, "Misformatted scan result text with " +
1150 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152 }
1153 }
1154
1155 return scanResult;
1156 }
1157
1158 /**
1159 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1160 * and construct a {@code WifiConfiguration} that describes the encryption,
1161 * key management, and authenticaion capabilities of the access point.
1162 * @param flags the string returned by wpa_supplicant
1163 * @return the {@link WifiConfiguration} object, filled in
1164 */
1165 WifiConfiguration parseScanFlags(String flags) {
1166 WifiConfiguration config = new WifiConfiguration();
1167
1168 if (flags.length() == 0) {
1169 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1170 }
1171 // ... to be implemented
1172 return config;
1173 }
1174
1175 /**
1176 * Tell the supplicant to persist the current list of configured networks.
1177 * @return {@code true} if the operation succeeded
1178 */
1179 public boolean saveConfiguration() {
1180 boolean result;
1181 enforceChangePermission();
1182 synchronized (mWifiStateTracker) {
1183 result = WifiNative.saveConfigCommand();
1184 if (result && mNeedReconfig) {
1185 mNeedReconfig = false;
1186 result = WifiNative.reloadConfigCommand();
1187
1188 if (result) {
1189 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1190 mContext.sendBroadcast(intent);
1191 }
1192 }
1193 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001194 // Inform the backup manager about a data change
1195 IBackupManager ibm = IBackupManager.Stub.asInterface(
1196 ServiceManager.getService(Context.BACKUP_SERVICE));
1197 if (ibm != null) {
1198 try {
1199 ibm.dataChanged("com.android.providers.settings");
1200 } catch (Exception e) {
1201 // Try again later
1202 }
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 return result;
1205 }
1206
1207 /**
1208 * Set the number of radio frequency channels that are allowed to be used
1209 * in the current regulatory domain. This method should be used only
1210 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001211 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 * persisted as a Secure setting.
1213 * @param numChannels the number of allowed channels. Must be greater than 0
1214 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001215 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1217 * {@code numChannels} is outside the valid range.
1218 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001219 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1220 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1221 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 enforceChangePermission();
1223 /*
1224 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1225 * but if Wi-Fi isn't currently enabled, that's not possible, and
1226 * we want to persist the setting anyway,so that it will take
1227 * effect when Wi-Fi does become enabled.
1228 */
1229 boolean found = false;
1230 for (int validChan : sValidRegulatoryChannelCounts) {
1231 if (validChan == numChannels) {
1232 found = true;
1233 break;
1234 }
1235 }
1236 if (!found) {
1237 return false;
1238 }
1239
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001240 if (persist) {
1241 Settings.Secure.putInt(mContext.getContentResolver(),
1242 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1243 numChannels);
1244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mWifiStateTracker.setNumAllowedChannels(numChannels);
1246 return true;
1247 }
1248
1249 /**
1250 * Return the number of frequency channels that are allowed
1251 * to be used in the current regulatory domain.
1252 * @return the number of allowed channels, or {@code -1} if an error occurs
1253 */
1254 public int getNumAllowedChannels() {
1255 int numChannels;
1256
1257 enforceAccessPermission();
1258 synchronized (mWifiStateTracker) {
1259 /*
1260 * If we can't get the value from the driver (e.g., because
1261 * Wi-Fi is not currently enabled), get the value from
1262 * Settings.
1263 */
1264 numChannels = WifiNative.getNumAllowedChannelsCommand();
1265 if (numChannels < 0) {
1266 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1267 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1268 -1);
1269 }
1270 }
1271 return numChannels;
1272 }
1273
1274 /**
1275 * Return the list of valid values for the number of allowed radio channels
1276 * for various regulatory domains.
1277 * @return the list of channel counts
1278 */
1279 public int[] getValidChannelCounts() {
1280 enforceAccessPermission();
1281 return sValidRegulatoryChannelCounts;
1282 }
1283
1284 /**
1285 * Return the DHCP-assigned addresses from the last successful DHCP request,
1286 * if any.
1287 * @return the DHCP information
1288 */
1289 public DhcpInfo getDhcpInfo() {
1290 enforceAccessPermission();
1291 return mWifiStateTracker.getDhcpInfo();
1292 }
1293
1294 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1295 @Override
1296 public void onReceive(Context context, Intent intent) {
1297 String action = intent.getAction();
1298
1299 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1300 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1301 int stayAwakeConditions =
1302 Settings.System.getInt(mContext.getContentResolver(),
1303 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1304 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001305 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 mAlarmManager.cancel(mIdleIntent);
1307 mDeviceIdle = false;
1308 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001309 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001311 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001313 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 /*
1315 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1316 * AND the "stay on while plugged in" setting doesn't match the
1317 * current power conditions (i.e, not plugged in, plugged in to USB,
1318 * or plugged in to AC).
1319 */
1320 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001321 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1322 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1323 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001324 mDeviceIdle = true;
1325 updateWifiState();
1326 } else {
1327 long triggerTime = System.currentTimeMillis() + idleMillis;
1328 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1329 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332 /* we can return now -- there's nothing to do until we get the idle intent back */
1333 return;
1334 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001335 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 mDeviceIdle = true;
1337 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1338 /*
1339 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1340 * AND we are transitioning from a state in which the device was supposed
1341 * to stay awake to a state in which it is not supposed to stay awake.
1342 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1343 * the already-set timer.
1344 */
1345 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001346 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1348 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1349 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001350 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1352 mPluggedType = pluggedType;
1353 return;
1354 }
1355 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001356 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001357 boolean isBluetoothPlaying =
1358 intent.getIntExtra(
Nick Pelly005b2282009-09-10 10:21:56 -07001359 BluetoothA2dp.EXTRA_SINK_STATE,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001360 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1361 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 } else {
1363 return;
1364 }
1365
1366 updateWifiState();
1367 }
1368
1369 /**
1370 * Determines whether the Wi-Fi chipset should stay awake or be put to
1371 * sleep. Looks at the setting for the sleep policy and the current
1372 * conditions.
1373 *
1374 * @see #shouldDeviceStayAwake(int, int)
1375 */
1376 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1377 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1378 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1379
1380 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1381 // Never sleep
1382 return true;
1383 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1384 (pluggedType != 0)) {
1385 // Never sleep while plugged, and we're plugged
1386 return true;
1387 } else {
1388 // Default
1389 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1390 }
1391 }
1392
1393 /**
1394 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1395 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1396 * of {@code 0} isn't really a plugged type, but rather an indication that the
1397 * device isn't plugged in at all, there is no bit value corresponding to a
1398 * {@code pluggedType} value of {@code 0}. That is why we shift by
1399 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1400 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1401 * keep the device (and hence Wi-Fi) awake.
1402 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1403 * being made
1404 * @return {@code true} if {@code pluggedType} indicates that the device is
1405 * supposed to stay awake, {@code false} otherwise.
1406 */
1407 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1408 return (stayAwakeConditions & pluggedType) != 0;
1409 }
1410 };
1411
Dianne Hackborn617f8772009-03-31 15:04:46 -07001412 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 Message msg = Message.obtain(mWifiHandler,
1414 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001415 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 msg.sendToTarget();
1417 }
1418
1419 private void sendStartMessage(boolean scanOnlyMode) {
1420 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1421 }
1422
1423 private void updateWifiState() {
1424 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001425 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 boolean lockHeld = mLocks.hasLocks();
1427 int strongestLockMode;
1428 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1429 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1430 if (mDeviceIdle && lockHeld) {
1431 strongestLockMode = mLocks.getStrongestLockMode();
1432 } else {
1433 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1434 }
1435
1436 synchronized (mWifiHandler) {
1437 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1438 return;
1439 }
1440 if (wifiShouldBeEnabled) {
1441 if (wifiShouldBeStarted) {
1442 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001443 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 sWakeLock.acquire();
1445 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1446 } else {
1447 int wakeLockTimeout =
1448 Settings.Secure.getInt(
1449 mContext.getContentResolver(),
1450 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1451 DEFAULT_WAKELOCK_TIMEOUT);
1452 /*
1453 * The following wakelock is held in order to ensure
1454 * that the connectivity manager has time to fail over
1455 * to the mobile data network. The connectivity manager
1456 * releases it once mobile data connectivity has been
1457 * established. If connectivity cannot be established,
1458 * the wakelock is released after wakeLockTimeout
1459 * milliseconds have elapsed.
1460 */
1461 sDriverStopWakeLock.acquire();
1462 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1463 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1464 }
1465 } else {
1466 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001467 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
1469 }
1470 }
1471
1472 private void registerForBroadcasts() {
1473 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1475 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1476 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1477 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001478 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 mContext.registerReceiver(mReceiver, intentFilter);
1480 }
1481
1482 private boolean isAirplaneSensitive() {
1483 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1484 Settings.System.AIRPLANE_MODE_RADIOS);
1485 return airplaneModeRadios == null
1486 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1487 }
1488
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001489 private boolean isAirplaneToggleable() {
1490 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1491 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1492 return toggleableRadios != null
1493 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1494 }
1495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 /**
1497 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1498 * currently on.
1499 * @return {@code true} if airplane mode is on.
1500 */
1501 private boolean isAirplaneModeOn() {
1502 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1503 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1504 }
1505
1506 /**
1507 * Handler that allows posting to the WifiThread.
1508 */
1509 private class WifiHandler extends Handler {
1510 public WifiHandler(Looper looper) {
1511 super(looper);
1512 }
1513
1514 @Override
1515 public void handleMessage(Message msg) {
1516 switch (msg.what) {
1517
1518 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001519 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 sWakeLock.release();
1521 break;
1522
1523 case MESSAGE_START_WIFI:
1524 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1525 mWifiStateTracker.restart();
1526 sWakeLock.release();
1527 break;
1528
1529 case MESSAGE_DISABLE_WIFI:
1530 // a non-zero msg.arg1 value means the "enabled" setting
1531 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001532 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 sWakeLock.release();
1534 break;
1535
1536 case MESSAGE_STOP_WIFI:
1537 mWifiStateTracker.disconnectAndStop();
1538 // don't release wakelock
1539 break;
1540
1541 case MESSAGE_RELEASE_WAKELOCK:
1542 synchronized (sDriverStopWakeLock) {
1543 if (sDriverStopWakeLock.isHeld()) {
1544 sDriverStopWakeLock.release();
1545 }
1546 }
1547 break;
1548 }
1549 }
1550 }
1551
1552 @Override
1553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1554 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1555 != PackageManager.PERMISSION_GRANTED) {
1556 pw.println("Permission Denial: can't dump WifiService from from pid="
1557 + Binder.getCallingPid()
1558 + ", uid=" + Binder.getCallingUid());
1559 return;
1560 }
1561 pw.println("Wi-Fi is " + stateName(mWifiState));
1562 pw.println("Stay-awake conditions: " +
1563 Settings.System.getInt(mContext.getContentResolver(),
1564 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1565 pw.println();
1566
1567 pw.println("Internal state:");
1568 pw.println(mWifiStateTracker);
1569 pw.println();
1570 pw.println("Latest scan results:");
1571 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1572 if (scanResults != null && scanResults.size() != 0) {
1573 pw.println(" BSSID Frequency RSSI Flags SSID");
1574 for (ScanResult r : scanResults) {
1575 pw.printf(" %17s %9d %5d %-16s %s%n",
1576 r.BSSID,
1577 r.frequency,
1578 r.level,
1579 r.capabilities,
1580 r.SSID == null ? "" : r.SSID);
1581 }
1582 }
1583 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001584 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1585 mScanLocksAcquired + " scan");
1586 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1587 mScanLocksReleased + " scan");
1588 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 pw.println("Locks held:");
1590 mLocks.dump(pw);
1591 }
1592
1593 private static String stateName(int wifiState) {
1594 switch (wifiState) {
1595 case WIFI_STATE_DISABLING:
1596 return "disabling";
1597 case WIFI_STATE_DISABLED:
1598 return "disabled";
1599 case WIFI_STATE_ENABLING:
1600 return "enabling";
1601 case WIFI_STATE_ENABLED:
1602 return "enabled";
1603 case WIFI_STATE_UNKNOWN:
1604 return "unknown state";
1605 default:
1606 return "[invalid state]";
1607 }
1608 }
1609
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001610 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001612 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
1615 public void binderDied() {
1616 synchronized (mLocks) {
1617 releaseWifiLockLocked(mBinder);
1618 }
1619 }
1620
1621 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001622 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 }
1625
1626 private class LockList {
1627 private List<WifiLock> mList;
1628
1629 private LockList() {
1630 mList = new ArrayList<WifiLock>();
1631 }
1632
1633 private synchronized boolean hasLocks() {
1634 return !mList.isEmpty();
1635 }
1636
1637 private synchronized int getStrongestLockMode() {
1638 if (mList.isEmpty()) {
1639 return WifiManager.WIFI_MODE_FULL;
1640 }
1641 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001642 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 return WifiManager.WIFI_MODE_FULL;
1644 }
1645 }
1646 return WifiManager.WIFI_MODE_SCAN_ONLY;
1647 }
1648
1649 private void addLock(WifiLock lock) {
1650 if (findLockByBinder(lock.mBinder) < 0) {
1651 mList.add(lock);
1652 }
1653 }
1654
1655 private WifiLock removeLock(IBinder binder) {
1656 int index = findLockByBinder(binder);
1657 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001658 WifiLock ret = mList.remove(index);
1659 ret.unlinkDeathRecipient();
1660 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 } else {
1662 return null;
1663 }
1664 }
1665
1666 private int findLockByBinder(IBinder binder) {
1667 int size = mList.size();
1668 for (int i = size - 1; i >= 0; i--)
1669 if (mList.get(i).mBinder == binder)
1670 return i;
1671 return -1;
1672 }
1673
1674 private void dump(PrintWriter pw) {
1675 for (WifiLock l : mList) {
1676 pw.print(" ");
1677 pw.println(l);
1678 }
1679 }
1680 }
1681
1682 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1684 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1685 return false;
1686 }
1687 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1688 synchronized (mLocks) {
1689 return acquireWifiLockLocked(wifiLock);
1690 }
1691 }
1692
1693 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1694 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001695
1696 int uid = Binder.getCallingUid();
1697 long ident = Binder.clearCallingIdentity();
1698 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001699 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001700 case WifiManager.WIFI_MODE_FULL:
1701 ++mFullLocksAcquired;
1702 mBatteryStats.noteFullWifiLockAcquired(uid);
1703 break;
1704 case WifiManager.WIFI_MODE_SCAN_ONLY:
1705 ++mScanLocksAcquired;
1706 mBatteryStats.noteScanWifiLockAcquired(uid);
1707 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001708 }
1709 } catch (RemoteException e) {
1710 } finally {
1711 Binder.restoreCallingIdentity(ident);
1712 }
1713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 updateWifiState();
1715 return true;
1716 }
1717
1718 public boolean releaseWifiLock(IBinder lock) {
1719 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1720 synchronized (mLocks) {
1721 return releaseWifiLockLocked(lock);
1722 }
1723 }
1724
1725 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001726 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001727
1728 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001729 hadLock = (wifiLock != null);
1730
1731 if (hadLock) {
1732 int uid = Binder.getCallingUid();
1733 long ident = Binder.clearCallingIdentity();
1734 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001735 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001736 case WifiManager.WIFI_MODE_FULL:
1737 ++mFullLocksReleased;
1738 mBatteryStats.noteFullWifiLockReleased(uid);
1739 break;
1740 case WifiManager.WIFI_MODE_SCAN_ONLY:
1741 ++mScanLocksReleased;
1742 mBatteryStats.noteScanWifiLockReleased(uid);
1743 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001744 }
1745 } catch (RemoteException e) {
1746 } finally {
1747 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001748 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001749 }
1750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001752 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001754
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001755 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001756 implements IBinder.DeathRecipient {
1757 String mTag;
1758 int mMode;
1759 IBinder mBinder;
1760
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001761 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001762 super();
1763 mTag = tag;
1764 mMode = mode;
1765 mBinder = binder;
1766 try {
1767 mBinder.linkToDeath(this, 0);
1768 } catch (RemoteException e) {
1769 binderDied();
1770 }
1771 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001772
1773 void unlinkDeathRecipient() {
1774 mBinder.unlinkToDeath(this, 0);
1775 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001776 }
1777
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001778 private class Multicaster extends DeathRecipient {
1779 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001780 super(Binder.getCallingUid(), tag, binder);
1781 }
1782
1783 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001784 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001785 synchronized (mMulticasters) {
1786 int i = mMulticasters.indexOf(this);
1787 if (i != -1) {
1788 removeMulticasterLocked(i, mMode);
1789 }
1790 }
1791 }
1792
1793 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001794 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001795 }
1796
1797 public int getUid() {
1798 return mMode;
1799 }
1800 }
1801
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001802 public void acquireMulticastLock(IBinder binder, String tag) {
1803 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001804
1805 synchronized (mMulticasters) {
1806 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001807 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001808 // Note that we could call stopPacketFiltering only when
1809 // our new size == 1 (first call), but this function won't
1810 // be called often and by making the stopPacket call each
1811 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001812 synchronized (mWifiStateTracker) {
1813 WifiNative.stopPacketFiltering();
1814 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001815 }
1816
1817 int uid = Binder.getCallingUid();
1818 Long ident = Binder.clearCallingIdentity();
1819 try {
1820 mBatteryStats.noteWifiMulticastEnabled(uid);
1821 } catch (RemoteException e) {
1822 } finally {
1823 Binder.restoreCallingIdentity(ident);
1824 }
1825 }
1826
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001827 public void releaseMulticastLock() {
1828 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001829
1830 int uid = Binder.getCallingUid();
1831 synchronized (mMulticasters) {
1832 mMulticastDisabled++;
1833 int size = mMulticasters.size();
1834 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001835 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001836 if ((m != null) && (m.getUid() == uid)) {
1837 removeMulticasterLocked(i, uid);
1838 }
1839 }
1840 }
1841 }
1842
1843 private void removeMulticasterLocked(int i, int uid)
1844 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001845 Multicaster removed = mMulticasters.remove(i);
1846 if (removed != null) {
1847 removed.unlinkDeathRecipient();
1848 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001849 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001850 synchronized (mWifiStateTracker) {
1851 WifiNative.startPacketFiltering();
1852 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001853 }
1854
1855 Long ident = Binder.clearCallingIdentity();
1856 try {
1857 mBatteryStats.noteWifiMulticastDisabled(uid);
1858 } catch (RemoteException e) {
1859 } finally {
1860 Binder.restoreCallingIdentity(ident);
1861 }
1862 }
1863
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001864 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001865 enforceAccessPermission();
1866
1867 synchronized (mMulticasters) {
1868 return (mMulticasters.size() > 0);
1869 }
1870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871}