blob: 2dc747ea6914be9995fe05ea488d3cc2d109bd9f [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 Lockwood00717e22009-08-17 10:09:36 -04001212 // bssid + ssid is the hash key
1213 String key = bssid + ssid;
1214 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001215 if (scanResult != null) {
1216 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001217 scanResult.SSID = ssid;
1218 scanResult.capabilities = flags;
1219 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001220 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 // Do not add scan results that have no SSID set
1222 if (0 < ssid.trim().length()) {
1223 scanResult =
1224 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001225 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001226 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001229 } else {
1230 Log.w(TAG, "Misformatted scan result text with " +
1231 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234 }
1235
1236 return scanResult;
1237 }
1238
1239 /**
1240 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1241 * and construct a {@code WifiConfiguration} that describes the encryption,
1242 * key management, and authenticaion capabilities of the access point.
1243 * @param flags the string returned by wpa_supplicant
1244 * @return the {@link WifiConfiguration} object, filled in
1245 */
1246 WifiConfiguration parseScanFlags(String flags) {
1247 WifiConfiguration config = new WifiConfiguration();
1248
1249 if (flags.length() == 0) {
1250 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1251 }
1252 // ... to be implemented
1253 return config;
1254 }
1255
1256 /**
1257 * Tell the supplicant to persist the current list of configured networks.
1258 * @return {@code true} if the operation succeeded
1259 */
1260 public boolean saveConfiguration() {
1261 boolean result;
1262 enforceChangePermission();
1263 synchronized (mWifiStateTracker) {
1264 result = WifiNative.saveConfigCommand();
1265 if (result && mNeedReconfig) {
1266 mNeedReconfig = false;
1267 result = WifiNative.reloadConfigCommand();
1268
1269 if (result) {
1270 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1271 mContext.sendBroadcast(intent);
1272 }
1273 }
1274 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001275 // Inform the backup manager about a data change
1276 IBackupManager ibm = IBackupManager.Stub.asInterface(
1277 ServiceManager.getService(Context.BACKUP_SERVICE));
1278 if (ibm != null) {
1279 try {
1280 ibm.dataChanged("com.android.providers.settings");
1281 } catch (Exception e) {
1282 // Try again later
1283 }
1284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 return result;
1286 }
1287
1288 /**
1289 * Set the number of radio frequency channels that are allowed to be used
1290 * in the current regulatory domain. This method should be used only
1291 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001292 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 * persisted as a Secure setting.
1294 * @param numChannels the number of allowed channels. Must be greater than 0
1295 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001296 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1298 * {@code numChannels} is outside the valid range.
1299 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001300 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1301 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1302 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 enforceChangePermission();
1304 /*
1305 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1306 * but if Wi-Fi isn't currently enabled, that's not possible, and
1307 * we want to persist the setting anyway,so that it will take
1308 * effect when Wi-Fi does become enabled.
1309 */
1310 boolean found = false;
1311 for (int validChan : sValidRegulatoryChannelCounts) {
1312 if (validChan == numChannels) {
1313 found = true;
1314 break;
1315 }
1316 }
1317 if (!found) {
1318 return false;
1319 }
1320
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001321 if (persist) {
1322 Settings.Secure.putInt(mContext.getContentResolver(),
1323 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1324 numChannels);
1325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 mWifiStateTracker.setNumAllowedChannels(numChannels);
1327 return true;
1328 }
1329
1330 /**
1331 * Return the number of frequency channels that are allowed
1332 * to be used in the current regulatory domain.
1333 * @return the number of allowed channels, or {@code -1} if an error occurs
1334 */
1335 public int getNumAllowedChannels() {
1336 int numChannels;
1337
1338 enforceAccessPermission();
1339 synchronized (mWifiStateTracker) {
1340 /*
1341 * If we can't get the value from the driver (e.g., because
1342 * Wi-Fi is not currently enabled), get the value from
1343 * Settings.
1344 */
1345 numChannels = WifiNative.getNumAllowedChannelsCommand();
1346 if (numChannels < 0) {
1347 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1348 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1349 -1);
1350 }
1351 }
1352 return numChannels;
1353 }
1354
1355 /**
1356 * Return the list of valid values for the number of allowed radio channels
1357 * for various regulatory domains.
1358 * @return the list of channel counts
1359 */
1360 public int[] getValidChannelCounts() {
1361 enforceAccessPermission();
1362 return sValidRegulatoryChannelCounts;
1363 }
1364
1365 /**
1366 * Return the DHCP-assigned addresses from the last successful DHCP request,
1367 * if any.
1368 * @return the DHCP information
1369 */
1370 public DhcpInfo getDhcpInfo() {
1371 enforceAccessPermission();
1372 return mWifiStateTracker.getDhcpInfo();
1373 }
1374
1375 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1376 @Override
1377 public void onReceive(Context context, Intent intent) {
1378 String action = intent.getAction();
1379
1380 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1381 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1382 int stayAwakeConditions =
1383 Settings.System.getInt(mContext.getContentResolver(),
1384 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1385 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001386 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 mAlarmManager.cancel(mIdleIntent);
1388 mDeviceIdle = false;
1389 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001390 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001392 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001394 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 /*
1396 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1397 * AND the "stay on while plugged in" setting doesn't match the
1398 * current power conditions (i.e, not plugged in, plugged in to USB,
1399 * or plugged in to AC).
1400 */
1401 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001402 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1403 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1404 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001405 mDeviceIdle = true;
1406 updateWifiState();
1407 } else {
1408 long triggerTime = System.currentTimeMillis() + idleMillis;
1409 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1410 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 /* we can return now -- there's nothing to do until we get the idle intent back */
1414 return;
1415 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001416 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 mDeviceIdle = true;
1418 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1419 /*
1420 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1421 * AND we are transitioning from a state in which the device was supposed
1422 * to stay awake to a state in which it is not supposed to stay awake.
1423 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1424 * the already-set timer.
1425 */
1426 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001427 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1429 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1430 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001431 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1433 mPluggedType = pluggedType;
1434 return;
1435 }
1436 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001437 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1438 boolean isBluetoothPlaying =
1439 intent.getIntExtra(
1440 BluetoothA2dp.SINK_STATE,
1441 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1442 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 } else {
1444 return;
1445 }
1446
1447 updateWifiState();
1448 }
1449
1450 /**
1451 * Determines whether the Wi-Fi chipset should stay awake or be put to
1452 * sleep. Looks at the setting for the sleep policy and the current
1453 * conditions.
1454 *
1455 * @see #shouldDeviceStayAwake(int, int)
1456 */
1457 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1458 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1459 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1460
1461 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1462 // Never sleep
1463 return true;
1464 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1465 (pluggedType != 0)) {
1466 // Never sleep while plugged, and we're plugged
1467 return true;
1468 } else {
1469 // Default
1470 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1471 }
1472 }
1473
1474 /**
1475 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1476 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1477 * of {@code 0} isn't really a plugged type, but rather an indication that the
1478 * device isn't plugged in at all, there is no bit value corresponding to a
1479 * {@code pluggedType} value of {@code 0}. That is why we shift by
1480 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1481 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1482 * keep the device (and hence Wi-Fi) awake.
1483 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1484 * being made
1485 * @return {@code true} if {@code pluggedType} indicates that the device is
1486 * supposed to stay awake, {@code false} otherwise.
1487 */
1488 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1489 return (stayAwakeConditions & pluggedType) != 0;
1490 }
1491 };
1492
Dianne Hackborn617f8772009-03-31 15:04:46 -07001493 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 Message msg = Message.obtain(mWifiHandler,
1495 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001496 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 msg.sendToTarget();
1498 }
1499
1500 private void sendStartMessage(boolean scanOnlyMode) {
1501 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1502 }
1503
1504 private void updateWifiState() {
1505 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001506 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 boolean lockHeld = mLocks.hasLocks();
1508 int strongestLockMode;
1509 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1510 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1511 if (mDeviceIdle && lockHeld) {
1512 strongestLockMode = mLocks.getStrongestLockMode();
1513 } else {
1514 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1515 }
1516
1517 synchronized (mWifiHandler) {
1518 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1519 return;
1520 }
1521 if (wifiShouldBeEnabled) {
1522 if (wifiShouldBeStarted) {
1523 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001524 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 sWakeLock.acquire();
1526 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1527 } else {
1528 int wakeLockTimeout =
1529 Settings.Secure.getInt(
1530 mContext.getContentResolver(),
1531 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1532 DEFAULT_WAKELOCK_TIMEOUT);
1533 /*
1534 * The following wakelock is held in order to ensure
1535 * that the connectivity manager has time to fail over
1536 * to the mobile data network. The connectivity manager
1537 * releases it once mobile data connectivity has been
1538 * established. If connectivity cannot be established,
1539 * the wakelock is released after wakeLockTimeout
1540 * milliseconds have elapsed.
1541 */
1542 sDriverStopWakeLock.acquire();
1543 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1544 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1545 }
1546 } else {
1547 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001548 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
1550 }
1551 }
1552
1553 private void registerForBroadcasts() {
1554 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1556 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1557 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1558 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001559 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 mContext.registerReceiver(mReceiver, intentFilter);
1561 }
1562
1563 private boolean isAirplaneSensitive() {
1564 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1565 Settings.System.AIRPLANE_MODE_RADIOS);
1566 return airplaneModeRadios == null
1567 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1568 }
1569
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001570 private boolean isAirplaneToggleable() {
1571 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1572 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1573 return toggleableRadios != null
1574 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1575 }
1576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 /**
1578 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1579 * currently on.
1580 * @return {@code true} if airplane mode is on.
1581 */
1582 private boolean isAirplaneModeOn() {
1583 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1584 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1585 }
1586
1587 /**
1588 * Handler that allows posting to the WifiThread.
1589 */
1590 private class WifiHandler extends Handler {
1591 public WifiHandler(Looper looper) {
1592 super(looper);
1593 }
1594
1595 @Override
1596 public void handleMessage(Message msg) {
1597 switch (msg.what) {
1598
1599 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001600 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 sWakeLock.release();
1602 break;
1603
1604 case MESSAGE_START_WIFI:
1605 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1606 mWifiStateTracker.restart();
1607 sWakeLock.release();
1608 break;
1609
1610 case MESSAGE_DISABLE_WIFI:
1611 // a non-zero msg.arg1 value means the "enabled" setting
1612 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001613 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 sWakeLock.release();
1615 break;
1616
1617 case MESSAGE_STOP_WIFI:
1618 mWifiStateTracker.disconnectAndStop();
1619 // don't release wakelock
1620 break;
1621
1622 case MESSAGE_RELEASE_WAKELOCK:
1623 synchronized (sDriverStopWakeLock) {
1624 if (sDriverStopWakeLock.isHeld()) {
1625 sDriverStopWakeLock.release();
1626 }
1627 }
1628 break;
1629 }
1630 }
1631 }
1632
1633 @Override
1634 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1635 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1636 != PackageManager.PERMISSION_GRANTED) {
1637 pw.println("Permission Denial: can't dump WifiService from from pid="
1638 + Binder.getCallingPid()
1639 + ", uid=" + Binder.getCallingUid());
1640 return;
1641 }
1642 pw.println("Wi-Fi is " + stateName(mWifiState));
1643 pw.println("Stay-awake conditions: " +
1644 Settings.System.getInt(mContext.getContentResolver(),
1645 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1646 pw.println();
1647
1648 pw.println("Internal state:");
1649 pw.println(mWifiStateTracker);
1650 pw.println();
1651 pw.println("Latest scan results:");
1652 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1653 if (scanResults != null && scanResults.size() != 0) {
1654 pw.println(" BSSID Frequency RSSI Flags SSID");
1655 for (ScanResult r : scanResults) {
1656 pw.printf(" %17s %9d %5d %-16s %s%n",
1657 r.BSSID,
1658 r.frequency,
1659 r.level,
1660 r.capabilities,
1661 r.SSID == null ? "" : r.SSID);
1662 }
1663 }
1664 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001665 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1666 mScanLocksAcquired + " scan");
1667 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1668 mScanLocksReleased + " scan");
1669 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 pw.println("Locks held:");
1671 mLocks.dump(pw);
1672 }
1673
1674 private static String stateName(int wifiState) {
1675 switch (wifiState) {
1676 case WIFI_STATE_DISABLING:
1677 return "disabling";
1678 case WIFI_STATE_DISABLED:
1679 return "disabled";
1680 case WIFI_STATE_ENABLING:
1681 return "enabling";
1682 case WIFI_STATE_ENABLED:
1683 return "enabled";
1684 case WIFI_STATE_UNKNOWN:
1685 return "unknown state";
1686 default:
1687 return "[invalid state]";
1688 }
1689 }
1690
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001691 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001693 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695
1696 public void binderDied() {
1697 synchronized (mLocks) {
1698 releaseWifiLockLocked(mBinder);
1699 }
1700 }
1701
1702 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001703 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 }
1706
1707 private class LockList {
1708 private List<WifiLock> mList;
1709
1710 private LockList() {
1711 mList = new ArrayList<WifiLock>();
1712 }
1713
1714 private synchronized boolean hasLocks() {
1715 return !mList.isEmpty();
1716 }
1717
1718 private synchronized int getStrongestLockMode() {
1719 if (mList.isEmpty()) {
1720 return WifiManager.WIFI_MODE_FULL;
1721 }
1722 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001723 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 return WifiManager.WIFI_MODE_FULL;
1725 }
1726 }
1727 return WifiManager.WIFI_MODE_SCAN_ONLY;
1728 }
1729
1730 private void addLock(WifiLock lock) {
1731 if (findLockByBinder(lock.mBinder) < 0) {
1732 mList.add(lock);
1733 }
1734 }
1735
1736 private WifiLock removeLock(IBinder binder) {
1737 int index = findLockByBinder(binder);
1738 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001739 WifiLock ret = mList.remove(index);
1740 ret.unlinkDeathRecipient();
1741 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 } else {
1743 return null;
1744 }
1745 }
1746
1747 private int findLockByBinder(IBinder binder) {
1748 int size = mList.size();
1749 for (int i = size - 1; i >= 0; i--)
1750 if (mList.get(i).mBinder == binder)
1751 return i;
1752 return -1;
1753 }
1754
1755 private void dump(PrintWriter pw) {
1756 for (WifiLock l : mList) {
1757 pw.print(" ");
1758 pw.println(l);
1759 }
1760 }
1761 }
1762
1763 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1765 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1766 return false;
1767 }
1768 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1769 synchronized (mLocks) {
1770 return acquireWifiLockLocked(wifiLock);
1771 }
1772 }
1773
1774 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1775 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001776
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 ++mFullLocksAcquired;
1783 mBatteryStats.noteFullWifiLockAcquired(uid);
1784 break;
1785 case WifiManager.WIFI_MODE_SCAN_ONLY:
1786 ++mScanLocksAcquired;
1787 mBatteryStats.noteScanWifiLockAcquired(uid);
1788 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001789 }
1790 } catch (RemoteException e) {
1791 } finally {
1792 Binder.restoreCallingIdentity(ident);
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 updateWifiState();
1796 return true;
1797 }
1798
1799 public boolean releaseWifiLock(IBinder lock) {
1800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1801 synchronized (mLocks) {
1802 return releaseWifiLockLocked(lock);
1803 }
1804 }
1805
1806 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001807 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001808
1809 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001810 hadLock = (wifiLock != null);
1811
1812 if (hadLock) {
1813 int uid = Binder.getCallingUid();
1814 long ident = Binder.clearCallingIdentity();
1815 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001816 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001817 case WifiManager.WIFI_MODE_FULL:
1818 ++mFullLocksReleased;
1819 mBatteryStats.noteFullWifiLockReleased(uid);
1820 break;
1821 case WifiManager.WIFI_MODE_SCAN_ONLY:
1822 ++mScanLocksReleased;
1823 mBatteryStats.noteScanWifiLockReleased(uid);
1824 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001825 }
1826 } catch (RemoteException e) {
1827 } finally {
1828 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001829 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001833 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001835
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001836 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001837 implements IBinder.DeathRecipient {
1838 String mTag;
1839 int mMode;
1840 IBinder mBinder;
1841
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001842 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001843 super();
1844 mTag = tag;
1845 mMode = mode;
1846 mBinder = binder;
1847 try {
1848 mBinder.linkToDeath(this, 0);
1849 } catch (RemoteException e) {
1850 binderDied();
1851 }
1852 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001853
1854 void unlinkDeathRecipient() {
1855 mBinder.unlinkToDeath(this, 0);
1856 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001857 }
1858
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001859 private class Multicaster extends DeathRecipient {
1860 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001861 super(Binder.getCallingUid(), tag, binder);
1862 }
1863
1864 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001865 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001866 synchronized (mMulticasters) {
1867 int i = mMulticasters.indexOf(this);
1868 if (i != -1) {
1869 removeMulticasterLocked(i, mMode);
1870 }
1871 }
1872 }
1873
1874 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001875 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001876 }
1877
1878 public int getUid() {
1879 return mMode;
1880 }
1881 }
1882
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001883 public void acquireMulticastLock(IBinder binder, String tag) {
1884 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001885
1886 synchronized (mMulticasters) {
1887 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001888 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001889 // Note that we could call stopPacketFiltering only when
1890 // our new size == 1 (first call), but this function won't
1891 // be called often and by making the stopPacket call each
1892 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001893 synchronized (mWifiStateTracker) {
1894 WifiNative.stopPacketFiltering();
1895 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001896 }
1897
1898 int uid = Binder.getCallingUid();
1899 Long ident = Binder.clearCallingIdentity();
1900 try {
1901 mBatteryStats.noteWifiMulticastEnabled(uid);
1902 } catch (RemoteException e) {
1903 } finally {
1904 Binder.restoreCallingIdentity(ident);
1905 }
1906 }
1907
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001908 public void releaseMulticastLock() {
1909 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001910
1911 int uid = Binder.getCallingUid();
1912 synchronized (mMulticasters) {
1913 mMulticastDisabled++;
1914 int size = mMulticasters.size();
1915 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001916 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001917 if ((m != null) && (m.getUid() == uid)) {
1918 removeMulticasterLocked(i, uid);
1919 }
1920 }
1921 }
1922 }
1923
1924 private void removeMulticasterLocked(int i, int uid)
1925 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001926 Multicaster removed = mMulticasters.remove(i);
1927 if (removed != null) {
1928 removed.unlinkDeathRecipient();
1929 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001930 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001931 synchronized (mWifiStateTracker) {
1932 WifiNative.startPacketFiltering();
1933 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001934 }
1935
1936 Long ident = Binder.clearCallingIdentity();
1937 try {
1938 mBatteryStats.noteWifiMulticastDisabled(uid);
1939 } catch (RemoteException e) {
1940 } finally {
1941 Binder.restoreCallingIdentity(ident);
1942 }
1943 }
1944
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001945 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001946 enforceAccessPermission();
1947
1948 synchronized (mMulticasters) {
1949 return (mMulticasters.size() > 0);
1950 }
1951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952}