blob: 55b7a30a7b1652cc964b86aaf986e904aa056d1b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.app.AlarmManager;
26import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070027import android.bluetooth.BluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
34import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
37import android.net.wifi.WifiNative;
38import android.net.wifi.WifiStateTracker;
39import android.net.wifi.ScanResult;
40import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070041import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.NetworkStateTracker;
43import android.net.DhcpInfo;
44import android.os.Binder;
45import android.os.Handler;
46import android.os.HandlerThread;
47import android.os.IBinder;
48import android.os.Looper;
49import android.os.Message;
50import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070051import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070053import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings;
55import android.util.Log;
56import android.text.TextUtils;
57
58import java.util.ArrayList;
59import java.util.BitSet;
60import java.util.HashMap;
61import java.util.LinkedHashMap;
62import java.util.List;
63import java.util.Map;
64import java.util.regex.Pattern;
65import java.io.FileDescriptor;
66import java.io.PrintWriter;
67
The Android Open Source Project10592532009-03-18 17:39:46 -070068import com.android.internal.app.IBatteryStats;
Amith Yamasani47873e52009-07-02 12:05:32 -070069import android.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070070import com.android.server.am.BatteryStatsService;
71
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072/**
73 * WifiService handles remote WiFi operation requests by implementing
74 * the IWifiManager interface. It also creates a WifiMonitor to listen
75 * for Wifi-related events.
76 *
77 * @hide
78 */
79public class WifiService extends IWifiManager.Stub {
80 private static final String TAG = "WifiService";
81 private static final boolean DBG = false;
82 private static final Pattern scanResultPattern = Pattern.compile("\t+");
83 private final WifiStateTracker mWifiStateTracker;
84
85 private Context mContext;
86 private int mWifiState;
87
88 private AlarmManager mAlarmManager;
89 private PendingIntent mIdleIntent;
90 private static final int IDLE_REQUEST = 0;
91 private boolean mScreenOff;
92 private boolean mDeviceIdle;
93 private int mPluggedType;
94
95 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070096 // some wifi lock statistics
97 private int mFullLocksAcquired;
98 private int mFullLocksReleased;
99 private int mScanLocksAcquired;
100 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700101
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700102 private final List<Multicaster> mMulticasters =
103 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700104 private int mMulticastEnabled;
105 private int mMulticastDisabled;
106
The Android Open Source Project10592532009-03-18 17:39:46 -0700107 private final IBatteryStats mBatteryStats;
108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 /**
110 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
111 * Settings.Gservices value is not present. This timeout value is chosen as
112 * the approximate point at which the battery drain caused by Wi-Fi
113 * being enabled but not active exceeds the battery drain caused by
114 * re-establishing a connection to the mobile data network.
115 */
116 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
117
118 private static final String WAKELOCK_TAG = "WifiService";
119
120 /**
121 * The maximum amount of time to hold the wake lock after a disconnect
122 * caused by stopping the driver. Establishing an EDGE connection has been
123 * observed to take about 5 seconds under normal circumstances. This
124 * provides a bit of extra margin.
125 * <p>
126 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
127 * This is the default value if a Settings.Secure value is not present.
128 */
129 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
130
131 // Wake lock used by driver-stop operation
132 private static PowerManager.WakeLock sDriverStopWakeLock;
133 // Wake lock used by other operations
134 private static PowerManager.WakeLock sWakeLock;
135
136 private static final int MESSAGE_ENABLE_WIFI = 0;
137 private static final int MESSAGE_DISABLE_WIFI = 1;
138 private static final int MESSAGE_STOP_WIFI = 2;
139 private static final int MESSAGE_START_WIFI = 3;
140 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
141
142 private final WifiHandler mWifiHandler;
143
144 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 * Cache of scan results objects (size is somewhat arbitrary)
146 */
147 private static final int SCAN_RESULT_CACHE_SIZE = 80;
148 private final LinkedHashMap<String, ScanResult> mScanResultCache;
149
150 /*
151 * Character buffer used to parse scan results (optimization)
152 */
153 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 private boolean mNeedReconfig;
155
Dianne Hackborn617f8772009-03-31 15:04:46 -0700156 /*
157 * Last UID that asked to enable WIFI.
158 */
159 private int mLastEnableUid = Process.myUid();
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 /**
162 * Number of allowed radio frequency channels in various regulatory domains.
163 * This list is sufficient for 802.11b/g networks (2.4GHz range).
164 */
165 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
166
167 private static final String ACTION_DEVICE_IDLE =
168 "com.android.server.WifiManager.action.DEVICE_IDLE";
169
170 WifiService(Context context, WifiStateTracker tracker) {
171 mContext = context;
172 mWifiStateTracker = tracker;
The Android Open Source Project10592532009-03-18 17:39:46 -0700173 mBatteryStats = BatteryStatsService.getService();
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 mScanResultCache = new LinkedHashMap<String, ScanResult>(
176 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
177 /*
178 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
179 * elements
180 */
181 public boolean removeEldestEntry(Map.Entry eldest) {
182 return SCAN_RESULT_CACHE_SIZE < this.size();
183 }
184 };
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 HandlerThread wifiThread = new HandlerThread("WifiService");
187 wifiThread.start();
188 mWifiHandler = new WifiHandler(wifiThread.getLooper());
189
190 mWifiState = WIFI_STATE_DISABLED;
191 boolean wifiEnabled = getPersistedWifiEnabled();
192
193 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
194 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
195 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
196
197 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
198 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
199 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
200 mWifiStateTracker.setReleaseWakeLockCallback(
201 new Runnable() {
202 public void run() {
203 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
204 synchronized (sDriverStopWakeLock) {
205 if (sDriverStopWakeLock.isHeld()) {
206 sDriverStopWakeLock.release();
207 }
208 }
209 }
210 }
211 );
212
213 Log.i(TAG, "WifiService starting up with Wi-Fi " +
214 (wifiEnabled ? "enabled" : "disabled"));
215
216 mContext.registerReceiver(
217 new BroadcastReceiver() {
218 @Override
219 public void onReceive(Context context, Intent intent) {
220 updateWifiState();
221 }
222 },
223 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
224
Dianne Hackborn617f8772009-03-31 15:04:46 -0700225 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 }
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private boolean getPersistedWifiEnabled() {
229 final ContentResolver cr = mContext.getContentResolver();
230 try {
231 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
232 } catch (Settings.SettingNotFoundException e) {
233 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
234 return false;
235 }
236 }
237
238 private void persistWifiEnabled(boolean enabled) {
239 final ContentResolver cr = mContext.getContentResolver();
240 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
241 }
242
243 NetworkStateTracker getNetworkStateTracker() {
244 return mWifiStateTracker;
245 }
246
247 /**
248 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
249 * @return {@code true} if the operation succeeds
250 */
251 public boolean pingSupplicant() {
252 enforceChangePermission();
253 synchronized (mWifiStateTracker) {
254 return WifiNative.pingCommand();
255 }
256 }
257
258 /**
259 * see {@link android.net.wifi.WifiManager#startScan()}
260 * @return {@code true} if the operation succeeds
261 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400262 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 enforceChangePermission();
264 synchronized (mWifiStateTracker) {
265 switch (mWifiStateTracker.getSupplicantState()) {
266 case DISCONNECTED:
267 case INACTIVE:
268 case SCANNING:
269 case DORMANT:
270 break;
271 default:
272 WifiNative.setScanResultHandlingCommand(
273 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
274 break;
275 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400276 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278 }
279
280 /**
281 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
282 * @param enable {@code true} to enable, {@code false} to disable.
283 * @return {@code true} if the enable/disable operation was
284 * started or is already in the queue.
285 */
286 public boolean setWifiEnabled(boolean enable) {
287 enforceChangePermission();
288 if (mWifiHandler == null) return false;
289
290 synchronized (mWifiHandler) {
291 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700292 mLastEnableUid = Binder.getCallingUid();
293 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295
296 return true;
297 }
298
299 /**
300 * Enables/disables Wi-Fi synchronously.
301 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
302 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700303 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * @return {@code true} if the operation succeeds (or if the existing state
305 * is the same as the requested state)
306 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700307 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
309
310 if (mWifiState == eventualWifiState) {
311 return true;
312 }
313 if (enable && isAirplaneModeOn()) {
314 return false;
315 }
316
Dianne Hackborn617f8772009-03-31 15:04:46 -0700317 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318
319 if (enable) {
320 if (!WifiNative.loadDriver()) {
321 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700322 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 return false;
324 }
325 if (!WifiNative.startSupplicant()) {
326 WifiNative.unloadDriver();
327 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700328 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 return false;
330 }
331 registerForBroadcasts();
332 mWifiStateTracker.startEventLoop();
333 } else {
334
335 mContext.unregisterReceiver(mReceiver);
336 // Remove notification (it will no-op if it isn't visible)
337 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
338
339 boolean failedToStopSupplicantOrUnloadDriver = false;
340 if (!WifiNative.stopSupplicant()) {
341 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700342 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 failedToStopSupplicantOrUnloadDriver = true;
344 }
345
346 // We must reset the interface before we unload the driver
347 mWifiStateTracker.resetInterface();
348
349 if (!WifiNative.unloadDriver()) {
350 Log.e(TAG, "Failed to unload Wi-Fi driver.");
351 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700352 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 failedToStopSupplicantOrUnloadDriver = true;
354 }
355 }
356 if (failedToStopSupplicantOrUnloadDriver) {
357 return false;
358 }
359 }
360
361 // Success!
362
363 if (persist) {
364 persistWifiEnabled(enable);
365 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700366 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367
368 /*
Mike Lockwood622f82a2009-07-09 23:39:01 -0400369 * Initialize the number of allowed radio channels if Wi-Fi is being turned on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 */
371 if (enable) {
372 mWifiStateTracker.setNumAllowedChannels();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 }
374
375 return true;
376 }
377
Dianne Hackborn617f8772009-03-31 15:04:46 -0700378 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 final int previousWifiState = mWifiState;
380
The Android Open Source Project10592532009-03-18 17:39:46 -0700381 long ident = Binder.clearCallingIdentity();
382 try {
383 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700384 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700385 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700386 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700387 }
388 } catch (RemoteException e) {
389 } finally {
390 Binder.restoreCallingIdentity(ident);
391 }
392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 // Update state
394 mWifiState = wifiState;
395
396 // Broadcast
397 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
398 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
399 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
400 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
401 mContext.sendStickyBroadcast(intent);
402 }
403
404 private void enforceAccessPermission() {
405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
406 "WifiService");
407 }
408
409 private void enforceChangePermission() {
410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
411 "WifiService");
412
413 }
414
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700415 private void enforceMulticastChangePermission() {
416 mContext.enforceCallingOrSelfPermission(
417 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
418 "WifiService");
419 }
420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 /**
422 * see {@link WifiManager#getWifiState()}
423 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
424 * {@link WifiManager#WIFI_STATE_DISABLING},
425 * {@link WifiManager#WIFI_STATE_ENABLED},
426 * {@link WifiManager#WIFI_STATE_ENABLING},
427 * {@link WifiManager#WIFI_STATE_UNKNOWN}
428 */
429 public int getWifiEnabledState() {
430 enforceAccessPermission();
431 return mWifiState;
432 }
433
434 /**
435 * see {@link android.net.wifi.WifiManager#disconnect()}
436 * @return {@code true} if the operation succeeds
437 */
438 public boolean disconnect() {
439 enforceChangePermission();
440 synchronized (mWifiStateTracker) {
441 return WifiNative.disconnectCommand();
442 }
443 }
444
445 /**
446 * see {@link android.net.wifi.WifiManager#reconnect()}
447 * @return {@code true} if the operation succeeds
448 */
449 public boolean reconnect() {
450 enforceChangePermission();
451 synchronized (mWifiStateTracker) {
452 return WifiNative.reconnectCommand();
453 }
454 }
455
456 /**
457 * see {@link android.net.wifi.WifiManager#reassociate()}
458 * @return {@code true} if the operation succeeds
459 */
460 public boolean reassociate() {
461 enforceChangePermission();
462 synchronized (mWifiStateTracker) {
463 return WifiNative.reassociateCommand();
464 }
465 }
466
467 /**
468 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
469 * @return the list of configured networks
470 */
471 public List<WifiConfiguration> getConfiguredNetworks() {
472 enforceAccessPermission();
473 String listStr;
474 /*
475 * We don't cache the list, because we want to allow
476 * for the possibility that the configuration file
477 * has been modified through some external means,
478 * such as the wpa_cli command line program.
479 */
480 synchronized (mWifiStateTracker) {
481 listStr = WifiNative.listNetworksCommand();
482 }
483 List<WifiConfiguration> networks =
484 new ArrayList<WifiConfiguration>();
485 if (listStr == null)
486 return networks;
487
488 String[] lines = listStr.split("\n");
489 // Skip the first line, which is a header
490 for (int i = 1; i < lines.length; i++) {
491 String[] result = lines[i].split("\t");
492 // network-id | ssid | bssid | flags
493 WifiConfiguration config = new WifiConfiguration();
494 try {
495 config.networkId = Integer.parseInt(result[0]);
496 } catch(NumberFormatException e) {
497 continue;
498 }
499 if (result.length > 3) {
500 if (result[3].indexOf("[CURRENT]") != -1)
501 config.status = WifiConfiguration.Status.CURRENT;
502 else if (result[3].indexOf("[DISABLED]") != -1)
503 config.status = WifiConfiguration.Status.DISABLED;
504 else
505 config.status = WifiConfiguration.Status.ENABLED;
506 } else
507 config.status = WifiConfiguration.Status.ENABLED;
508 synchronized (mWifiStateTracker) {
509 readNetworkVariables(config);
510 }
511 networks.add(config);
512 }
513
514 return networks;
515 }
516
517 /**
518 * Read the variables from the supplicant daemon that are needed to
519 * fill in the WifiConfiguration object.
520 * <p/>
521 * The caller must hold the synchronization monitor.
522 * @param config the {@link WifiConfiguration} object to be filled in.
523 */
524 private static void readNetworkVariables(WifiConfiguration config) {
525
526 int netId = config.networkId;
527 if (netId < 0)
528 return;
529
530 /*
531 * TODO: maybe should have a native method that takes an array of
532 * variable names and returns an array of values. But we'd still
533 * be doing a round trip to the supplicant daemon for each variable.
534 */
535 String value;
536
537 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
538 if (!TextUtils.isEmpty(value)) {
539 config.SSID = value;
540 } else {
541 config.SSID = null;
542 }
543
544 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
545 if (!TextUtils.isEmpty(value)) {
546 config.BSSID = value;
547 } else {
548 config.BSSID = null;
549 }
550
551 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
552 config.priority = -1;
553 if (!TextUtils.isEmpty(value)) {
554 try {
555 config.priority = Integer.parseInt(value);
556 } catch (NumberFormatException ignore) {
557 }
558 }
559
560 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
561 config.hiddenSSID = false;
562 if (!TextUtils.isEmpty(value)) {
563 try {
564 config.hiddenSSID = Integer.parseInt(value) != 0;
565 } catch (NumberFormatException ignore) {
566 }
567 }
568
569 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
570 config.wepTxKeyIndex = -1;
571 if (!TextUtils.isEmpty(value)) {
572 try {
573 config.wepTxKeyIndex = Integer.parseInt(value);
574 } catch (NumberFormatException ignore) {
575 }
576 }
577
578 /*
579 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
580 * just a "*" if the key is set, or the null string otherwise.
581 */
582 for (int i = 0; i < 4; i++) {
583 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
584 if (!TextUtils.isEmpty(value)) {
585 config.wepKeys[i] = value;
586 } else {
587 config.wepKeys[i] = null;
588 }
589 }
590
591 /*
592 * Get the private shared key. Note that the actual keys are not passed back,
593 * just a "*" if the key is set, or the null string otherwise.
594 */
595 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
596 if (!TextUtils.isEmpty(value)) {
597 config.preSharedKey = value;
598 } else {
599 config.preSharedKey = null;
600 }
601
602 value = WifiNative.getNetworkVariableCommand(config.networkId,
603 WifiConfiguration.Protocol.varName);
604 if (!TextUtils.isEmpty(value)) {
605 String vals[] = value.split(" ");
606 for (String val : vals) {
607 int index =
608 lookupString(val, WifiConfiguration.Protocol.strings);
609 if (0 <= index) {
610 config.allowedProtocols.set(index);
611 }
612 }
613 }
614
615 value = WifiNative.getNetworkVariableCommand(config.networkId,
616 WifiConfiguration.KeyMgmt.varName);
617 if (!TextUtils.isEmpty(value)) {
618 String vals[] = value.split(" ");
619 for (String val : vals) {
620 int index =
621 lookupString(val, WifiConfiguration.KeyMgmt.strings);
622 if (0 <= index) {
623 config.allowedKeyManagement.set(index);
624 }
625 }
626 }
627
628 value = WifiNative.getNetworkVariableCommand(config.networkId,
629 WifiConfiguration.AuthAlgorithm.varName);
630 if (!TextUtils.isEmpty(value)) {
631 String vals[] = value.split(" ");
632 for (String val : vals) {
633 int index =
634 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
635 if (0 <= index) {
636 config.allowedAuthAlgorithms.set(index);
637 }
638 }
639 }
640
641 value = WifiNative.getNetworkVariableCommand(config.networkId,
642 WifiConfiguration.PairwiseCipher.varName);
643 if (!TextUtils.isEmpty(value)) {
644 String vals[] = value.split(" ");
645 for (String val : vals) {
646 int index =
647 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
648 if (0 <= index) {
649 config.allowedPairwiseCiphers.set(index);
650 }
651 }
652 }
653
654 value = WifiNative.getNetworkVariableCommand(config.networkId,
655 WifiConfiguration.GroupCipher.varName);
656 if (!TextUtils.isEmpty(value)) {
657 String vals[] = value.split(" ");
658 for (String val : vals) {
659 int index =
660 lookupString(val, WifiConfiguration.GroupCipher.strings);
661 if (0 <= index) {
662 config.allowedGroupCiphers.set(index);
663 }
664 }
665 }
666 }
667
668 /**
669 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
670 * @return the supplicant-assigned identifier for the new or updated
671 * network if the operation succeeds, or {@code -1} if it fails
672 */
673 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
674 enforceChangePermission();
675 /*
676 * If the supplied networkId is -1, we create a new empty
677 * network configuration. Otherwise, the networkId should
678 * refer to an existing configuration.
679 */
680 int netId = config.networkId;
681 boolean newNetwork = netId == -1;
682 boolean doReconfig;
683 int currentPriority;
684 // networkId of -1 means we want to create a new network
685 if (newNetwork) {
686 netId = WifiNative.addNetworkCommand();
687 if (netId < 0) {
688 if (DBG) {
689 Log.d(TAG, "Failed to add a network!");
690 }
691 return -1;
692 }
693 doReconfig = true;
694 } else {
695 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
696 currentPriority = -1;
697 if (!TextUtils.isEmpty(priorityVal)) {
698 try {
699 currentPriority = Integer.parseInt(priorityVal);
700 } catch (NumberFormatException ignore) {
701 }
702 }
703 doReconfig = currentPriority != config.priority;
704 }
705 mNeedReconfig = mNeedReconfig || doReconfig;
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 setVariables: {
708 /*
709 * Note that if a networkId for a non-existent network
710 * was supplied, then the first setNetworkVariableCommand()
711 * will fail, so we don't bother to make a separate check
712 * for the validity of the ID up front.
713 */
714
715 if (config.SSID != null &&
716 !WifiNative.setNetworkVariableCommand(
717 netId,
718 WifiConfiguration.ssidVarName,
719 config.SSID)) {
720 if (DBG) {
721 Log.d(TAG, "failed to set SSID: "+config.SSID);
722 }
723 break setVariables;
724 }
725
726 if (config.BSSID != null &&
727 !WifiNative.setNetworkVariableCommand(
728 netId,
729 WifiConfiguration.bssidVarName,
730 config.BSSID)) {
731 if (DBG) {
732 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
733 }
734 break setVariables;
735 }
736
737 String allowedKeyManagementString =
738 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
739 if (config.allowedKeyManagement.cardinality() != 0 &&
740 !WifiNative.setNetworkVariableCommand(
741 netId,
742 WifiConfiguration.KeyMgmt.varName,
743 allowedKeyManagementString)) {
744 if (DBG) {
745 Log.d(TAG, "failed to set key_mgmt: "+
746 allowedKeyManagementString);
747 }
748 break setVariables;
749 }
750
751 String allowedProtocolsString =
752 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
753 if (config.allowedProtocols.cardinality() != 0 &&
754 !WifiNative.setNetworkVariableCommand(
755 netId,
756 WifiConfiguration.Protocol.varName,
757 allowedProtocolsString)) {
758 if (DBG) {
759 Log.d(TAG, "failed to set proto: "+
760 allowedProtocolsString);
761 }
762 break setVariables;
763 }
764
765 String allowedAuthAlgorithmsString =
766 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
767 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
768 !WifiNative.setNetworkVariableCommand(
769 netId,
770 WifiConfiguration.AuthAlgorithm.varName,
771 allowedAuthAlgorithmsString)) {
772 if (DBG) {
773 Log.d(TAG, "failed to set auth_alg: "+
774 allowedAuthAlgorithmsString);
775 }
776 break setVariables;
777 }
778
779 String allowedPairwiseCiphersString =
780 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
781 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
782 !WifiNative.setNetworkVariableCommand(
783 netId,
784 WifiConfiguration.PairwiseCipher.varName,
785 allowedPairwiseCiphersString)) {
786 if (DBG) {
787 Log.d(TAG, "failed to set pairwise: "+
788 allowedPairwiseCiphersString);
789 }
790 break setVariables;
791 }
792
793 String allowedGroupCiphersString =
794 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
795 if (config.allowedGroupCiphers.cardinality() != 0 &&
796 !WifiNative.setNetworkVariableCommand(
797 netId,
798 WifiConfiguration.GroupCipher.varName,
799 allowedGroupCiphersString)) {
800 if (DBG) {
801 Log.d(TAG, "failed to set group: "+
802 allowedGroupCiphersString);
803 }
804 break setVariables;
805 }
806
807 // Prevent client screw-up by passing in a WifiConfiguration we gave it
808 // by preventing "*" as a key.
809 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
810 !WifiNative.setNetworkVariableCommand(
811 netId,
812 WifiConfiguration.pskVarName,
813 config.preSharedKey)) {
814 if (DBG) {
815 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
816 }
817 break setVariables;
818 }
819
820 boolean hasSetKey = false;
821 if (config.wepKeys != null) {
822 for (int i = 0; i < config.wepKeys.length; i++) {
823 // Prevent client screw-up by passing in a WifiConfiguration we gave it
824 // by preventing "*" as a key.
825 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
826 if (!WifiNative.setNetworkVariableCommand(
827 netId,
828 WifiConfiguration.wepKeyVarNames[i],
829 config.wepKeys[i])) {
830 if (DBG) {
831 Log.d(TAG,
832 "failed to set wep_key"+i+": " +
833 config.wepKeys[i]);
834 }
835 break setVariables;
836 }
837 hasSetKey = true;
838 }
839 }
840 }
841
842 if (hasSetKey) {
843 if (!WifiNative.setNetworkVariableCommand(
844 netId,
845 WifiConfiguration.wepTxKeyIdxVarName,
846 Integer.toString(config.wepTxKeyIndex))) {
847 if (DBG) {
848 Log.d(TAG,
849 "failed to set wep_tx_keyidx: "+
850 config.wepTxKeyIndex);
851 }
852 break setVariables;
853 }
854 }
855
856 if (!WifiNative.setNetworkVariableCommand(
857 netId,
858 WifiConfiguration.priorityVarName,
859 Integer.toString(config.priority))) {
860 if (DBG) {
861 Log.d(TAG, config.SSID + ": failed to set priority: "
862 +config.priority);
863 }
864 break setVariables;
865 }
866
867 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
868 netId,
869 WifiConfiguration.hiddenSSIDVarName,
870 Integer.toString(config.hiddenSSID ? 1 : 0))) {
871 if (DBG) {
872 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
873 config.hiddenSSID);
874 }
875 break setVariables;
876 }
877
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800878 if ((config.eap != null) && !WifiNative.setNetworkVariableCommand(
879 netId,
880 WifiConfiguration.eapVarName,
881 config.eap)) {
882 if (DBG) {
883 Log.d(TAG, config.SSID + ": failed to set eap: "+
884 config.eap);
885 }
886 break setVariables;
887 }
888
889 if ((config.identity != null) && !WifiNative.setNetworkVariableCommand(
890 netId,
891 WifiConfiguration.identityVarName,
892 config.identity)) {
893 if (DBG) {
894 Log.d(TAG, config.SSID + ": failed to set identity: "+
895 config.identity);
896 }
897 break setVariables;
898 }
899
900 if ((config.anonymousIdentity != null) && !WifiNative.setNetworkVariableCommand(
901 netId,
902 WifiConfiguration.anonymousIdentityVarName,
903 config.anonymousIdentity)) {
904 if (DBG) {
905 Log.d(TAG, config.SSID + ": failed to set anonymousIdentity: "+
906 config.anonymousIdentity);
907 }
908 break setVariables;
909 }
910
Chung-yih Wang699ca3f2009-07-04 22:19:51 +0800911 if ((config.password != null) && !WifiNative.setNetworkVariableCommand(
912 netId,
913 WifiConfiguration.passwordVarName,
914 config.password)) {
915 if (DBG) {
916 Log.d(TAG, config.SSID + ": failed to set password: "+
917 config.password);
918 }
919 break setVariables;
920 }
921
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800922 if ((config.clientCert != null) && !WifiNative.setNetworkVariableCommand(
923 netId,
924 WifiConfiguration.clientCertVarName,
925 config.clientCert)) {
926 if (DBG) {
927 Log.d(TAG, config.SSID + ": failed to set clientCert: "+
928 config.clientCert);
929 }
930 break setVariables;
931 }
932
933 if ((config.caCert != null) && !WifiNative.setNetworkVariableCommand(
934 netId,
935 WifiConfiguration.caCertVarName,
936 config.caCert)) {
937 if (DBG) {
938 Log.d(TAG, config.SSID + ": failed to set caCert: "+
939 config.caCert);
940 }
941 break setVariables;
942 }
943
944 if ((config.privateKey != null) && !WifiNative.setNetworkVariableCommand(
945 netId,
946 WifiConfiguration.privateKeyVarName,
947 config.privateKey)) {
948 if (DBG) {
949 Log.d(TAG, config.SSID + ": failed to set privateKey: "+
950 config.privateKey);
951 }
952 break setVariables;
953 }
954
955 if ((config.privateKeyPasswd != null) && !WifiNative.setNetworkVariableCommand(
956 netId,
957 WifiConfiguration.privateKeyPasswdVarName,
958 config.privateKeyPasswd)) {
959 if (DBG) {
960 Log.d(TAG, config.SSID + ": failed to set privateKeyPasswd: "+
961 config.privateKeyPasswd);
962 }
963 break setVariables;
964 }
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 return netId;
967 }
968
969 /*
970 * For an update, if one of the setNetworkVariable operations fails,
971 * we might want to roll back all the changes already made. But the
972 * chances are that if anything is going to go wrong, it'll happen
973 * the first time we try to set one of the variables.
974 */
975 if (newNetwork) {
976 removeNetwork(netId);
977 if (DBG) {
978 Log.d(TAG,
979 "Failed to set a network variable, removed network: "
980 + netId);
981 }
982 }
983 return -1;
984 }
985
986 private static String makeString(BitSet set, String[] strings) {
987 StringBuffer buf = new StringBuffer();
988 int nextSetBit = -1;
989
990 /* Make sure all set bits are in [0, strings.length) to avoid
991 * going out of bounds on strings. (Shouldn't happen, but...) */
992 set = set.get(0, strings.length);
993
994 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
995 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
996 }
997
998 // remove trailing space
999 if (set.cardinality() > 0) {
1000 buf.setLength(buf.length() - 1);
1001 }
1002
1003 return buf.toString();
1004 }
1005
1006 private static int lookupString(String string, String[] strings) {
1007 int size = strings.length;
1008
1009 string = string.replace('-', '_');
1010
1011 for (int i = 0; i < size; i++)
1012 if (string.equals(strings[i]))
1013 return i;
1014
1015 if (DBG) {
1016 // if we ever get here, we should probably add the
1017 // value to WifiConfiguration to reflect that it's
1018 // supported by the WPA supplicant
1019 Log.w(TAG, "Failed to look-up a string: " + string);
1020 }
1021
1022 return -1;
1023 }
1024
1025 /**
1026 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1027 * @param netId the integer that identifies the network configuration
1028 * to the supplicant
1029 * @return {@code true} if the operation succeeded
1030 */
1031 public boolean removeNetwork(int netId) {
1032 enforceChangePermission();
1033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 return mWifiStateTracker.removeNetwork(netId);
1035 }
1036
1037 /**
1038 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1039 * @param netId the integer that identifies the network configuration
1040 * to the supplicant
1041 * @param disableOthers if true, disable all other networks.
1042 * @return {@code true} if the operation succeeded
1043 */
1044 public boolean enableNetwork(int netId, boolean disableOthers) {
1045 enforceChangePermission();
1046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 synchronized (mWifiStateTracker) {
1048 return WifiNative.enableNetworkCommand(netId, disableOthers);
1049 }
1050 }
1051
1052 /**
1053 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1054 * @param netId the integer that identifies the network configuration
1055 * to the supplicant
1056 * @return {@code true} if the operation succeeded
1057 */
1058 public boolean disableNetwork(int netId) {
1059 enforceChangePermission();
1060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 synchronized (mWifiStateTracker) {
1062 return WifiNative.disableNetworkCommand(netId);
1063 }
1064 }
1065
1066 /**
1067 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1068 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1069 */
1070 public WifiInfo getConnectionInfo() {
1071 enforceAccessPermission();
1072 /*
1073 * Make sure we have the latest information, by sending
1074 * a status request to the supplicant.
1075 */
1076 return mWifiStateTracker.requestConnectionInfo();
1077 }
1078
1079 /**
1080 * Return the results of the most recent access point scan, in the form of
1081 * a list of {@link ScanResult} objects.
1082 * @return the list of results
1083 */
1084 public List<ScanResult> getScanResults() {
1085 enforceAccessPermission();
1086 String reply;
1087 synchronized (mWifiStateTracker) {
1088 reply = WifiNative.scanResultsCommand();
1089 }
1090 if (reply == null) {
1091 return null;
1092 }
1093
1094 List<ScanResult> scanList = new ArrayList<ScanResult>();
1095
1096 int lineCount = 0;
1097
1098 int replyLen = reply.length();
1099 // Parse the result string, keeping in mind that the last line does
1100 // not end with a newline.
1101 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1102 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1103 ++lineCount;
1104 /*
1105 * Skip the first line, which is a header
1106 */
1107 if (lineCount == 1) {
1108 lineBeg = lineEnd + 1;
1109 continue;
1110 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001111 if (lineEnd > lineBeg) {
1112 String line = reply.substring(lineBeg, lineEnd);
1113 ScanResult scanResult = parseScanResult(line);
1114 if (scanResult != null) {
1115 scanList.add(scanResult);
1116 } else if (DBG) {
1117 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
1120 lineBeg = lineEnd + 1;
1121 }
1122 }
1123 mWifiStateTracker.setScanResultsList(scanList);
1124 return scanList;
1125 }
1126
1127 /**
1128 * Parse the scan result line passed to us by wpa_supplicant (helper).
1129 * @param line the line to parse
1130 * @return the {@link ScanResult} object
1131 */
1132 private ScanResult parseScanResult(String line) {
1133 ScanResult scanResult = null;
1134 if (line != null) {
1135 /*
1136 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1137 * must synchronized here!
1138 */
1139 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001140 String[] result = scanResultPattern.split(line);
1141 if (3 <= result.length && result.length <= 5) {
1142 String bssid = result[0];
1143 // bssid | frequency | level | flags | ssid
1144 int frequency;
1145 int level;
1146 try {
1147 frequency = Integer.parseInt(result[1]);
1148 level = Integer.parseInt(result[2]);
1149 /* some implementations avoid negative values by adding 256
1150 * so we need to adjust for that here.
1151 */
1152 if (level > 0) level -= 256;
1153 } catch (NumberFormatException e) {
1154 frequency = 0;
1155 level = 0;
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157
Mike Lockwood1a645052009-06-25 13:01:12 -04001158 /*
1159 * The formatting of the results returned by
1160 * wpa_supplicant is intended to make the fields
1161 * line up nicely when printed,
1162 * not to make them easy to parse. So we have to
1163 * apply some heuristics to figure out which field
1164 * is the SSID and which field is the flags.
1165 */
1166 String ssid;
1167 String flags;
1168 if (result.length == 4) {
1169 if (result[3].charAt(0) == '[') {
1170 flags = result[3];
1171 ssid = "";
1172 } else {
1173 flags = "";
1174 ssid = result[3];
1175 }
1176 } else if (result.length == 5) {
1177 flags = result[3];
1178 ssid = result[4];
1179 } else {
1180 // Here, we must have 3 fields: no flags and ssid
1181 // set
1182 flags = "";
1183 ssid = "";
1184 }
1185
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001186 // bssid is the hash key
1187 scanResult = mScanResultCache.get(bssid);
1188 if (scanResult != null) {
1189 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001190 scanResult.SSID = ssid;
1191 scanResult.capabilities = flags;
1192 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001193 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 // Do not add scan results that have no SSID set
1195 if (0 < ssid.trim().length()) {
1196 scanResult =
1197 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001198 ssid, bssid, flags, level, frequency);
1199 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001202 } else {
1203 Log.w(TAG, "Misformatted scan result text with " +
1204 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206 }
1207 }
1208
1209 return scanResult;
1210 }
1211
1212 /**
1213 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1214 * and construct a {@code WifiConfiguration} that describes the encryption,
1215 * key management, and authenticaion capabilities of the access point.
1216 * @param flags the string returned by wpa_supplicant
1217 * @return the {@link WifiConfiguration} object, filled in
1218 */
1219 WifiConfiguration parseScanFlags(String flags) {
1220 WifiConfiguration config = new WifiConfiguration();
1221
1222 if (flags.length() == 0) {
1223 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1224 }
1225 // ... to be implemented
1226 return config;
1227 }
1228
1229 /**
1230 * Tell the supplicant to persist the current list of configured networks.
1231 * @return {@code true} if the operation succeeded
1232 */
1233 public boolean saveConfiguration() {
1234 boolean result;
1235 enforceChangePermission();
1236 synchronized (mWifiStateTracker) {
1237 result = WifiNative.saveConfigCommand();
1238 if (result && mNeedReconfig) {
1239 mNeedReconfig = false;
1240 result = WifiNative.reloadConfigCommand();
1241
1242 if (result) {
1243 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1244 mContext.sendBroadcast(intent);
1245 }
1246 }
1247 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001248 // Inform the backup manager about a data change
1249 IBackupManager ibm = IBackupManager.Stub.asInterface(
1250 ServiceManager.getService(Context.BACKUP_SERVICE));
1251 if (ibm != null) {
1252 try {
1253 ibm.dataChanged("com.android.providers.settings");
1254 } catch (Exception e) {
1255 // Try again later
1256 }
1257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 return result;
1259 }
1260
1261 /**
1262 * Set the number of radio frequency channels that are allowed to be used
1263 * in the current regulatory domain. This method should be used only
1264 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001265 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * persisted as a Secure setting.
1267 * @param numChannels the number of allowed channels. Must be greater than 0
1268 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001269 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1271 * {@code numChannels} is outside the valid range.
1272 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001273 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1274 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1275 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 enforceChangePermission();
1277 /*
1278 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1279 * but if Wi-Fi isn't currently enabled, that's not possible, and
1280 * we want to persist the setting anyway,so that it will take
1281 * effect when Wi-Fi does become enabled.
1282 */
1283 boolean found = false;
1284 for (int validChan : sValidRegulatoryChannelCounts) {
1285 if (validChan == numChannels) {
1286 found = true;
1287 break;
1288 }
1289 }
1290 if (!found) {
1291 return false;
1292 }
1293
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001294 if (persist) {
1295 Settings.Secure.putInt(mContext.getContentResolver(),
1296 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1297 numChannels);
1298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 mWifiStateTracker.setNumAllowedChannels(numChannels);
1300 return true;
1301 }
1302
1303 /**
1304 * Return the number of frequency channels that are allowed
1305 * to be used in the current regulatory domain.
1306 * @return the number of allowed channels, or {@code -1} if an error occurs
1307 */
1308 public int getNumAllowedChannels() {
1309 int numChannels;
1310
1311 enforceAccessPermission();
1312 synchronized (mWifiStateTracker) {
1313 /*
1314 * If we can't get the value from the driver (e.g., because
1315 * Wi-Fi is not currently enabled), get the value from
1316 * Settings.
1317 */
1318 numChannels = WifiNative.getNumAllowedChannelsCommand();
1319 if (numChannels < 0) {
1320 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1321 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1322 -1);
1323 }
1324 }
1325 return numChannels;
1326 }
1327
1328 /**
1329 * Return the list of valid values for the number of allowed radio channels
1330 * for various regulatory domains.
1331 * @return the list of channel counts
1332 */
1333 public int[] getValidChannelCounts() {
1334 enforceAccessPermission();
1335 return sValidRegulatoryChannelCounts;
1336 }
1337
1338 /**
1339 * Return the DHCP-assigned addresses from the last successful DHCP request,
1340 * if any.
1341 * @return the DHCP information
1342 */
1343 public DhcpInfo getDhcpInfo() {
1344 enforceAccessPermission();
1345 return mWifiStateTracker.getDhcpInfo();
1346 }
1347
1348 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1349 @Override
1350 public void onReceive(Context context, Intent intent) {
1351 String action = intent.getAction();
1352
1353 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1354 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1355 int stayAwakeConditions =
1356 Settings.System.getInt(mContext.getContentResolver(),
1357 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1358 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001359 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 mAlarmManager.cancel(mIdleIntent);
1361 mDeviceIdle = false;
1362 mScreenOff = false;
1363 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001364 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 mScreenOff = true;
1366 /*
1367 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1368 * AND the "stay on while plugged in" setting doesn't match the
1369 * current power conditions (i.e, not plugged in, plugged in to USB,
1370 * or plugged in to AC).
1371 */
1372 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001373 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1374 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1375 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001376 mDeviceIdle = true;
1377 updateWifiState();
1378 } else {
1379 long triggerTime = System.currentTimeMillis() + idleMillis;
1380 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1381 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384 /* we can return now -- there's nothing to do until we get the idle intent back */
1385 return;
1386 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001387 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 mDeviceIdle = true;
1389 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1390 /*
1391 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1392 * AND we are transitioning from a state in which the device was supposed
1393 * to stay awake to a state in which it is not supposed to stay awake.
1394 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1395 * the already-set timer.
1396 */
1397 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001398 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1400 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1401 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001402 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1404 mPluggedType = pluggedType;
1405 return;
1406 }
1407 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001408 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1409 boolean isBluetoothPlaying =
1410 intent.getIntExtra(
1411 BluetoothA2dp.SINK_STATE,
1412 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1413 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 } else {
1415 return;
1416 }
1417
1418 updateWifiState();
1419 }
1420
1421 /**
1422 * Determines whether the Wi-Fi chipset should stay awake or be put to
1423 * sleep. Looks at the setting for the sleep policy and the current
1424 * conditions.
1425 *
1426 * @see #shouldDeviceStayAwake(int, int)
1427 */
1428 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1429 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1430 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1431
1432 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1433 // Never sleep
1434 return true;
1435 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1436 (pluggedType != 0)) {
1437 // Never sleep while plugged, and we're plugged
1438 return true;
1439 } else {
1440 // Default
1441 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1442 }
1443 }
1444
1445 /**
1446 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1447 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1448 * of {@code 0} isn't really a plugged type, but rather an indication that the
1449 * device isn't plugged in at all, there is no bit value corresponding to a
1450 * {@code pluggedType} value of {@code 0}. That is why we shift by
1451 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1452 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1453 * keep the device (and hence Wi-Fi) awake.
1454 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1455 * being made
1456 * @return {@code true} if {@code pluggedType} indicates that the device is
1457 * supposed to stay awake, {@code false} otherwise.
1458 */
1459 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1460 return (stayAwakeConditions & pluggedType) != 0;
1461 }
1462 };
1463
Dianne Hackborn617f8772009-03-31 15:04:46 -07001464 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 Message msg = Message.obtain(mWifiHandler,
1466 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001467 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 msg.sendToTarget();
1469 }
1470
1471 private void sendStartMessage(boolean scanOnlyMode) {
1472 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1473 }
1474
1475 private void updateWifiState() {
1476 boolean wifiEnabled = getPersistedWifiEnabled();
1477 boolean airplaneMode = isAirplaneModeOn();
1478 boolean lockHeld = mLocks.hasLocks();
1479 int strongestLockMode;
1480 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1481 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1482 if (mDeviceIdle && lockHeld) {
1483 strongestLockMode = mLocks.getStrongestLockMode();
1484 } else {
1485 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1486 }
1487
1488 synchronized (mWifiHandler) {
1489 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1490 return;
1491 }
1492 if (wifiShouldBeEnabled) {
1493 if (wifiShouldBeStarted) {
1494 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001495 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 sWakeLock.acquire();
1497 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1498 } else {
1499 int wakeLockTimeout =
1500 Settings.Secure.getInt(
1501 mContext.getContentResolver(),
1502 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1503 DEFAULT_WAKELOCK_TIMEOUT);
1504 /*
1505 * The following wakelock is held in order to ensure
1506 * that the connectivity manager has time to fail over
1507 * to the mobile data network. The connectivity manager
1508 * releases it once mobile data connectivity has been
1509 * established. If connectivity cannot be established,
1510 * the wakelock is released after wakeLockTimeout
1511 * milliseconds have elapsed.
1512 */
1513 sDriverStopWakeLock.acquire();
1514 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1515 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1516 }
1517 } else {
1518 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001519 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521 }
1522 }
1523
1524 private void registerForBroadcasts() {
1525 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1527 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1528 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1529 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001530 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 mContext.registerReceiver(mReceiver, intentFilter);
1532 }
1533
1534 private boolean isAirplaneSensitive() {
1535 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1536 Settings.System.AIRPLANE_MODE_RADIOS);
1537 return airplaneModeRadios == null
1538 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1539 }
1540
1541 /**
1542 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1543 * currently on.
1544 * @return {@code true} if airplane mode is on.
1545 */
1546 private boolean isAirplaneModeOn() {
1547 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1548 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1549 }
1550
1551 /**
1552 * Handler that allows posting to the WifiThread.
1553 */
1554 private class WifiHandler extends Handler {
1555 public WifiHandler(Looper looper) {
1556 super(looper);
1557 }
1558
1559 @Override
1560 public void handleMessage(Message msg) {
1561 switch (msg.what) {
1562
1563 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001564 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 sWakeLock.release();
1566 break;
1567
1568 case MESSAGE_START_WIFI:
1569 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1570 mWifiStateTracker.restart();
1571 sWakeLock.release();
1572 break;
1573
1574 case MESSAGE_DISABLE_WIFI:
1575 // a non-zero msg.arg1 value means the "enabled" setting
1576 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001577 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 sWakeLock.release();
1579 break;
1580
1581 case MESSAGE_STOP_WIFI:
1582 mWifiStateTracker.disconnectAndStop();
1583 // don't release wakelock
1584 break;
1585
1586 case MESSAGE_RELEASE_WAKELOCK:
1587 synchronized (sDriverStopWakeLock) {
1588 if (sDriverStopWakeLock.isHeld()) {
1589 sDriverStopWakeLock.release();
1590 }
1591 }
1592 break;
1593 }
1594 }
1595 }
1596
1597 @Override
1598 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1599 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1600 != PackageManager.PERMISSION_GRANTED) {
1601 pw.println("Permission Denial: can't dump WifiService from from pid="
1602 + Binder.getCallingPid()
1603 + ", uid=" + Binder.getCallingUid());
1604 return;
1605 }
1606 pw.println("Wi-Fi is " + stateName(mWifiState));
1607 pw.println("Stay-awake conditions: " +
1608 Settings.System.getInt(mContext.getContentResolver(),
1609 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1610 pw.println();
1611
1612 pw.println("Internal state:");
1613 pw.println(mWifiStateTracker);
1614 pw.println();
1615 pw.println("Latest scan results:");
1616 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1617 if (scanResults != null && scanResults.size() != 0) {
1618 pw.println(" BSSID Frequency RSSI Flags SSID");
1619 for (ScanResult r : scanResults) {
1620 pw.printf(" %17s %9d %5d %-16s %s%n",
1621 r.BSSID,
1622 r.frequency,
1623 r.level,
1624 r.capabilities,
1625 r.SSID == null ? "" : r.SSID);
1626 }
1627 }
1628 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001629 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1630 mScanLocksAcquired + " scan");
1631 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1632 mScanLocksReleased + " scan");
1633 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 pw.println("Locks held:");
1635 mLocks.dump(pw);
1636 }
1637
1638 private static String stateName(int wifiState) {
1639 switch (wifiState) {
1640 case WIFI_STATE_DISABLING:
1641 return "disabling";
1642 case WIFI_STATE_DISABLED:
1643 return "disabled";
1644 case WIFI_STATE_ENABLING:
1645 return "enabling";
1646 case WIFI_STATE_ENABLED:
1647 return "enabled";
1648 case WIFI_STATE_UNKNOWN:
1649 return "unknown state";
1650 default:
1651 return "[invalid state]";
1652 }
1653 }
1654
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001655 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001657 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659
1660 public void binderDied() {
1661 synchronized (mLocks) {
1662 releaseWifiLockLocked(mBinder);
1663 }
1664 }
1665
1666 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001667 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669 }
1670
1671 private class LockList {
1672 private List<WifiLock> mList;
1673
1674 private LockList() {
1675 mList = new ArrayList<WifiLock>();
1676 }
1677
1678 private synchronized boolean hasLocks() {
1679 return !mList.isEmpty();
1680 }
1681
1682 private synchronized int getStrongestLockMode() {
1683 if (mList.isEmpty()) {
1684 return WifiManager.WIFI_MODE_FULL;
1685 }
1686 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001687 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 return WifiManager.WIFI_MODE_FULL;
1689 }
1690 }
1691 return WifiManager.WIFI_MODE_SCAN_ONLY;
1692 }
1693
1694 private void addLock(WifiLock lock) {
1695 if (findLockByBinder(lock.mBinder) < 0) {
1696 mList.add(lock);
1697 }
1698 }
1699
1700 private WifiLock removeLock(IBinder binder) {
1701 int index = findLockByBinder(binder);
1702 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001703 WifiLock ret = mList.remove(index);
1704 ret.unlinkDeathRecipient();
1705 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 } else {
1707 return null;
1708 }
1709 }
1710
1711 private int findLockByBinder(IBinder binder) {
1712 int size = mList.size();
1713 for (int i = size - 1; i >= 0; i--)
1714 if (mList.get(i).mBinder == binder)
1715 return i;
1716 return -1;
1717 }
1718
1719 private void dump(PrintWriter pw) {
1720 for (WifiLock l : mList) {
1721 pw.print(" ");
1722 pw.println(l);
1723 }
1724 }
1725 }
1726
1727 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1729 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1730 return false;
1731 }
1732 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1733 synchronized (mLocks) {
1734 return acquireWifiLockLocked(wifiLock);
1735 }
1736 }
1737
1738 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1739 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001740
1741 int uid = Binder.getCallingUid();
1742 long ident = Binder.clearCallingIdentity();
1743 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001744 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001745 case WifiManager.WIFI_MODE_FULL:
1746 ++mFullLocksAcquired;
1747 mBatteryStats.noteFullWifiLockAcquired(uid);
1748 break;
1749 case WifiManager.WIFI_MODE_SCAN_ONLY:
1750 ++mScanLocksAcquired;
1751 mBatteryStats.noteScanWifiLockAcquired(uid);
1752 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001753 }
1754 } catch (RemoteException e) {
1755 } finally {
1756 Binder.restoreCallingIdentity(ident);
1757 }
1758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 updateWifiState();
1760 return true;
1761 }
1762
1763 public boolean releaseWifiLock(IBinder lock) {
1764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1765 synchronized (mLocks) {
1766 return releaseWifiLockLocked(lock);
1767 }
1768 }
1769
1770 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001771 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001772
1773 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001774 hadLock = (wifiLock != null);
1775
1776 if (hadLock) {
1777 int uid = Binder.getCallingUid();
1778 long ident = Binder.clearCallingIdentity();
1779 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001780 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001781 case WifiManager.WIFI_MODE_FULL:
1782 ++mFullLocksReleased;
1783 mBatteryStats.noteFullWifiLockReleased(uid);
1784 break;
1785 case WifiManager.WIFI_MODE_SCAN_ONLY:
1786 ++mScanLocksReleased;
1787 mBatteryStats.noteScanWifiLockReleased(uid);
1788 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001789 }
1790 } catch (RemoteException e) {
1791 } finally {
1792 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001793 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001794 }
1795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001797 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001799
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001800 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001801 implements IBinder.DeathRecipient {
1802 String mTag;
1803 int mMode;
1804 IBinder mBinder;
1805
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001806 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001807 super();
1808 mTag = tag;
1809 mMode = mode;
1810 mBinder = binder;
1811 try {
1812 mBinder.linkToDeath(this, 0);
1813 } catch (RemoteException e) {
1814 binderDied();
1815 }
1816 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001817
1818 void unlinkDeathRecipient() {
1819 mBinder.unlinkToDeath(this, 0);
1820 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001821 }
1822
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001823 private class Multicaster extends DeathRecipient {
1824 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001825 super(Binder.getCallingUid(), tag, binder);
1826 }
1827
1828 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001829 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001830 synchronized (mMulticasters) {
1831 int i = mMulticasters.indexOf(this);
1832 if (i != -1) {
1833 removeMulticasterLocked(i, mMode);
1834 }
1835 }
1836 }
1837
1838 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001839 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001840 }
1841
1842 public int getUid() {
1843 return mMode;
1844 }
1845 }
1846
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001847 public void acquireMulticastLock(IBinder binder, String tag) {
1848 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001849
1850 synchronized (mMulticasters) {
1851 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001852 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001853 // Note that we could call stopPacketFiltering only when
1854 // our new size == 1 (first call), but this function won't
1855 // be called often and by making the stopPacket call each
1856 // time we're less fragile and self-healing.
1857 WifiNative.stopPacketFiltering();
1858 }
1859
1860 int uid = Binder.getCallingUid();
1861 Long ident = Binder.clearCallingIdentity();
1862 try {
1863 mBatteryStats.noteWifiMulticastEnabled(uid);
1864 } catch (RemoteException e) {
1865 } finally {
1866 Binder.restoreCallingIdentity(ident);
1867 }
1868 }
1869
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001870 public void releaseMulticastLock() {
1871 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001872
1873 int uid = Binder.getCallingUid();
1874 synchronized (mMulticasters) {
1875 mMulticastDisabled++;
1876 int size = mMulticasters.size();
1877 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001878 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001879 if ((m != null) && (m.getUid() == uid)) {
1880 removeMulticasterLocked(i, uid);
1881 }
1882 }
1883 }
1884 }
1885
1886 private void removeMulticasterLocked(int i, int uid)
1887 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001888 Multicaster removed = mMulticasters.remove(i);
1889 if (removed != null) {
1890 removed.unlinkDeathRecipient();
1891 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001892 if (mMulticasters.size() == 0) {
1893 WifiNative.startPacketFiltering();
1894 }
1895
1896 Long ident = Binder.clearCallingIdentity();
1897 try {
1898 mBatteryStats.noteWifiMulticastDisabled(uid);
1899 } catch (RemoteException e) {
1900 } finally {
1901 Binder.restoreCallingIdentity(ident);
1902 }
1903 }
1904
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001905 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001906 enforceAccessPermission();
1907
1908 synchronized (mMulticasters) {
1909 return (mMulticasters.size() > 0);
1910 }
1911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912}