blob: fae987a3af87872abfebb57d6e1ff4902b44241d [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
377 /*
Mike Lockwood622f82a2009-07-09 23:39:01 -0400378 * Initialize the number of allowed radio channels if Wi-Fi is being turned on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 */
380 if (enable) {
381 mWifiStateTracker.setNumAllowedChannels();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
384 return true;
385 }
386
Dianne Hackborn617f8772009-03-31 15:04:46 -0700387 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 final int previousWifiState = mWifiState;
389
The Android Open Source Project10592532009-03-18 17:39:46 -0700390 long ident = Binder.clearCallingIdentity();
391 try {
392 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700393 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700394 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700395 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700396 }
397 } catch (RemoteException e) {
398 } finally {
399 Binder.restoreCallingIdentity(ident);
400 }
401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 // Update state
403 mWifiState = wifiState;
404
405 // Broadcast
406 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
407 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
408 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
409 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
410 mContext.sendStickyBroadcast(intent);
411 }
412
413 private void enforceAccessPermission() {
414 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
415 "WifiService");
416 }
417
418 private void enforceChangePermission() {
419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
420 "WifiService");
421
422 }
423
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700424 private void enforceMulticastChangePermission() {
425 mContext.enforceCallingOrSelfPermission(
426 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
427 "WifiService");
428 }
429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 /**
431 * see {@link WifiManager#getWifiState()}
432 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
433 * {@link WifiManager#WIFI_STATE_DISABLING},
434 * {@link WifiManager#WIFI_STATE_ENABLED},
435 * {@link WifiManager#WIFI_STATE_ENABLING},
436 * {@link WifiManager#WIFI_STATE_UNKNOWN}
437 */
438 public int getWifiEnabledState() {
439 enforceAccessPermission();
440 return mWifiState;
441 }
442
443 /**
444 * see {@link android.net.wifi.WifiManager#disconnect()}
445 * @return {@code true} if the operation succeeds
446 */
447 public boolean disconnect() {
448 enforceChangePermission();
449 synchronized (mWifiStateTracker) {
450 return WifiNative.disconnectCommand();
451 }
452 }
453
454 /**
455 * see {@link android.net.wifi.WifiManager#reconnect()}
456 * @return {@code true} if the operation succeeds
457 */
458 public boolean reconnect() {
459 enforceChangePermission();
460 synchronized (mWifiStateTracker) {
461 return WifiNative.reconnectCommand();
462 }
463 }
464
465 /**
466 * see {@link android.net.wifi.WifiManager#reassociate()}
467 * @return {@code true} if the operation succeeds
468 */
469 public boolean reassociate() {
470 enforceChangePermission();
471 synchronized (mWifiStateTracker) {
472 return WifiNative.reassociateCommand();
473 }
474 }
475
476 /**
477 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
478 * @return the list of configured networks
479 */
480 public List<WifiConfiguration> getConfiguredNetworks() {
481 enforceAccessPermission();
482 String listStr;
483 /*
484 * We don't cache the list, because we want to allow
485 * for the possibility that the configuration file
486 * has been modified through some external means,
487 * such as the wpa_cli command line program.
488 */
489 synchronized (mWifiStateTracker) {
490 listStr = WifiNative.listNetworksCommand();
491 }
492 List<WifiConfiguration> networks =
493 new ArrayList<WifiConfiguration>();
494 if (listStr == null)
495 return networks;
496
497 String[] lines = listStr.split("\n");
498 // Skip the first line, which is a header
499 for (int i = 1; i < lines.length; i++) {
500 String[] result = lines[i].split("\t");
501 // network-id | ssid | bssid | flags
502 WifiConfiguration config = new WifiConfiguration();
503 try {
504 config.networkId = Integer.parseInt(result[0]);
505 } catch(NumberFormatException e) {
506 continue;
507 }
508 if (result.length > 3) {
509 if (result[3].indexOf("[CURRENT]") != -1)
510 config.status = WifiConfiguration.Status.CURRENT;
511 else if (result[3].indexOf("[DISABLED]") != -1)
512 config.status = WifiConfiguration.Status.DISABLED;
513 else
514 config.status = WifiConfiguration.Status.ENABLED;
515 } else
516 config.status = WifiConfiguration.Status.ENABLED;
517 synchronized (mWifiStateTracker) {
518 readNetworkVariables(config);
519 }
520 networks.add(config);
521 }
522
523 return networks;
524 }
525
526 /**
527 * Read the variables from the supplicant daemon that are needed to
528 * fill in the WifiConfiguration object.
529 * <p/>
530 * The caller must hold the synchronization monitor.
531 * @param config the {@link WifiConfiguration} object to be filled in.
532 */
533 private static void readNetworkVariables(WifiConfiguration config) {
534
535 int netId = config.networkId;
536 if (netId < 0)
537 return;
538
539 /*
540 * TODO: maybe should have a native method that takes an array of
541 * variable names and returns an array of values. But we'd still
542 * be doing a round trip to the supplicant daemon for each variable.
543 */
544 String value;
545
546 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
547 if (!TextUtils.isEmpty(value)) {
548 config.SSID = value;
549 } else {
550 config.SSID = null;
551 }
552
553 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
554 if (!TextUtils.isEmpty(value)) {
555 config.BSSID = value;
556 } else {
557 config.BSSID = null;
558 }
559
560 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
561 config.priority = -1;
562 if (!TextUtils.isEmpty(value)) {
563 try {
564 config.priority = Integer.parseInt(value);
565 } catch (NumberFormatException ignore) {
566 }
567 }
568
569 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
570 config.hiddenSSID = false;
571 if (!TextUtils.isEmpty(value)) {
572 try {
573 config.hiddenSSID = Integer.parseInt(value) != 0;
574 } catch (NumberFormatException ignore) {
575 }
576 }
577
578 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
579 config.wepTxKeyIndex = -1;
580 if (!TextUtils.isEmpty(value)) {
581 try {
582 config.wepTxKeyIndex = Integer.parseInt(value);
583 } catch (NumberFormatException ignore) {
584 }
585 }
586
587 /*
588 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
589 * just a "*" if the key is set, or the null string otherwise.
590 */
591 for (int i = 0; i < 4; i++) {
592 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
593 if (!TextUtils.isEmpty(value)) {
594 config.wepKeys[i] = value;
595 } else {
596 config.wepKeys[i] = null;
597 }
598 }
599
600 /*
601 * Get the private shared key. Note that the actual keys are not passed back,
602 * just a "*" if the key is set, or the null string otherwise.
603 */
604 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
605 if (!TextUtils.isEmpty(value)) {
606 config.preSharedKey = value;
607 } else {
608 config.preSharedKey = null;
609 }
610
611 value = WifiNative.getNetworkVariableCommand(config.networkId,
612 WifiConfiguration.Protocol.varName);
613 if (!TextUtils.isEmpty(value)) {
614 String vals[] = value.split(" ");
615 for (String val : vals) {
616 int index =
617 lookupString(val, WifiConfiguration.Protocol.strings);
618 if (0 <= index) {
619 config.allowedProtocols.set(index);
620 }
621 }
622 }
623
624 value = WifiNative.getNetworkVariableCommand(config.networkId,
625 WifiConfiguration.KeyMgmt.varName);
626 if (!TextUtils.isEmpty(value)) {
627 String vals[] = value.split(" ");
628 for (String val : vals) {
629 int index =
630 lookupString(val, WifiConfiguration.KeyMgmt.strings);
631 if (0 <= index) {
632 config.allowedKeyManagement.set(index);
633 }
634 }
635 }
636
637 value = WifiNative.getNetworkVariableCommand(config.networkId,
638 WifiConfiguration.AuthAlgorithm.varName);
639 if (!TextUtils.isEmpty(value)) {
640 String vals[] = value.split(" ");
641 for (String val : vals) {
642 int index =
643 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
644 if (0 <= index) {
645 config.allowedAuthAlgorithms.set(index);
646 }
647 }
648 }
649
650 value = WifiNative.getNetworkVariableCommand(config.networkId,
651 WifiConfiguration.PairwiseCipher.varName);
652 if (!TextUtils.isEmpty(value)) {
653 String vals[] = value.split(" ");
654 for (String val : vals) {
655 int index =
656 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
657 if (0 <= index) {
658 config.allowedPairwiseCiphers.set(index);
659 }
660 }
661 }
662
663 value = WifiNative.getNetworkVariableCommand(config.networkId,
664 WifiConfiguration.GroupCipher.varName);
665 if (!TextUtils.isEmpty(value)) {
666 String vals[] = value.split(" ");
667 for (String val : vals) {
668 int index =
669 lookupString(val, WifiConfiguration.GroupCipher.strings);
670 if (0 <= index) {
671 config.allowedGroupCiphers.set(index);
672 }
673 }
674 }
675 }
676
677 /**
678 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
679 * @return the supplicant-assigned identifier for the new or updated
680 * network if the operation succeeds, or {@code -1} if it fails
681 */
682 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
683 enforceChangePermission();
684 /*
685 * If the supplied networkId is -1, we create a new empty
686 * network configuration. Otherwise, the networkId should
687 * refer to an existing configuration.
688 */
689 int netId = config.networkId;
690 boolean newNetwork = netId == -1;
691 boolean doReconfig;
692 int currentPriority;
693 // networkId of -1 means we want to create a new network
694 if (newNetwork) {
695 netId = WifiNative.addNetworkCommand();
696 if (netId < 0) {
697 if (DBG) {
698 Log.d(TAG, "Failed to add a network!");
699 }
700 return -1;
701 }
702 doReconfig = true;
703 } else {
704 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
705 currentPriority = -1;
706 if (!TextUtils.isEmpty(priorityVal)) {
707 try {
708 currentPriority = Integer.parseInt(priorityVal);
709 } catch (NumberFormatException ignore) {
710 }
711 }
712 doReconfig = currentPriority != config.priority;
713 }
714 mNeedReconfig = mNeedReconfig || doReconfig;
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 setVariables: {
717 /*
718 * Note that if a networkId for a non-existent network
719 * was supplied, then the first setNetworkVariableCommand()
720 * will fail, so we don't bother to make a separate check
721 * for the validity of the ID up front.
722 */
723
724 if (config.SSID != null &&
725 !WifiNative.setNetworkVariableCommand(
726 netId,
727 WifiConfiguration.ssidVarName,
728 config.SSID)) {
729 if (DBG) {
730 Log.d(TAG, "failed to set SSID: "+config.SSID);
731 }
732 break setVariables;
733 }
734
735 if (config.BSSID != null &&
736 !WifiNative.setNetworkVariableCommand(
737 netId,
738 WifiConfiguration.bssidVarName,
739 config.BSSID)) {
740 if (DBG) {
741 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
742 }
743 break setVariables;
744 }
745
746 String allowedKeyManagementString =
747 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
748 if (config.allowedKeyManagement.cardinality() != 0 &&
749 !WifiNative.setNetworkVariableCommand(
750 netId,
751 WifiConfiguration.KeyMgmt.varName,
752 allowedKeyManagementString)) {
753 if (DBG) {
754 Log.d(TAG, "failed to set key_mgmt: "+
755 allowedKeyManagementString);
756 }
757 break setVariables;
758 }
759
760 String allowedProtocolsString =
761 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
762 if (config.allowedProtocols.cardinality() != 0 &&
763 !WifiNative.setNetworkVariableCommand(
764 netId,
765 WifiConfiguration.Protocol.varName,
766 allowedProtocolsString)) {
767 if (DBG) {
768 Log.d(TAG, "failed to set proto: "+
769 allowedProtocolsString);
770 }
771 break setVariables;
772 }
773
774 String allowedAuthAlgorithmsString =
775 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
776 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
777 !WifiNative.setNetworkVariableCommand(
778 netId,
779 WifiConfiguration.AuthAlgorithm.varName,
780 allowedAuthAlgorithmsString)) {
781 if (DBG) {
782 Log.d(TAG, "failed to set auth_alg: "+
783 allowedAuthAlgorithmsString);
784 }
785 break setVariables;
786 }
787
788 String allowedPairwiseCiphersString =
789 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
790 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
791 !WifiNative.setNetworkVariableCommand(
792 netId,
793 WifiConfiguration.PairwiseCipher.varName,
794 allowedPairwiseCiphersString)) {
795 if (DBG) {
796 Log.d(TAG, "failed to set pairwise: "+
797 allowedPairwiseCiphersString);
798 }
799 break setVariables;
800 }
801
802 String allowedGroupCiphersString =
803 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
804 if (config.allowedGroupCiphers.cardinality() != 0 &&
805 !WifiNative.setNetworkVariableCommand(
806 netId,
807 WifiConfiguration.GroupCipher.varName,
808 allowedGroupCiphersString)) {
809 if (DBG) {
810 Log.d(TAG, "failed to set group: "+
811 allowedGroupCiphersString);
812 }
813 break setVariables;
814 }
815
816 // Prevent client screw-up by passing in a WifiConfiguration we gave it
817 // by preventing "*" as a key.
818 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
819 !WifiNative.setNetworkVariableCommand(
820 netId,
821 WifiConfiguration.pskVarName,
822 config.preSharedKey)) {
823 if (DBG) {
824 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
825 }
826 break setVariables;
827 }
828
829 boolean hasSetKey = false;
830 if (config.wepKeys != null) {
831 for (int i = 0; i < config.wepKeys.length; i++) {
832 // Prevent client screw-up by passing in a WifiConfiguration we gave it
833 // by preventing "*" as a key.
834 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
835 if (!WifiNative.setNetworkVariableCommand(
836 netId,
837 WifiConfiguration.wepKeyVarNames[i],
838 config.wepKeys[i])) {
839 if (DBG) {
840 Log.d(TAG,
841 "failed to set wep_key"+i+": " +
842 config.wepKeys[i]);
843 }
844 break setVariables;
845 }
846 hasSetKey = true;
847 }
848 }
849 }
850
851 if (hasSetKey) {
852 if (!WifiNative.setNetworkVariableCommand(
853 netId,
854 WifiConfiguration.wepTxKeyIdxVarName,
855 Integer.toString(config.wepTxKeyIndex))) {
856 if (DBG) {
857 Log.d(TAG,
858 "failed to set wep_tx_keyidx: "+
859 config.wepTxKeyIndex);
860 }
861 break setVariables;
862 }
863 }
864
865 if (!WifiNative.setNetworkVariableCommand(
866 netId,
867 WifiConfiguration.priorityVarName,
868 Integer.toString(config.priority))) {
869 if (DBG) {
870 Log.d(TAG, config.SSID + ": failed to set priority: "
871 +config.priority);
872 }
873 break setVariables;
874 }
875
876 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
877 netId,
878 WifiConfiguration.hiddenSSIDVarName,
879 Integer.toString(config.hiddenSSID ? 1 : 0))) {
880 if (DBG) {
881 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
882 config.hiddenSSID);
883 }
884 break setVariables;
885 }
886
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800887 if ((config.eap != null) && !WifiNative.setNetworkVariableCommand(
888 netId,
889 WifiConfiguration.eapVarName,
890 config.eap)) {
891 if (DBG) {
892 Log.d(TAG, config.SSID + ": failed to set eap: "+
893 config.eap);
894 }
895 break setVariables;
896 }
897
Chung-yih Wangb96ea202009-07-22 15:56:04 +0800898 if ((config.phase2 != null) && !WifiNative.setNetworkVariableCommand(
899 netId,
900 WifiConfiguration.phase2VarName,
901 config.phase2)) {
902 if (DBG) {
903 Log.d(TAG, config.SSID + ": failed to set phase2: "+
904 config.phase2);
905 }
906 break setVariables;
907 }
908
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800909 if ((config.identity != null) && !WifiNative.setNetworkVariableCommand(
910 netId,
911 WifiConfiguration.identityVarName,
912 config.identity)) {
913 if (DBG) {
914 Log.d(TAG, config.SSID + ": failed to set identity: "+
915 config.identity);
916 }
917 break setVariables;
918 }
919
920 if ((config.anonymousIdentity != null) && !WifiNative.setNetworkVariableCommand(
921 netId,
922 WifiConfiguration.anonymousIdentityVarName,
923 config.anonymousIdentity)) {
924 if (DBG) {
925 Log.d(TAG, config.SSID + ": failed to set anonymousIdentity: "+
926 config.anonymousIdentity);
927 }
928 break setVariables;
929 }
930
Chung-yih Wang699ca3f2009-07-04 22:19:51 +0800931 if ((config.password != null) && !WifiNative.setNetworkVariableCommand(
932 netId,
933 WifiConfiguration.passwordVarName,
934 config.password)) {
935 if (DBG) {
936 Log.d(TAG, config.SSID + ": failed to set password: "+
937 config.password);
938 }
939 break setVariables;
940 }
941
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800942 if ((config.clientCert != null) && !WifiNative.setNetworkVariableCommand(
943 netId,
944 WifiConfiguration.clientCertVarName,
945 config.clientCert)) {
946 if (DBG) {
947 Log.d(TAG, config.SSID + ": failed to set clientCert: "+
948 config.clientCert);
949 }
950 break setVariables;
951 }
952
953 if ((config.caCert != null) && !WifiNative.setNetworkVariableCommand(
954 netId,
955 WifiConfiguration.caCertVarName,
956 config.caCert)) {
957 if (DBG) {
958 Log.d(TAG, config.SSID + ": failed to set caCert: "+
959 config.caCert);
960 }
961 break setVariables;
962 }
963
964 if ((config.privateKey != null) && !WifiNative.setNetworkVariableCommand(
965 netId,
966 WifiConfiguration.privateKeyVarName,
967 config.privateKey)) {
968 if (DBG) {
969 Log.d(TAG, config.SSID + ": failed to set privateKey: "+
970 config.privateKey);
971 }
972 break setVariables;
973 }
974
975 if ((config.privateKeyPasswd != null) && !WifiNative.setNetworkVariableCommand(
976 netId,
977 WifiConfiguration.privateKeyPasswdVarName,
978 config.privateKeyPasswd)) {
979 if (DBG) {
980 Log.d(TAG, config.SSID + ": failed to set privateKeyPasswd: "+
981 config.privateKeyPasswd);
982 }
983 break setVariables;
984 }
985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 return netId;
987 }
988
989 /*
990 * For an update, if one of the setNetworkVariable operations fails,
991 * we might want to roll back all the changes already made. But the
992 * chances are that if anything is going to go wrong, it'll happen
993 * the first time we try to set one of the variables.
994 */
995 if (newNetwork) {
996 removeNetwork(netId);
997 if (DBG) {
998 Log.d(TAG,
999 "Failed to set a network variable, removed network: "
1000 + netId);
1001 }
1002 }
1003 return -1;
1004 }
1005
1006 private static String makeString(BitSet set, String[] strings) {
1007 StringBuffer buf = new StringBuffer();
1008 int nextSetBit = -1;
1009
1010 /* Make sure all set bits are in [0, strings.length) to avoid
1011 * going out of bounds on strings. (Shouldn't happen, but...) */
1012 set = set.get(0, strings.length);
1013
1014 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1015 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1016 }
1017
1018 // remove trailing space
1019 if (set.cardinality() > 0) {
1020 buf.setLength(buf.length() - 1);
1021 }
1022
1023 return buf.toString();
1024 }
1025
1026 private static int lookupString(String string, String[] strings) {
1027 int size = strings.length;
1028
1029 string = string.replace('-', '_');
1030
1031 for (int i = 0; i < size; i++)
1032 if (string.equals(strings[i]))
1033 return i;
1034
1035 if (DBG) {
1036 // if we ever get here, we should probably add the
1037 // value to WifiConfiguration to reflect that it's
1038 // supported by the WPA supplicant
1039 Log.w(TAG, "Failed to look-up a string: " + string);
1040 }
1041
1042 return -1;
1043 }
1044
1045 /**
1046 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1047 * @param netId the integer that identifies the network configuration
1048 * to the supplicant
1049 * @return {@code true} if the operation succeeded
1050 */
1051 public boolean removeNetwork(int netId) {
1052 enforceChangePermission();
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 return mWifiStateTracker.removeNetwork(netId);
1055 }
1056
1057 /**
1058 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1059 * @param netId the integer that identifies the network configuration
1060 * to the supplicant
1061 * @param disableOthers if true, disable all other networks.
1062 * @return {@code true} if the operation succeeded
1063 */
1064 public boolean enableNetwork(int netId, boolean disableOthers) {
1065 enforceChangePermission();
1066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001068 String ifname = mWifiStateTracker.getInterfaceName();
1069 NetworkUtils.enableInterface(ifname);
1070 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1071 if (!result) {
1072 NetworkUtils.disableInterface(ifname);
1073 }
1074 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076 }
1077
1078 /**
1079 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1080 * @param netId the integer that identifies the network configuration
1081 * to the supplicant
1082 * @return {@code true} if the operation succeeded
1083 */
1084 public boolean disableNetwork(int netId) {
1085 enforceChangePermission();
1086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 synchronized (mWifiStateTracker) {
1088 return WifiNative.disableNetworkCommand(netId);
1089 }
1090 }
1091
1092 /**
1093 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1094 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1095 */
1096 public WifiInfo getConnectionInfo() {
1097 enforceAccessPermission();
1098 /*
1099 * Make sure we have the latest information, by sending
1100 * a status request to the supplicant.
1101 */
1102 return mWifiStateTracker.requestConnectionInfo();
1103 }
1104
1105 /**
1106 * Return the results of the most recent access point scan, in the form of
1107 * a list of {@link ScanResult} objects.
1108 * @return the list of results
1109 */
1110 public List<ScanResult> getScanResults() {
1111 enforceAccessPermission();
1112 String reply;
1113 synchronized (mWifiStateTracker) {
1114 reply = WifiNative.scanResultsCommand();
1115 }
1116 if (reply == null) {
1117 return null;
1118 }
1119
1120 List<ScanResult> scanList = new ArrayList<ScanResult>();
1121
1122 int lineCount = 0;
1123
1124 int replyLen = reply.length();
1125 // Parse the result string, keeping in mind that the last line does
1126 // not end with a newline.
1127 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1128 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1129 ++lineCount;
1130 /*
1131 * Skip the first line, which is a header
1132 */
1133 if (lineCount == 1) {
1134 lineBeg = lineEnd + 1;
1135 continue;
1136 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001137 if (lineEnd > lineBeg) {
1138 String line = reply.substring(lineBeg, lineEnd);
1139 ScanResult scanResult = parseScanResult(line);
1140 if (scanResult != null) {
1141 scanList.add(scanResult);
1142 } else if (DBG) {
1143 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 }
1146 lineBeg = lineEnd + 1;
1147 }
1148 }
1149 mWifiStateTracker.setScanResultsList(scanList);
1150 return scanList;
1151 }
1152
1153 /**
1154 * Parse the scan result line passed to us by wpa_supplicant (helper).
1155 * @param line the line to parse
1156 * @return the {@link ScanResult} object
1157 */
1158 private ScanResult parseScanResult(String line) {
1159 ScanResult scanResult = null;
1160 if (line != null) {
1161 /*
1162 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1163 * must synchronized here!
1164 */
1165 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001166 String[] result = scanResultPattern.split(line);
1167 if (3 <= result.length && result.length <= 5) {
1168 String bssid = result[0];
1169 // bssid | frequency | level | flags | ssid
1170 int frequency;
1171 int level;
1172 try {
1173 frequency = Integer.parseInt(result[1]);
1174 level = Integer.parseInt(result[2]);
1175 /* some implementations avoid negative values by adding 256
1176 * so we need to adjust for that here.
1177 */
1178 if (level > 0) level -= 256;
1179 } catch (NumberFormatException e) {
1180 frequency = 0;
1181 level = 0;
1182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183
Mike Lockwood1a645052009-06-25 13:01:12 -04001184 /*
1185 * The formatting of the results returned by
1186 * wpa_supplicant is intended to make the fields
1187 * line up nicely when printed,
1188 * not to make them easy to parse. So we have to
1189 * apply some heuristics to figure out which field
1190 * is the SSID and which field is the flags.
1191 */
1192 String ssid;
1193 String flags;
1194 if (result.length == 4) {
1195 if (result[3].charAt(0) == '[') {
1196 flags = result[3];
1197 ssid = "";
1198 } else {
1199 flags = "";
1200 ssid = result[3];
1201 }
1202 } else if (result.length == 5) {
1203 flags = result[3];
1204 ssid = result[4];
1205 } else {
1206 // Here, we must have 3 fields: no flags and ssid
1207 // set
1208 flags = "";
1209 ssid = "";
1210 }
1211
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001212 // bssid is the hash key
1213 scanResult = mScanResultCache.get(bssid);
1214 if (scanResult != null) {
1215 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001216 scanResult.SSID = ssid;
1217 scanResult.capabilities = flags;
1218 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001219 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 // Do not add scan results that have no SSID set
1221 if (0 < ssid.trim().length()) {
1222 scanResult =
1223 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001224 ssid, bssid, flags, level, frequency);
1225 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001228 } else {
1229 Log.w(TAG, "Misformatted scan result text with " +
1230 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232 }
1233 }
1234
1235 return scanResult;
1236 }
1237
1238 /**
1239 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1240 * and construct a {@code WifiConfiguration} that describes the encryption,
1241 * key management, and authenticaion capabilities of the access point.
1242 * @param flags the string returned by wpa_supplicant
1243 * @return the {@link WifiConfiguration} object, filled in
1244 */
1245 WifiConfiguration parseScanFlags(String flags) {
1246 WifiConfiguration config = new WifiConfiguration();
1247
1248 if (flags.length() == 0) {
1249 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1250 }
1251 // ... to be implemented
1252 return config;
1253 }
1254
1255 /**
1256 * Tell the supplicant to persist the current list of configured networks.
1257 * @return {@code true} if the operation succeeded
1258 */
1259 public boolean saveConfiguration() {
1260 boolean result;
1261 enforceChangePermission();
1262 synchronized (mWifiStateTracker) {
1263 result = WifiNative.saveConfigCommand();
1264 if (result && mNeedReconfig) {
1265 mNeedReconfig = false;
1266 result = WifiNative.reloadConfigCommand();
1267
1268 if (result) {
1269 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1270 mContext.sendBroadcast(intent);
1271 }
1272 }
1273 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001274 // Inform the backup manager about a data change
1275 IBackupManager ibm = IBackupManager.Stub.asInterface(
1276 ServiceManager.getService(Context.BACKUP_SERVICE));
1277 if (ibm != null) {
1278 try {
1279 ibm.dataChanged("com.android.providers.settings");
1280 } catch (Exception e) {
1281 // Try again later
1282 }
1283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 return result;
1285 }
1286
1287 /**
1288 * Set the number of radio frequency channels that are allowed to be used
1289 * in the current regulatory domain. This method should be used only
1290 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001291 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * persisted as a Secure setting.
1293 * @param numChannels the number of allowed channels. Must be greater than 0
1294 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001295 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1297 * {@code numChannels} is outside the valid range.
1298 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001299 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1300 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1301 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 enforceChangePermission();
1303 /*
1304 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1305 * but if Wi-Fi isn't currently enabled, that's not possible, and
1306 * we want to persist the setting anyway,so that it will take
1307 * effect when Wi-Fi does become enabled.
1308 */
1309 boolean found = false;
1310 for (int validChan : sValidRegulatoryChannelCounts) {
1311 if (validChan == numChannels) {
1312 found = true;
1313 break;
1314 }
1315 }
1316 if (!found) {
1317 return false;
1318 }
1319
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001320 if (persist) {
1321 Settings.Secure.putInt(mContext.getContentResolver(),
1322 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1323 numChannels);
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 mWifiStateTracker.setNumAllowedChannels(numChannels);
1326 return true;
1327 }
1328
1329 /**
1330 * Return the number of frequency channels that are allowed
1331 * to be used in the current regulatory domain.
1332 * @return the number of allowed channels, or {@code -1} if an error occurs
1333 */
1334 public int getNumAllowedChannels() {
1335 int numChannels;
1336
1337 enforceAccessPermission();
1338 synchronized (mWifiStateTracker) {
1339 /*
1340 * If we can't get the value from the driver (e.g., because
1341 * Wi-Fi is not currently enabled), get the value from
1342 * Settings.
1343 */
1344 numChannels = WifiNative.getNumAllowedChannelsCommand();
1345 if (numChannels < 0) {
1346 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1347 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1348 -1);
1349 }
1350 }
1351 return numChannels;
1352 }
1353
1354 /**
1355 * Return the list of valid values for the number of allowed radio channels
1356 * for various regulatory domains.
1357 * @return the list of channel counts
1358 */
1359 public int[] getValidChannelCounts() {
1360 enforceAccessPermission();
1361 return sValidRegulatoryChannelCounts;
1362 }
1363
1364 /**
1365 * Return the DHCP-assigned addresses from the last successful DHCP request,
1366 * if any.
1367 * @return the DHCP information
1368 */
1369 public DhcpInfo getDhcpInfo() {
1370 enforceAccessPermission();
1371 return mWifiStateTracker.getDhcpInfo();
1372 }
1373
1374 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1375 @Override
1376 public void onReceive(Context context, Intent intent) {
1377 String action = intent.getAction();
1378
1379 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1380 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1381 int stayAwakeConditions =
1382 Settings.System.getInt(mContext.getContentResolver(),
1383 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1384 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001385 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 mAlarmManager.cancel(mIdleIntent);
1387 mDeviceIdle = false;
1388 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001389 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001391 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001393 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 /*
1395 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1396 * AND the "stay on while plugged in" setting doesn't match the
1397 * current power conditions (i.e, not plugged in, plugged in to USB,
1398 * or plugged in to AC).
1399 */
1400 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001401 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1402 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1403 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001404 mDeviceIdle = true;
1405 updateWifiState();
1406 } else {
1407 long triggerTime = System.currentTimeMillis() + idleMillis;
1408 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1409 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412 /* we can return now -- there's nothing to do until we get the idle intent back */
1413 return;
1414 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001415 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 mDeviceIdle = true;
1417 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1418 /*
1419 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1420 * AND we are transitioning from a state in which the device was supposed
1421 * to stay awake to a state in which it is not supposed to stay awake.
1422 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1423 * the already-set timer.
1424 */
1425 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001426 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1428 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1429 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001430 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1432 mPluggedType = pluggedType;
1433 return;
1434 }
1435 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001436 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1437 boolean isBluetoothPlaying =
1438 intent.getIntExtra(
1439 BluetoothA2dp.SINK_STATE,
1440 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1441 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 } else {
1443 return;
1444 }
1445
1446 updateWifiState();
1447 }
1448
1449 /**
1450 * Determines whether the Wi-Fi chipset should stay awake or be put to
1451 * sleep. Looks at the setting for the sleep policy and the current
1452 * conditions.
1453 *
1454 * @see #shouldDeviceStayAwake(int, int)
1455 */
1456 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1457 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1458 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1459
1460 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1461 // Never sleep
1462 return true;
1463 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1464 (pluggedType != 0)) {
1465 // Never sleep while plugged, and we're plugged
1466 return true;
1467 } else {
1468 // Default
1469 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1470 }
1471 }
1472
1473 /**
1474 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1475 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1476 * of {@code 0} isn't really a plugged type, but rather an indication that the
1477 * device isn't plugged in at all, there is no bit value corresponding to a
1478 * {@code pluggedType} value of {@code 0}. That is why we shift by
1479 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1480 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1481 * keep the device (and hence Wi-Fi) awake.
1482 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1483 * being made
1484 * @return {@code true} if {@code pluggedType} indicates that the device is
1485 * supposed to stay awake, {@code false} otherwise.
1486 */
1487 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1488 return (stayAwakeConditions & pluggedType) != 0;
1489 }
1490 };
1491
Dianne Hackborn617f8772009-03-31 15:04:46 -07001492 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 Message msg = Message.obtain(mWifiHandler,
1494 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001495 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 msg.sendToTarget();
1497 }
1498
1499 private void sendStartMessage(boolean scanOnlyMode) {
1500 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1501 }
1502
1503 private void updateWifiState() {
1504 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001505 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 boolean lockHeld = mLocks.hasLocks();
1507 int strongestLockMode;
1508 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1509 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1510 if (mDeviceIdle && lockHeld) {
1511 strongestLockMode = mLocks.getStrongestLockMode();
1512 } else {
1513 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1514 }
1515
1516 synchronized (mWifiHandler) {
1517 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1518 return;
1519 }
1520 if (wifiShouldBeEnabled) {
1521 if (wifiShouldBeStarted) {
1522 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001523 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 sWakeLock.acquire();
1525 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1526 } else {
1527 int wakeLockTimeout =
1528 Settings.Secure.getInt(
1529 mContext.getContentResolver(),
1530 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1531 DEFAULT_WAKELOCK_TIMEOUT);
1532 /*
1533 * The following wakelock is held in order to ensure
1534 * that the connectivity manager has time to fail over
1535 * to the mobile data network. The connectivity manager
1536 * releases it once mobile data connectivity has been
1537 * established. If connectivity cannot be established,
1538 * the wakelock is released after wakeLockTimeout
1539 * milliseconds have elapsed.
1540 */
1541 sDriverStopWakeLock.acquire();
1542 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1543 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1544 }
1545 } else {
1546 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001547 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 }
1550 }
1551
1552 private void registerForBroadcasts() {
1553 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1555 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1556 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1557 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001558 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 mContext.registerReceiver(mReceiver, intentFilter);
1560 }
1561
1562 private boolean isAirplaneSensitive() {
1563 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1564 Settings.System.AIRPLANE_MODE_RADIOS);
1565 return airplaneModeRadios == null
1566 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1567 }
1568
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001569 private boolean isAirplaneToggleable() {
1570 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1571 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1572 return toggleableRadios != null
1573 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 /**
1577 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1578 * currently on.
1579 * @return {@code true} if airplane mode is on.
1580 */
1581 private boolean isAirplaneModeOn() {
1582 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1583 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1584 }
1585
1586 /**
1587 * Handler that allows posting to the WifiThread.
1588 */
1589 private class WifiHandler extends Handler {
1590 public WifiHandler(Looper looper) {
1591 super(looper);
1592 }
1593
1594 @Override
1595 public void handleMessage(Message msg) {
1596 switch (msg.what) {
1597
1598 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001599 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 sWakeLock.release();
1601 break;
1602
1603 case MESSAGE_START_WIFI:
1604 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1605 mWifiStateTracker.restart();
1606 sWakeLock.release();
1607 break;
1608
1609 case MESSAGE_DISABLE_WIFI:
1610 // a non-zero msg.arg1 value means the "enabled" setting
1611 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001612 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 sWakeLock.release();
1614 break;
1615
1616 case MESSAGE_STOP_WIFI:
1617 mWifiStateTracker.disconnectAndStop();
1618 // don't release wakelock
1619 break;
1620
1621 case MESSAGE_RELEASE_WAKELOCK:
1622 synchronized (sDriverStopWakeLock) {
1623 if (sDriverStopWakeLock.isHeld()) {
1624 sDriverStopWakeLock.release();
1625 }
1626 }
1627 break;
1628 }
1629 }
1630 }
1631
1632 @Override
1633 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1634 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1635 != PackageManager.PERMISSION_GRANTED) {
1636 pw.println("Permission Denial: can't dump WifiService from from pid="
1637 + Binder.getCallingPid()
1638 + ", uid=" + Binder.getCallingUid());
1639 return;
1640 }
1641 pw.println("Wi-Fi is " + stateName(mWifiState));
1642 pw.println("Stay-awake conditions: " +
1643 Settings.System.getInt(mContext.getContentResolver(),
1644 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1645 pw.println();
1646
1647 pw.println("Internal state:");
1648 pw.println(mWifiStateTracker);
1649 pw.println();
1650 pw.println("Latest scan results:");
1651 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1652 if (scanResults != null && scanResults.size() != 0) {
1653 pw.println(" BSSID Frequency RSSI Flags SSID");
1654 for (ScanResult r : scanResults) {
1655 pw.printf(" %17s %9d %5d %-16s %s%n",
1656 r.BSSID,
1657 r.frequency,
1658 r.level,
1659 r.capabilities,
1660 r.SSID == null ? "" : r.SSID);
1661 }
1662 }
1663 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001664 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1665 mScanLocksAcquired + " scan");
1666 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1667 mScanLocksReleased + " scan");
1668 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 pw.println("Locks held:");
1670 mLocks.dump(pw);
1671 }
1672
1673 private static String stateName(int wifiState) {
1674 switch (wifiState) {
1675 case WIFI_STATE_DISABLING:
1676 return "disabling";
1677 case WIFI_STATE_DISABLED:
1678 return "disabled";
1679 case WIFI_STATE_ENABLING:
1680 return "enabling";
1681 case WIFI_STATE_ENABLED:
1682 return "enabled";
1683 case WIFI_STATE_UNKNOWN:
1684 return "unknown state";
1685 default:
1686 return "[invalid state]";
1687 }
1688 }
1689
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001690 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001692 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
1695 public void binderDied() {
1696 synchronized (mLocks) {
1697 releaseWifiLockLocked(mBinder);
1698 }
1699 }
1700
1701 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001702 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704 }
1705
1706 private class LockList {
1707 private List<WifiLock> mList;
1708
1709 private LockList() {
1710 mList = new ArrayList<WifiLock>();
1711 }
1712
1713 private synchronized boolean hasLocks() {
1714 return !mList.isEmpty();
1715 }
1716
1717 private synchronized int getStrongestLockMode() {
1718 if (mList.isEmpty()) {
1719 return WifiManager.WIFI_MODE_FULL;
1720 }
1721 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001722 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 return WifiManager.WIFI_MODE_FULL;
1724 }
1725 }
1726 return WifiManager.WIFI_MODE_SCAN_ONLY;
1727 }
1728
1729 private void addLock(WifiLock lock) {
1730 if (findLockByBinder(lock.mBinder) < 0) {
1731 mList.add(lock);
1732 }
1733 }
1734
1735 private WifiLock removeLock(IBinder binder) {
1736 int index = findLockByBinder(binder);
1737 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001738 WifiLock ret = mList.remove(index);
1739 ret.unlinkDeathRecipient();
1740 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 } else {
1742 return null;
1743 }
1744 }
1745
1746 private int findLockByBinder(IBinder binder) {
1747 int size = mList.size();
1748 for (int i = size - 1; i >= 0; i--)
1749 if (mList.get(i).mBinder == binder)
1750 return i;
1751 return -1;
1752 }
1753
1754 private void dump(PrintWriter pw) {
1755 for (WifiLock l : mList) {
1756 pw.print(" ");
1757 pw.println(l);
1758 }
1759 }
1760 }
1761
1762 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1764 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1765 return false;
1766 }
1767 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1768 synchronized (mLocks) {
1769 return acquireWifiLockLocked(wifiLock);
1770 }
1771 }
1772
1773 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1774 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001775
1776 int uid = Binder.getCallingUid();
1777 long ident = Binder.clearCallingIdentity();
1778 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001779 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001780 case WifiManager.WIFI_MODE_FULL:
1781 ++mFullLocksAcquired;
1782 mBatteryStats.noteFullWifiLockAcquired(uid);
1783 break;
1784 case WifiManager.WIFI_MODE_SCAN_ONLY:
1785 ++mScanLocksAcquired;
1786 mBatteryStats.noteScanWifiLockAcquired(uid);
1787 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001788 }
1789 } catch (RemoteException e) {
1790 } finally {
1791 Binder.restoreCallingIdentity(ident);
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 updateWifiState();
1795 return true;
1796 }
1797
1798 public boolean releaseWifiLock(IBinder lock) {
1799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1800 synchronized (mLocks) {
1801 return releaseWifiLockLocked(lock);
1802 }
1803 }
1804
1805 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001806 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001807
1808 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001809 hadLock = (wifiLock != null);
1810
1811 if (hadLock) {
1812 int uid = Binder.getCallingUid();
1813 long ident = Binder.clearCallingIdentity();
1814 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001815 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001816 case WifiManager.WIFI_MODE_FULL:
1817 ++mFullLocksReleased;
1818 mBatteryStats.noteFullWifiLockReleased(uid);
1819 break;
1820 case WifiManager.WIFI_MODE_SCAN_ONLY:
1821 ++mScanLocksReleased;
1822 mBatteryStats.noteScanWifiLockReleased(uid);
1823 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001824 }
1825 } catch (RemoteException e) {
1826 } finally {
1827 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001828 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001832 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001834
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001835 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001836 implements IBinder.DeathRecipient {
1837 String mTag;
1838 int mMode;
1839 IBinder mBinder;
1840
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001841 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001842 super();
1843 mTag = tag;
1844 mMode = mode;
1845 mBinder = binder;
1846 try {
1847 mBinder.linkToDeath(this, 0);
1848 } catch (RemoteException e) {
1849 binderDied();
1850 }
1851 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001852
1853 void unlinkDeathRecipient() {
1854 mBinder.unlinkToDeath(this, 0);
1855 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001856 }
1857
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001858 private class Multicaster extends DeathRecipient {
1859 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001860 super(Binder.getCallingUid(), tag, binder);
1861 }
1862
1863 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001864 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001865 synchronized (mMulticasters) {
1866 int i = mMulticasters.indexOf(this);
1867 if (i != -1) {
1868 removeMulticasterLocked(i, mMode);
1869 }
1870 }
1871 }
1872
1873 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001874 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001875 }
1876
1877 public int getUid() {
1878 return mMode;
1879 }
1880 }
1881
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001882 public void acquireMulticastLock(IBinder binder, String tag) {
1883 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001884
1885 synchronized (mMulticasters) {
1886 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001887 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001888 // Note that we could call stopPacketFiltering only when
1889 // our new size == 1 (first call), but this function won't
1890 // be called often and by making the stopPacket call each
1891 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001892 synchronized (mWifiStateTracker) {
1893 WifiNative.stopPacketFiltering();
1894 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001895 }
1896
1897 int uid = Binder.getCallingUid();
1898 Long ident = Binder.clearCallingIdentity();
1899 try {
1900 mBatteryStats.noteWifiMulticastEnabled(uid);
1901 } catch (RemoteException e) {
1902 } finally {
1903 Binder.restoreCallingIdentity(ident);
1904 }
1905 }
1906
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001907 public void releaseMulticastLock() {
1908 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001909
1910 int uid = Binder.getCallingUid();
1911 synchronized (mMulticasters) {
1912 mMulticastDisabled++;
1913 int size = mMulticasters.size();
1914 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001915 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001916 if ((m != null) && (m.getUid() == uid)) {
1917 removeMulticasterLocked(i, uid);
1918 }
1919 }
1920 }
1921 }
1922
1923 private void removeMulticasterLocked(int i, int uid)
1924 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001925 Multicaster removed = mMulticasters.remove(i);
1926 if (removed != null) {
1927 removed.unlinkDeathRecipient();
1928 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001929 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001930 synchronized (mWifiStateTracker) {
1931 WifiNative.startPacketFiltering();
1932 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001933 }
1934
1935 Long ident = Binder.clearCallingIdentity();
1936 try {
1937 mBatteryStats.noteWifiMulticastDisabled(uid);
1938 } catch (RemoteException e) {
1939 } finally {
1940 Binder.restoreCallingIdentity(ident);
1941 }
1942 }
1943
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001944 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001945 enforceAccessPermission();
1946
1947 synchronized (mMulticasters) {
1948 return (mMulticasters.size() > 0);
1949 }
1950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951}