blob: b29e7693ffae4dda817f1fbc18615b733e47e9d6 [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;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080028import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.BroadcastReceiver;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
35import android.net.wifi.IWifiManager;
36import android.net.wifi.WifiInfo;
37import android.net.wifi.WifiManager;
38import android.net.wifi.WifiNative;
39import android.net.wifi.WifiStateTracker;
40import android.net.wifi.ScanResult;
41import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070042import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.NetworkStateTracker;
44import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040045import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Binder;
47import android.os.Handler;
48import android.os.HandlerThread;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070053import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070055import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
57import android.util.Log;
58import android.text.TextUtils;
59
60import java.util.ArrayList;
61import java.util.BitSet;
62import java.util.HashMap;
63import java.util.LinkedHashMap;
64import java.util.List;
65import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080066import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.regex.Pattern;
68import java.io.FileDescriptor;
69import java.io.PrintWriter;
70
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.internal.app.IBatteryStats;
Amith Yamasani47873e52009-07-02 12:05:32 -070072import android.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070073import com.android.server.am.BatteryStatsService;
74
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075/**
76 * WifiService handles remote WiFi operation requests by implementing
77 * the IWifiManager interface. It also creates a WifiMonitor to listen
78 * for Wifi-related events.
79 *
80 * @hide
81 */
82public class WifiService extends IWifiManager.Stub {
83 private static final String TAG = "WifiService";
84 private static final boolean DBG = false;
85 private static final Pattern scanResultPattern = Pattern.compile("\t+");
86 private final WifiStateTracker mWifiStateTracker;
87
88 private Context mContext;
89 private int mWifiState;
90
91 private AlarmManager mAlarmManager;
92 private PendingIntent mIdleIntent;
93 private static final int IDLE_REQUEST = 0;
94 private boolean mScreenOff;
95 private boolean mDeviceIdle;
96 private int mPluggedType;
97
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070098 // true if the user enabled Wifi while in airplane mode
99 private boolean mAirplaneModeOverwridden;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700102 // some wifi lock statistics
103 private int mFullLocksAcquired;
104 private int mFullLocksReleased;
105 private int mScanLocksAcquired;
106 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700107
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700108 private final List<Multicaster> mMulticasters =
109 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700110 private int mMulticastEnabled;
111 private int mMulticastDisabled;
112
The Android Open Source Project10592532009-03-18 17:39:46 -0700113 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 /**
116 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
117 * Settings.Gservices value is not present. This timeout value is chosen as
118 * the approximate point at which the battery drain caused by Wi-Fi
119 * being enabled but not active exceeds the battery drain caused by
120 * re-establishing a connection to the mobile data network.
121 */
122 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
123
124 private static final String WAKELOCK_TAG = "WifiService";
125
126 /**
127 * The maximum amount of time to hold the wake lock after a disconnect
128 * caused by stopping the driver. Establishing an EDGE connection has been
129 * observed to take about 5 seconds under normal circumstances. This
130 * provides a bit of extra margin.
131 * <p>
132 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
133 * This is the default value if a Settings.Secure value is not present.
134 */
135 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
136
137 // Wake lock used by driver-stop operation
138 private static PowerManager.WakeLock sDriverStopWakeLock;
139 // Wake lock used by other operations
140 private static PowerManager.WakeLock sWakeLock;
141
142 private static final int MESSAGE_ENABLE_WIFI = 0;
143 private static final int MESSAGE_DISABLE_WIFI = 1;
144 private static final int MESSAGE_STOP_WIFI = 2;
145 private static final int MESSAGE_START_WIFI = 3;
146 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
147
148 private final WifiHandler mWifiHandler;
149
150 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 * Cache of scan results objects (size is somewhat arbitrary)
152 */
153 private static final int SCAN_RESULT_CACHE_SIZE = 80;
154 private final LinkedHashMap<String, ScanResult> mScanResultCache;
155
156 /*
157 * Character buffer used to parse scan results (optimization)
158 */
159 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private boolean mNeedReconfig;
161
Dianne Hackborn617f8772009-03-31 15:04:46 -0700162 /*
163 * Last UID that asked to enable WIFI.
164 */
165 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Number of allowed radio frequency channels in various regulatory domains.
169 * This list is sufficient for 802.11b/g networks (2.4GHz range).
170 */
171 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
172
173 private static final String ACTION_DEVICE_IDLE =
174 "com.android.server.WifiManager.action.DEVICE_IDLE";
175
176 WifiService(Context context, WifiStateTracker tracker) {
177 mContext = context;
178 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400179 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700180 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 mScanResultCache = new LinkedHashMap<String, ScanResult>(
183 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
184 /*
185 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
186 * elements
187 */
188 public boolean removeEldestEntry(Map.Entry eldest) {
189 return SCAN_RESULT_CACHE_SIZE < this.size();
190 }
191 };
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 HandlerThread wifiThread = new HandlerThread("WifiService");
194 wifiThread.start();
195 mWifiHandler = new WifiHandler(wifiThread.getLooper());
196
197 mWifiState = WIFI_STATE_DISABLED;
198 boolean wifiEnabled = getPersistedWifiEnabled();
199
200 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
201 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
202 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
203
204 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
205 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
206 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
207 mWifiStateTracker.setReleaseWakeLockCallback(
208 new Runnable() {
209 public void run() {
210 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
211 synchronized (sDriverStopWakeLock) {
212 if (sDriverStopWakeLock.isHeld()) {
213 sDriverStopWakeLock.release();
214 }
215 }
216 }
217 }
218 );
219
220 Log.i(TAG, "WifiService starting up with Wi-Fi " +
221 (wifiEnabled ? "enabled" : "disabled"));
222
223 mContext.registerReceiver(
224 new BroadcastReceiver() {
225 @Override
226 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700227 // clear our flag indicating the user has overwridden airplane mode
228 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 updateWifiState();
230 }
231 },
232 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
233
Dianne Hackborn617f8772009-03-31 15:04:46 -0700234 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 }
236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 private boolean getPersistedWifiEnabled() {
238 final ContentResolver cr = mContext.getContentResolver();
239 try {
240 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
241 } catch (Settings.SettingNotFoundException e) {
242 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
243 return false;
244 }
245 }
246
247 private void persistWifiEnabled(boolean enabled) {
248 final ContentResolver cr = mContext.getContentResolver();
249 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
250 }
251
252 NetworkStateTracker getNetworkStateTracker() {
253 return mWifiStateTracker;
254 }
255
256 /**
257 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
258 * @return {@code true} if the operation succeeds
259 */
260 public boolean pingSupplicant() {
261 enforceChangePermission();
262 synchronized (mWifiStateTracker) {
263 return WifiNative.pingCommand();
264 }
265 }
266
267 /**
268 * see {@link android.net.wifi.WifiManager#startScan()}
269 * @return {@code true} if the operation succeeds
270 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400271 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 enforceChangePermission();
273 synchronized (mWifiStateTracker) {
274 switch (mWifiStateTracker.getSupplicantState()) {
275 case DISCONNECTED:
276 case INACTIVE:
277 case SCANNING:
278 case DORMANT:
279 break;
280 default:
281 WifiNative.setScanResultHandlingCommand(
282 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
283 break;
284 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400285 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287 }
288
289 /**
290 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
291 * @param enable {@code true} to enable, {@code false} to disable.
292 * @return {@code true} if the enable/disable operation was
293 * started or is already in the queue.
294 */
295 public boolean setWifiEnabled(boolean enable) {
296 enforceChangePermission();
297 if (mWifiHandler == null) return false;
298
299 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700300 // caller may not have WAKE_LOCK permission - it's not required here
301 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700303 Binder.restoreCallingIdentity(ident);
304
Dianne Hackborn617f8772009-03-31 15:04:46 -0700305 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700306 // set a flag if the user is enabling Wifi while in airplane mode
307 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700308 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 }
310
311 return true;
312 }
313
314 /**
315 * Enables/disables Wi-Fi synchronously.
316 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
317 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700318 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * @return {@code true} if the operation succeeds (or if the existing state
320 * is the same as the requested state)
321 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700322 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
324
325 if (mWifiState == eventualWifiState) {
326 return true;
327 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700328 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 return false;
330 }
331
Dianne Hackborn617f8772009-03-31 15:04:46 -0700332 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333
334 if (enable) {
335 if (!WifiNative.loadDriver()) {
336 Log.e(TAG, "Failed to load Wi-Fi driver.");
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 if (!WifiNative.startSupplicant()) {
341 WifiNative.unloadDriver();
342 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700343 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 return false;
345 }
346 registerForBroadcasts();
347 mWifiStateTracker.startEventLoop();
348 } else {
349
350 mContext.unregisterReceiver(mReceiver);
351 // Remove notification (it will no-op if it isn't visible)
352 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
353
354 boolean failedToStopSupplicantOrUnloadDriver = false;
355 if (!WifiNative.stopSupplicant()) {
356 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700357 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 failedToStopSupplicantOrUnloadDriver = true;
359 }
360
361 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400362 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
364 if (!WifiNative.unloadDriver()) {
365 Log.e(TAG, "Failed to unload Wi-Fi driver.");
366 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700367 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 failedToStopSupplicantOrUnloadDriver = true;
369 }
370 }
371 if (failedToStopSupplicantOrUnloadDriver) {
372 return false;
373 }
374 }
375
376 // Success!
377
378 if (persist) {
379 persistWifiEnabled(enable);
380 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700381 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 return true;
384 }
385
Dianne Hackborn617f8772009-03-31 15:04:46 -0700386 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 final int previousWifiState = mWifiState;
388
The Android Open Source Project10592532009-03-18 17:39:46 -0700389 long ident = Binder.clearCallingIdentity();
390 try {
391 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700392 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700393 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700394 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700395 }
396 } catch (RemoteException e) {
397 } finally {
398 Binder.restoreCallingIdentity(ident);
399 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 // Update state
402 mWifiState = wifiState;
403
404 // Broadcast
405 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
406 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
407 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
408 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
409 mContext.sendStickyBroadcast(intent);
410 }
411
412 private void enforceAccessPermission() {
413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
414 "WifiService");
415 }
416
417 private void enforceChangePermission() {
418 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
419 "WifiService");
420
421 }
422
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700423 private void enforceMulticastChangePermission() {
424 mContext.enforceCallingOrSelfPermission(
425 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
426 "WifiService");
427 }
428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 /**
430 * see {@link WifiManager#getWifiState()}
431 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
432 * {@link WifiManager#WIFI_STATE_DISABLING},
433 * {@link WifiManager#WIFI_STATE_ENABLED},
434 * {@link WifiManager#WIFI_STATE_ENABLING},
435 * {@link WifiManager#WIFI_STATE_UNKNOWN}
436 */
437 public int getWifiEnabledState() {
438 enforceAccessPermission();
439 return mWifiState;
440 }
441
442 /**
443 * see {@link android.net.wifi.WifiManager#disconnect()}
444 * @return {@code true} if the operation succeeds
445 */
446 public boolean disconnect() {
447 enforceChangePermission();
448 synchronized (mWifiStateTracker) {
449 return WifiNative.disconnectCommand();
450 }
451 }
452
453 /**
454 * see {@link android.net.wifi.WifiManager#reconnect()}
455 * @return {@code true} if the operation succeeds
456 */
457 public boolean reconnect() {
458 enforceChangePermission();
459 synchronized (mWifiStateTracker) {
460 return WifiNative.reconnectCommand();
461 }
462 }
463
464 /**
465 * see {@link android.net.wifi.WifiManager#reassociate()}
466 * @return {@code true} if the operation succeeds
467 */
468 public boolean reassociate() {
469 enforceChangePermission();
470 synchronized (mWifiStateTracker) {
471 return WifiNative.reassociateCommand();
472 }
473 }
474
475 /**
476 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
477 * @return the list of configured networks
478 */
479 public List<WifiConfiguration> getConfiguredNetworks() {
480 enforceAccessPermission();
481 String listStr;
482 /*
483 * We don't cache the list, because we want to allow
484 * for the possibility that the configuration file
485 * has been modified through some external means,
486 * such as the wpa_cli command line program.
487 */
488 synchronized (mWifiStateTracker) {
489 listStr = WifiNative.listNetworksCommand();
490 }
491 List<WifiConfiguration> networks =
492 new ArrayList<WifiConfiguration>();
493 if (listStr == null)
494 return networks;
495
496 String[] lines = listStr.split("\n");
497 // Skip the first line, which is a header
498 for (int i = 1; i < lines.length; i++) {
499 String[] result = lines[i].split("\t");
500 // network-id | ssid | bssid | flags
501 WifiConfiguration config = new WifiConfiguration();
502 try {
503 config.networkId = Integer.parseInt(result[0]);
504 } catch(NumberFormatException e) {
505 continue;
506 }
507 if (result.length > 3) {
508 if (result[3].indexOf("[CURRENT]") != -1)
509 config.status = WifiConfiguration.Status.CURRENT;
510 else if (result[3].indexOf("[DISABLED]") != -1)
511 config.status = WifiConfiguration.Status.DISABLED;
512 else
513 config.status = WifiConfiguration.Status.ENABLED;
514 } else
515 config.status = WifiConfiguration.Status.ENABLED;
516 synchronized (mWifiStateTracker) {
517 readNetworkVariables(config);
518 }
519 networks.add(config);
520 }
521
522 return networks;
523 }
524
525 /**
526 * Read the variables from the supplicant daemon that are needed to
527 * fill in the WifiConfiguration object.
528 * <p/>
529 * The caller must hold the synchronization monitor.
530 * @param config the {@link WifiConfiguration} object to be filled in.
531 */
532 private static void readNetworkVariables(WifiConfiguration config) {
533
534 int netId = config.networkId;
535 if (netId < 0)
536 return;
537
538 /*
539 * TODO: maybe should have a native method that takes an array of
540 * variable names and returns an array of values. But we'd still
541 * be doing a round trip to the supplicant daemon for each variable.
542 */
543 String value;
544
545 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
546 if (!TextUtils.isEmpty(value)) {
547 config.SSID = value;
548 } else {
549 config.SSID = null;
550 }
551
552 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
553 if (!TextUtils.isEmpty(value)) {
554 config.BSSID = value;
555 } else {
556 config.BSSID = null;
557 }
558
559 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
560 config.priority = -1;
561 if (!TextUtils.isEmpty(value)) {
562 try {
563 config.priority = Integer.parseInt(value);
564 } catch (NumberFormatException ignore) {
565 }
566 }
567
568 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
569 config.hiddenSSID = false;
570 if (!TextUtils.isEmpty(value)) {
571 try {
572 config.hiddenSSID = Integer.parseInt(value) != 0;
573 } catch (NumberFormatException ignore) {
574 }
575 }
576
577 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
578 config.wepTxKeyIndex = -1;
579 if (!TextUtils.isEmpty(value)) {
580 try {
581 config.wepTxKeyIndex = Integer.parseInt(value);
582 } catch (NumberFormatException ignore) {
583 }
584 }
585
586 /*
587 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
588 * just a "*" if the key is set, or the null string otherwise.
589 */
590 for (int i = 0; i < 4; i++) {
591 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
592 if (!TextUtils.isEmpty(value)) {
593 config.wepKeys[i] = value;
594 } else {
595 config.wepKeys[i] = null;
596 }
597 }
598
599 /*
600 * Get the private shared key. Note that the actual keys are not passed back,
601 * just a "*" if the key is set, or the null string otherwise.
602 */
603 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
604 if (!TextUtils.isEmpty(value)) {
605 config.preSharedKey = value;
606 } else {
607 config.preSharedKey = null;
608 }
609
610 value = WifiNative.getNetworkVariableCommand(config.networkId,
611 WifiConfiguration.Protocol.varName);
612 if (!TextUtils.isEmpty(value)) {
613 String vals[] = value.split(" ");
614 for (String val : vals) {
615 int index =
616 lookupString(val, WifiConfiguration.Protocol.strings);
617 if (0 <= index) {
618 config.allowedProtocols.set(index);
619 }
620 }
621 }
622
623 value = WifiNative.getNetworkVariableCommand(config.networkId,
624 WifiConfiguration.KeyMgmt.varName);
625 if (!TextUtils.isEmpty(value)) {
626 String vals[] = value.split(" ");
627 for (String val : vals) {
628 int index =
629 lookupString(val, WifiConfiguration.KeyMgmt.strings);
630 if (0 <= index) {
631 config.allowedKeyManagement.set(index);
632 }
633 }
634 }
635
636 value = WifiNative.getNetworkVariableCommand(config.networkId,
637 WifiConfiguration.AuthAlgorithm.varName);
638 if (!TextUtils.isEmpty(value)) {
639 String vals[] = value.split(" ");
640 for (String val : vals) {
641 int index =
642 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
643 if (0 <= index) {
644 config.allowedAuthAlgorithms.set(index);
645 }
646 }
647 }
648
649 value = WifiNative.getNetworkVariableCommand(config.networkId,
650 WifiConfiguration.PairwiseCipher.varName);
651 if (!TextUtils.isEmpty(value)) {
652 String vals[] = value.split(" ");
653 for (String val : vals) {
654 int index =
655 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
656 if (0 <= index) {
657 config.allowedPairwiseCiphers.set(index);
658 }
659 }
660 }
661
662 value = WifiNative.getNetworkVariableCommand(config.networkId,
663 WifiConfiguration.GroupCipher.varName);
664 if (!TextUtils.isEmpty(value)) {
665 String vals[] = value.split(" ");
666 for (String val : vals) {
667 int index =
668 lookupString(val, WifiConfiguration.GroupCipher.strings);
669 if (0 <= index) {
670 config.allowedGroupCiphers.set(index);
671 }
672 }
673 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800674
675 for (WifiConfiguration.EnterpriseField field :
676 config.enterpriseFields) {
677 value = WifiNative.getNetworkVariableCommand(netId,
678 field.varName());
679 if (!TextUtils.isEmpty(value)) {
680 field.setValue(value);
681 }
682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684
685 /**
686 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
687 * @return the supplicant-assigned identifier for the new or updated
688 * network if the operation succeeds, or {@code -1} if it fails
689 */
690 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
691 enforceChangePermission();
692 /*
693 * If the supplied networkId is -1, we create a new empty
694 * network configuration. Otherwise, the networkId should
695 * refer to an existing configuration.
696 */
697 int netId = config.networkId;
698 boolean newNetwork = netId == -1;
699 boolean doReconfig;
700 int currentPriority;
701 // networkId of -1 means we want to create a new network
702 if (newNetwork) {
703 netId = WifiNative.addNetworkCommand();
704 if (netId < 0) {
705 if (DBG) {
706 Log.d(TAG, "Failed to add a network!");
707 }
708 return -1;
709 }
710 doReconfig = true;
711 } else {
712 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
713 currentPriority = -1;
714 if (!TextUtils.isEmpty(priorityVal)) {
715 try {
716 currentPriority = Integer.parseInt(priorityVal);
717 } catch (NumberFormatException ignore) {
718 }
719 }
720 doReconfig = currentPriority != config.priority;
721 }
722 mNeedReconfig = mNeedReconfig || doReconfig;
723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 setVariables: {
725 /*
726 * Note that if a networkId for a non-existent network
727 * was supplied, then the first setNetworkVariableCommand()
728 * will fail, so we don't bother to make a separate check
729 * for the validity of the ID up front.
730 */
731
732 if (config.SSID != null &&
733 !WifiNative.setNetworkVariableCommand(
734 netId,
735 WifiConfiguration.ssidVarName,
736 config.SSID)) {
737 if (DBG) {
738 Log.d(TAG, "failed to set SSID: "+config.SSID);
739 }
740 break setVariables;
741 }
742
743 if (config.BSSID != null &&
744 !WifiNative.setNetworkVariableCommand(
745 netId,
746 WifiConfiguration.bssidVarName,
747 config.BSSID)) {
748 if (DBG) {
749 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
750 }
751 break setVariables;
752 }
753
754 String allowedKeyManagementString =
755 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
756 if (config.allowedKeyManagement.cardinality() != 0 &&
757 !WifiNative.setNetworkVariableCommand(
758 netId,
759 WifiConfiguration.KeyMgmt.varName,
760 allowedKeyManagementString)) {
761 if (DBG) {
762 Log.d(TAG, "failed to set key_mgmt: "+
763 allowedKeyManagementString);
764 }
765 break setVariables;
766 }
767
768 String allowedProtocolsString =
769 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
770 if (config.allowedProtocols.cardinality() != 0 &&
771 !WifiNative.setNetworkVariableCommand(
772 netId,
773 WifiConfiguration.Protocol.varName,
774 allowedProtocolsString)) {
775 if (DBG) {
776 Log.d(TAG, "failed to set proto: "+
777 allowedProtocolsString);
778 }
779 break setVariables;
780 }
781
782 String allowedAuthAlgorithmsString =
783 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
784 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
785 !WifiNative.setNetworkVariableCommand(
786 netId,
787 WifiConfiguration.AuthAlgorithm.varName,
788 allowedAuthAlgorithmsString)) {
789 if (DBG) {
790 Log.d(TAG, "failed to set auth_alg: "+
791 allowedAuthAlgorithmsString);
792 }
793 break setVariables;
794 }
795
796 String allowedPairwiseCiphersString =
797 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
798 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
799 !WifiNative.setNetworkVariableCommand(
800 netId,
801 WifiConfiguration.PairwiseCipher.varName,
802 allowedPairwiseCiphersString)) {
803 if (DBG) {
804 Log.d(TAG, "failed to set pairwise: "+
805 allowedPairwiseCiphersString);
806 }
807 break setVariables;
808 }
809
810 String allowedGroupCiphersString =
811 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
812 if (config.allowedGroupCiphers.cardinality() != 0 &&
813 !WifiNative.setNetworkVariableCommand(
814 netId,
815 WifiConfiguration.GroupCipher.varName,
816 allowedGroupCiphersString)) {
817 if (DBG) {
818 Log.d(TAG, "failed to set group: "+
819 allowedGroupCiphersString);
820 }
821 break setVariables;
822 }
823
824 // Prevent client screw-up by passing in a WifiConfiguration we gave it
825 // by preventing "*" as a key.
826 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
827 !WifiNative.setNetworkVariableCommand(
828 netId,
829 WifiConfiguration.pskVarName,
830 config.preSharedKey)) {
831 if (DBG) {
832 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
833 }
834 break setVariables;
835 }
836
837 boolean hasSetKey = false;
838 if (config.wepKeys != null) {
839 for (int i = 0; i < config.wepKeys.length; i++) {
840 // Prevent client screw-up by passing in a WifiConfiguration we gave it
841 // by preventing "*" as a key.
842 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
843 if (!WifiNative.setNetworkVariableCommand(
844 netId,
845 WifiConfiguration.wepKeyVarNames[i],
846 config.wepKeys[i])) {
847 if (DBG) {
848 Log.d(TAG,
849 "failed to set wep_key"+i+": " +
850 config.wepKeys[i]);
851 }
852 break setVariables;
853 }
854 hasSetKey = true;
855 }
856 }
857 }
858
859 if (hasSetKey) {
860 if (!WifiNative.setNetworkVariableCommand(
861 netId,
862 WifiConfiguration.wepTxKeyIdxVarName,
863 Integer.toString(config.wepTxKeyIndex))) {
864 if (DBG) {
865 Log.d(TAG,
866 "failed to set wep_tx_keyidx: "+
867 config.wepTxKeyIndex);
868 }
869 break setVariables;
870 }
871 }
872
873 if (!WifiNative.setNetworkVariableCommand(
874 netId,
875 WifiConfiguration.priorityVarName,
876 Integer.toString(config.priority))) {
877 if (DBG) {
878 Log.d(TAG, config.SSID + ": failed to set priority: "
879 +config.priority);
880 }
881 break setVariables;
882 }
883
884 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
885 netId,
886 WifiConfiguration.hiddenSSIDVarName,
887 Integer.toString(config.hiddenSSID ? 1 : 0))) {
888 if (DBG) {
889 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
890 config.hiddenSSID);
891 }
892 break setVariables;
893 }
894
Chung-yih Wang43374762009-09-16 14:28:42 +0800895 for (WifiConfiguration.EnterpriseField field
896 : config.enterpriseFields) {
897 String varName = field.varName();
898 String value = field.value();
899 if ((value != null) && !WifiNative.setNetworkVariableCommand(
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800900 netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800901 varName,
902 value)) {
903 if (DBG) {
904 Log.d(TAG, config.SSID + ": failed to set " + varName +
905 ": " + value);
906 }
907 break setVariables;
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800908 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800909 }
910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 return netId;
912 }
913
914 /*
915 * For an update, if one of the setNetworkVariable operations fails,
916 * we might want to roll back all the changes already made. But the
917 * chances are that if anything is going to go wrong, it'll happen
918 * the first time we try to set one of the variables.
919 */
920 if (newNetwork) {
921 removeNetwork(netId);
922 if (DBG) {
923 Log.d(TAG,
924 "Failed to set a network variable, removed network: "
925 + netId);
926 }
927 }
928 return -1;
929 }
930
931 private static String makeString(BitSet set, String[] strings) {
932 StringBuffer buf = new StringBuffer();
933 int nextSetBit = -1;
934
935 /* Make sure all set bits are in [0, strings.length) to avoid
936 * going out of bounds on strings. (Shouldn't happen, but...) */
937 set = set.get(0, strings.length);
938
939 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
940 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
941 }
942
943 // remove trailing space
944 if (set.cardinality() > 0) {
945 buf.setLength(buf.length() - 1);
946 }
947
948 return buf.toString();
949 }
950
951 private static int lookupString(String string, String[] strings) {
952 int size = strings.length;
953
954 string = string.replace('-', '_');
955
956 for (int i = 0; i < size; i++)
957 if (string.equals(strings[i]))
958 return i;
959
960 if (DBG) {
961 // if we ever get here, we should probably add the
962 // value to WifiConfiguration to reflect that it's
963 // supported by the WPA supplicant
964 Log.w(TAG, "Failed to look-up a string: " + string);
965 }
966
967 return -1;
968 }
969
970 /**
971 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
972 * @param netId the integer that identifies the network configuration
973 * to the supplicant
974 * @return {@code true} if the operation succeeded
975 */
976 public boolean removeNetwork(int netId) {
977 enforceChangePermission();
978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 return mWifiStateTracker.removeNetwork(netId);
980 }
981
982 /**
983 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
984 * @param netId the integer that identifies the network configuration
985 * to the supplicant
986 * @param disableOthers if true, disable all other networks.
987 * @return {@code true} if the operation succeeded
988 */
989 public boolean enableNetwork(int netId, boolean disableOthers) {
990 enforceChangePermission();
991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -0400993 String ifname = mWifiStateTracker.getInterfaceName();
994 NetworkUtils.enableInterface(ifname);
995 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
996 if (!result) {
997 NetworkUtils.disableInterface(ifname);
998 }
999 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 }
1001 }
1002
1003 /**
1004 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1005 * @param netId the integer that identifies the network configuration
1006 * to the supplicant
1007 * @return {@code true} if the operation succeeded
1008 */
1009 public boolean disableNetwork(int netId) {
1010 enforceChangePermission();
1011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 synchronized (mWifiStateTracker) {
1013 return WifiNative.disableNetworkCommand(netId);
1014 }
1015 }
1016
1017 /**
1018 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1019 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1020 */
1021 public WifiInfo getConnectionInfo() {
1022 enforceAccessPermission();
1023 /*
1024 * Make sure we have the latest information, by sending
1025 * a status request to the supplicant.
1026 */
1027 return mWifiStateTracker.requestConnectionInfo();
1028 }
1029
1030 /**
1031 * Return the results of the most recent access point scan, in the form of
1032 * a list of {@link ScanResult} objects.
1033 * @return the list of results
1034 */
1035 public List<ScanResult> getScanResults() {
1036 enforceAccessPermission();
1037 String reply;
1038 synchronized (mWifiStateTracker) {
1039 reply = WifiNative.scanResultsCommand();
1040 }
1041 if (reply == null) {
1042 return null;
1043 }
1044
1045 List<ScanResult> scanList = new ArrayList<ScanResult>();
1046
1047 int lineCount = 0;
1048
1049 int replyLen = reply.length();
1050 // Parse the result string, keeping in mind that the last line does
1051 // not end with a newline.
1052 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1053 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1054 ++lineCount;
1055 /*
1056 * Skip the first line, which is a header
1057 */
1058 if (lineCount == 1) {
1059 lineBeg = lineEnd + 1;
1060 continue;
1061 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001062 if (lineEnd > lineBeg) {
1063 String line = reply.substring(lineBeg, lineEnd);
1064 ScanResult scanResult = parseScanResult(line);
1065 if (scanResult != null) {
1066 scanList.add(scanResult);
1067 } else if (DBG) {
1068 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070 }
1071 lineBeg = lineEnd + 1;
1072 }
1073 }
1074 mWifiStateTracker.setScanResultsList(scanList);
1075 return scanList;
1076 }
1077
1078 /**
1079 * Parse the scan result line passed to us by wpa_supplicant (helper).
1080 * @param line the line to parse
1081 * @return the {@link ScanResult} object
1082 */
1083 private ScanResult parseScanResult(String line) {
1084 ScanResult scanResult = null;
1085 if (line != null) {
1086 /*
1087 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1088 * must synchronized here!
1089 */
1090 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001091 String[] result = scanResultPattern.split(line);
1092 if (3 <= result.length && result.length <= 5) {
1093 String bssid = result[0];
1094 // bssid | frequency | level | flags | ssid
1095 int frequency;
1096 int level;
1097 try {
1098 frequency = Integer.parseInt(result[1]);
1099 level = Integer.parseInt(result[2]);
1100 /* some implementations avoid negative values by adding 256
1101 * so we need to adjust for that here.
1102 */
1103 if (level > 0) level -= 256;
1104 } catch (NumberFormatException e) {
1105 frequency = 0;
1106 level = 0;
1107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
Mike Lockwood1a645052009-06-25 13:01:12 -04001109 /*
1110 * The formatting of the results returned by
1111 * wpa_supplicant is intended to make the fields
1112 * line up nicely when printed,
1113 * not to make them easy to parse. So we have to
1114 * apply some heuristics to figure out which field
1115 * is the SSID and which field is the flags.
1116 */
1117 String ssid;
1118 String flags;
1119 if (result.length == 4) {
1120 if (result[3].charAt(0) == '[') {
1121 flags = result[3];
1122 ssid = "";
1123 } else {
1124 flags = "";
1125 ssid = result[3];
1126 }
1127 } else if (result.length == 5) {
1128 flags = result[3];
1129 ssid = result[4];
1130 } else {
1131 // Here, we must have 3 fields: no flags and ssid
1132 // set
1133 flags = "";
1134 ssid = "";
1135 }
1136
Mike Lockwood00717e22009-08-17 10:09:36 -04001137 // bssid + ssid is the hash key
1138 String key = bssid + ssid;
1139 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001140 if (scanResult != null) {
1141 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001142 scanResult.SSID = ssid;
1143 scanResult.capabilities = flags;
1144 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001145 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 // Do not add scan results that have no SSID set
1147 if (0 < ssid.trim().length()) {
1148 scanResult =
1149 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001150 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001151 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001154 } else {
1155 Log.w(TAG, "Misformatted scan result text with " +
1156 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158 }
1159 }
1160
1161 return scanResult;
1162 }
1163
1164 /**
1165 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1166 * and construct a {@code WifiConfiguration} that describes the encryption,
1167 * key management, and authenticaion capabilities of the access point.
1168 * @param flags the string returned by wpa_supplicant
1169 * @return the {@link WifiConfiguration} object, filled in
1170 */
1171 WifiConfiguration parseScanFlags(String flags) {
1172 WifiConfiguration config = new WifiConfiguration();
1173
1174 if (flags.length() == 0) {
1175 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1176 }
1177 // ... to be implemented
1178 return config;
1179 }
1180
1181 /**
1182 * Tell the supplicant to persist the current list of configured networks.
1183 * @return {@code true} if the operation succeeded
1184 */
1185 public boolean saveConfiguration() {
1186 boolean result;
1187 enforceChangePermission();
1188 synchronized (mWifiStateTracker) {
1189 result = WifiNative.saveConfigCommand();
1190 if (result && mNeedReconfig) {
1191 mNeedReconfig = false;
1192 result = WifiNative.reloadConfigCommand();
1193
1194 if (result) {
1195 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1196 mContext.sendBroadcast(intent);
1197 }
1198 }
1199 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001200 // Inform the backup manager about a data change
1201 IBackupManager ibm = IBackupManager.Stub.asInterface(
1202 ServiceManager.getService(Context.BACKUP_SERVICE));
1203 if (ibm != null) {
1204 try {
1205 ibm.dataChanged("com.android.providers.settings");
1206 } catch (Exception e) {
1207 // Try again later
1208 }
1209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 return result;
1211 }
1212
1213 /**
1214 * Set the number of radio frequency channels that are allowed to be used
1215 * in the current regulatory domain. This method should be used only
1216 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001217 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 * persisted as a Secure setting.
1219 * @param numChannels the number of allowed channels. Must be greater than 0
1220 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001221 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1223 * {@code numChannels} is outside the valid range.
1224 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001225 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1226 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1227 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 enforceChangePermission();
1229 /*
1230 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1231 * but if Wi-Fi isn't currently enabled, that's not possible, and
1232 * we want to persist the setting anyway,so that it will take
1233 * effect when Wi-Fi does become enabled.
1234 */
1235 boolean found = false;
1236 for (int validChan : sValidRegulatoryChannelCounts) {
1237 if (validChan == numChannels) {
1238 found = true;
1239 break;
1240 }
1241 }
1242 if (!found) {
1243 return false;
1244 }
1245
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001246 if (persist) {
1247 Settings.Secure.putInt(mContext.getContentResolver(),
1248 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1249 numChannels);
1250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 mWifiStateTracker.setNumAllowedChannels(numChannels);
1252 return true;
1253 }
1254
1255 /**
1256 * Return the number of frequency channels that are allowed
1257 * to be used in the current regulatory domain.
1258 * @return the number of allowed channels, or {@code -1} if an error occurs
1259 */
1260 public int getNumAllowedChannels() {
1261 int numChannels;
1262
1263 enforceAccessPermission();
1264 synchronized (mWifiStateTracker) {
1265 /*
1266 * If we can't get the value from the driver (e.g., because
1267 * Wi-Fi is not currently enabled), get the value from
1268 * Settings.
1269 */
1270 numChannels = WifiNative.getNumAllowedChannelsCommand();
1271 if (numChannels < 0) {
1272 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1273 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1274 -1);
1275 }
1276 }
1277 return numChannels;
1278 }
1279
1280 /**
1281 * Return the list of valid values for the number of allowed radio channels
1282 * for various regulatory domains.
1283 * @return the list of channel counts
1284 */
1285 public int[] getValidChannelCounts() {
1286 enforceAccessPermission();
1287 return sValidRegulatoryChannelCounts;
1288 }
1289
1290 /**
1291 * Return the DHCP-assigned addresses from the last successful DHCP request,
1292 * if any.
1293 * @return the DHCP information
1294 */
1295 public DhcpInfo getDhcpInfo() {
1296 enforceAccessPermission();
1297 return mWifiStateTracker.getDhcpInfo();
1298 }
1299
1300 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1301 @Override
1302 public void onReceive(Context context, Intent intent) {
1303 String action = intent.getAction();
1304
1305 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1306 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1307 int stayAwakeConditions =
1308 Settings.System.getInt(mContext.getContentResolver(),
1309 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1310 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001311 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 mAlarmManager.cancel(mIdleIntent);
1313 mDeviceIdle = false;
1314 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001315 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001317 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001319 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 /*
1321 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1322 * AND the "stay on while plugged in" setting doesn't match the
1323 * current power conditions (i.e, not plugged in, plugged in to USB,
1324 * or plugged in to AC).
1325 */
1326 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001327 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1328 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001329 // we used to go to sleep immediately, but this caused some race conditions
1330 // we don't have time to track down for this release. Delay instead, but not
1331 // as long as we would if connected (below)
1332 // TODO - fix the race conditions and switch back to the immediate turn-off
1333 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
1334 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
1335 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1336 // // do not keep Wifi awake when screen is off if Wifi is not associated
1337 // mDeviceIdle = true;
1338 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001339 } else {
1340 long triggerTime = System.currentTimeMillis() + idleMillis;
1341 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1342 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345 /* we can return now -- there's nothing to do until we get the idle intent back */
1346 return;
1347 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001348 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 mDeviceIdle = true;
1350 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1351 /*
1352 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1353 * AND we are transitioning from a state in which the device was supposed
1354 * to stay awake to a state in which it is not supposed to stay awake.
1355 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1356 * the already-set timer.
1357 */
1358 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001359 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1361 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1362 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001363 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1365 mPluggedType = pluggedType;
1366 return;
1367 }
1368 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001369 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001370 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1371 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1372 boolean isBluetoothPlaying = false;
1373 for (BluetoothDevice sink : sinks) {
1374 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1375 isBluetoothPlaying = true;
1376 }
1377 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001378 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 } else {
1381 return;
1382 }
1383
1384 updateWifiState();
1385 }
1386
1387 /**
1388 * Determines whether the Wi-Fi chipset should stay awake or be put to
1389 * sleep. Looks at the setting for the sleep policy and the current
1390 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001391 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 * @see #shouldDeviceStayAwake(int, int)
1393 */
1394 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1395 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1396 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1397
1398 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1399 // Never sleep
1400 return true;
1401 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1402 (pluggedType != 0)) {
1403 // Never sleep while plugged, and we're plugged
1404 return true;
1405 } else {
1406 // Default
1407 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1408 }
1409 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 /**
1412 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1413 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1414 * of {@code 0} isn't really a plugged type, but rather an indication that the
1415 * device isn't plugged in at all, there is no bit value corresponding to a
1416 * {@code pluggedType} value of {@code 0}. That is why we shift by
1417 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1418 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1419 * keep the device (and hence Wi-Fi) awake.
1420 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1421 * being made
1422 * @return {@code true} if {@code pluggedType} indicates that the device is
1423 * supposed to stay awake, {@code false} otherwise.
1424 */
1425 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1426 return (stayAwakeConditions & pluggedType) != 0;
1427 }
1428 };
1429
Dianne Hackborn617f8772009-03-31 15:04:46 -07001430 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 Message msg = Message.obtain(mWifiHandler,
1432 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001433 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 msg.sendToTarget();
1435 }
1436
1437 private void sendStartMessage(boolean scanOnlyMode) {
1438 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1439 }
1440
1441 private void updateWifiState() {
1442 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001443 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 boolean lockHeld = mLocks.hasLocks();
1445 int strongestLockMode;
1446 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1447 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1448 if (mDeviceIdle && lockHeld) {
1449 strongestLockMode = mLocks.getStrongestLockMode();
1450 } else {
1451 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1452 }
1453
1454 synchronized (mWifiHandler) {
1455 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1456 return;
1457 }
1458 if (wifiShouldBeEnabled) {
1459 if (wifiShouldBeStarted) {
1460 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001461 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 sWakeLock.acquire();
1463 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1464 } else {
1465 int wakeLockTimeout =
1466 Settings.Secure.getInt(
1467 mContext.getContentResolver(),
1468 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1469 DEFAULT_WAKELOCK_TIMEOUT);
1470 /*
1471 * The following wakelock is held in order to ensure
1472 * that the connectivity manager has time to fail over
1473 * to the mobile data network. The connectivity manager
1474 * releases it once mobile data connectivity has been
1475 * established. If connectivity cannot be established,
1476 * the wakelock is released after wakeLockTimeout
1477 * milliseconds have elapsed.
1478 */
1479 sDriverStopWakeLock.acquire();
1480 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1481 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1482 }
1483 } else {
1484 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001485 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 }
1488 }
1489
1490 private void registerForBroadcasts() {
1491 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1493 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1494 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1495 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001496 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 mContext.registerReceiver(mReceiver, intentFilter);
1498 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 private boolean isAirplaneSensitive() {
1501 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1502 Settings.System.AIRPLANE_MODE_RADIOS);
1503 return airplaneModeRadios == null
1504 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1505 }
1506
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001507 private boolean isAirplaneToggleable() {
1508 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1509 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1510 return toggleableRadios != null
1511 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1512 }
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 /**
1515 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1516 * currently on.
1517 * @return {@code true} if airplane mode is on.
1518 */
1519 private boolean isAirplaneModeOn() {
1520 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1521 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1522 }
1523
1524 /**
1525 * Handler that allows posting to the WifiThread.
1526 */
1527 private class WifiHandler extends Handler {
1528 public WifiHandler(Looper looper) {
1529 super(looper);
1530 }
1531
1532 @Override
1533 public void handleMessage(Message msg) {
1534 switch (msg.what) {
1535
1536 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001537 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 sWakeLock.release();
1539 break;
1540
1541 case MESSAGE_START_WIFI:
1542 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1543 mWifiStateTracker.restart();
1544 sWakeLock.release();
1545 break;
1546
1547 case MESSAGE_DISABLE_WIFI:
1548 // a non-zero msg.arg1 value means the "enabled" setting
1549 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001550 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 sWakeLock.release();
1552 break;
1553
1554 case MESSAGE_STOP_WIFI:
1555 mWifiStateTracker.disconnectAndStop();
1556 // don't release wakelock
1557 break;
1558
1559 case MESSAGE_RELEASE_WAKELOCK:
1560 synchronized (sDriverStopWakeLock) {
1561 if (sDriverStopWakeLock.isHeld()) {
1562 sDriverStopWakeLock.release();
1563 }
1564 }
1565 break;
1566 }
1567 }
1568 }
1569
1570 @Override
1571 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1572 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1573 != PackageManager.PERMISSION_GRANTED) {
1574 pw.println("Permission Denial: can't dump WifiService from from pid="
1575 + Binder.getCallingPid()
1576 + ", uid=" + Binder.getCallingUid());
1577 return;
1578 }
1579 pw.println("Wi-Fi is " + stateName(mWifiState));
1580 pw.println("Stay-awake conditions: " +
1581 Settings.System.getInt(mContext.getContentResolver(),
1582 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1583 pw.println();
1584
1585 pw.println("Internal state:");
1586 pw.println(mWifiStateTracker);
1587 pw.println();
1588 pw.println("Latest scan results:");
1589 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1590 if (scanResults != null && scanResults.size() != 0) {
1591 pw.println(" BSSID Frequency RSSI Flags SSID");
1592 for (ScanResult r : scanResults) {
1593 pw.printf(" %17s %9d %5d %-16s %s%n",
1594 r.BSSID,
1595 r.frequency,
1596 r.level,
1597 r.capabilities,
1598 r.SSID == null ? "" : r.SSID);
1599 }
1600 }
1601 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001602 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1603 mScanLocksAcquired + " scan");
1604 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1605 mScanLocksReleased + " scan");
1606 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 pw.println("Locks held:");
1608 mLocks.dump(pw);
1609 }
1610
1611 private static String stateName(int wifiState) {
1612 switch (wifiState) {
1613 case WIFI_STATE_DISABLING:
1614 return "disabling";
1615 case WIFI_STATE_DISABLED:
1616 return "disabled";
1617 case WIFI_STATE_ENABLING:
1618 return "enabling";
1619 case WIFI_STATE_ENABLED:
1620 return "enabled";
1621 case WIFI_STATE_UNKNOWN:
1622 return "unknown state";
1623 default:
1624 return "[invalid state]";
1625 }
1626 }
1627
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001628 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001630 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632
1633 public void binderDied() {
1634 synchronized (mLocks) {
1635 releaseWifiLockLocked(mBinder);
1636 }
1637 }
1638
1639 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001640 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
1642 }
1643
1644 private class LockList {
1645 private List<WifiLock> mList;
1646
1647 private LockList() {
1648 mList = new ArrayList<WifiLock>();
1649 }
1650
1651 private synchronized boolean hasLocks() {
1652 return !mList.isEmpty();
1653 }
1654
1655 private synchronized int getStrongestLockMode() {
1656 if (mList.isEmpty()) {
1657 return WifiManager.WIFI_MODE_FULL;
1658 }
1659 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001660 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 return WifiManager.WIFI_MODE_FULL;
1662 }
1663 }
1664 return WifiManager.WIFI_MODE_SCAN_ONLY;
1665 }
1666
1667 private void addLock(WifiLock lock) {
1668 if (findLockByBinder(lock.mBinder) < 0) {
1669 mList.add(lock);
1670 }
1671 }
1672
1673 private WifiLock removeLock(IBinder binder) {
1674 int index = findLockByBinder(binder);
1675 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001676 WifiLock ret = mList.remove(index);
1677 ret.unlinkDeathRecipient();
1678 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 } else {
1680 return null;
1681 }
1682 }
1683
1684 private int findLockByBinder(IBinder binder) {
1685 int size = mList.size();
1686 for (int i = size - 1; i >= 0; i--)
1687 if (mList.get(i).mBinder == binder)
1688 return i;
1689 return -1;
1690 }
1691
1692 private void dump(PrintWriter pw) {
1693 for (WifiLock l : mList) {
1694 pw.print(" ");
1695 pw.println(l);
1696 }
1697 }
1698 }
1699
1700 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1701 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1702 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1703 return false;
1704 }
1705 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1706 synchronized (mLocks) {
1707 return acquireWifiLockLocked(wifiLock);
1708 }
1709 }
1710
1711 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001712 Log.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001715
The Android Open Source Project10592532009-03-18 17:39:46 -07001716 int uid = Binder.getCallingUid();
1717 long ident = Binder.clearCallingIdentity();
1718 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001719 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001720 case WifiManager.WIFI_MODE_FULL:
1721 ++mFullLocksAcquired;
1722 mBatteryStats.noteFullWifiLockAcquired(uid);
1723 break;
1724 case WifiManager.WIFI_MODE_SCAN_ONLY:
1725 ++mScanLocksAcquired;
1726 mBatteryStats.noteScanWifiLockAcquired(uid);
1727 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001728 }
1729 } catch (RemoteException e) {
1730 } finally {
1731 Binder.restoreCallingIdentity(ident);
1732 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 updateWifiState();
1735 return true;
1736 }
1737
1738 public boolean releaseWifiLock(IBinder lock) {
1739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1740 synchronized (mLocks) {
1741 return releaseWifiLockLocked(lock);
1742 }
1743 }
1744
1745 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001746 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001747
The Android Open Source Project10592532009-03-18 17:39:46 -07001748 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001749
1750 Log.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1751
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001752 hadLock = (wifiLock != null);
1753
1754 if (hadLock) {
1755 int uid = Binder.getCallingUid();
1756 long ident = Binder.clearCallingIdentity();
1757 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001758 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001759 case WifiManager.WIFI_MODE_FULL:
1760 ++mFullLocksReleased;
1761 mBatteryStats.noteFullWifiLockReleased(uid);
1762 break;
1763 case WifiManager.WIFI_MODE_SCAN_ONLY:
1764 ++mScanLocksReleased;
1765 mBatteryStats.noteScanWifiLockReleased(uid);
1766 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001767 }
1768 } catch (RemoteException e) {
1769 } finally {
1770 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001771 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001772 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001773 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001775 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001777
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001778 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001779 implements IBinder.DeathRecipient {
1780 String mTag;
1781 int mMode;
1782 IBinder mBinder;
1783
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001784 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001785 super();
1786 mTag = tag;
1787 mMode = mode;
1788 mBinder = binder;
1789 try {
1790 mBinder.linkToDeath(this, 0);
1791 } catch (RemoteException e) {
1792 binderDied();
1793 }
1794 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001795
1796 void unlinkDeathRecipient() {
1797 mBinder.unlinkToDeath(this, 0);
1798 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001799 }
1800
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001801 private class Multicaster extends DeathRecipient {
1802 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001803 super(Binder.getCallingUid(), tag, binder);
1804 }
1805
1806 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001807 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001808 synchronized (mMulticasters) {
1809 int i = mMulticasters.indexOf(this);
1810 if (i != -1) {
1811 removeMulticasterLocked(i, mMode);
1812 }
1813 }
1814 }
1815
1816 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001817 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001818 }
1819
1820 public int getUid() {
1821 return mMode;
1822 }
1823 }
1824
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001825 public void acquireMulticastLock(IBinder binder, String tag) {
1826 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001827
1828 synchronized (mMulticasters) {
1829 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001830 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001831 // Note that we could call stopPacketFiltering only when
1832 // our new size == 1 (first call), but this function won't
1833 // be called often and by making the stopPacket call each
1834 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001835 synchronized (mWifiStateTracker) {
1836 WifiNative.stopPacketFiltering();
1837 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001838 }
1839
1840 int uid = Binder.getCallingUid();
1841 Long ident = Binder.clearCallingIdentity();
1842 try {
1843 mBatteryStats.noteWifiMulticastEnabled(uid);
1844 } catch (RemoteException e) {
1845 } finally {
1846 Binder.restoreCallingIdentity(ident);
1847 }
1848 }
1849
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001850 public void releaseMulticastLock() {
1851 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001852
1853 int uid = Binder.getCallingUid();
1854 synchronized (mMulticasters) {
1855 mMulticastDisabled++;
1856 int size = mMulticasters.size();
1857 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001858 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001859 if ((m != null) && (m.getUid() == uid)) {
1860 removeMulticasterLocked(i, uid);
1861 }
1862 }
1863 }
1864 }
1865
1866 private void removeMulticasterLocked(int i, int uid)
1867 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001868 Multicaster removed = mMulticasters.remove(i);
1869 if (removed != null) {
1870 removed.unlinkDeathRecipient();
1871 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001872 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001873 synchronized (mWifiStateTracker) {
1874 WifiNative.startPacketFiltering();
1875 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001876 }
1877
1878 Long ident = Binder.clearCallingIdentity();
1879 try {
1880 mBatteryStats.noteWifiMulticastDisabled(uid);
1881 } catch (RemoteException e) {
1882 } finally {
1883 Binder.restoreCallingIdentity(ident);
1884 }
1885 }
1886
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001887 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001888 enforceAccessPermission();
1889
1890 synchronized (mMulticasters) {
1891 return (mMulticasters.size() > 0);
1892 }
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894}