blob: 3a08e4d2cbfbc7fb9b38cec96f89a9822ba093f0 [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
Irfan Sheriff0fe3f7c2010-01-08 09:36:04 -0800332 /**
333 * Multiple calls to unregisterReceiver() cause exception and a system crash.
334 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
335 * disable wifi at the same time.
336 * Avoid doing a disable when the current Wifi state is UNKNOWN
337 * TODO: Handle driver load fail and supplicant lost as seperate states
338 */
339 if (mWifiState == WIFI_STATE_UNKNOWN && !enable) {
340 return false;
341 }
342
Dianne Hackborn617f8772009-03-31 15:04:46 -0700343 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344
345 if (enable) {
346 if (!WifiNative.loadDriver()) {
347 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700348 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 return false;
350 }
351 if (!WifiNative.startSupplicant()) {
352 WifiNative.unloadDriver();
353 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700354 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 return false;
356 }
357 registerForBroadcasts();
358 mWifiStateTracker.startEventLoop();
359 } else {
360
361 mContext.unregisterReceiver(mReceiver);
362 // Remove notification (it will no-op if it isn't visible)
363 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
364
365 boolean failedToStopSupplicantOrUnloadDriver = false;
366 if (!WifiNative.stopSupplicant()) {
367 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700368 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 failedToStopSupplicantOrUnloadDriver = true;
370 }
371
372 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400373 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374
375 if (!WifiNative.unloadDriver()) {
376 Log.e(TAG, "Failed to unload Wi-Fi driver.");
377 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700378 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 failedToStopSupplicantOrUnloadDriver = true;
380 }
381 }
382 if (failedToStopSupplicantOrUnloadDriver) {
383 return false;
384 }
385 }
386
387 // Success!
388
389 if (persist) {
390 persistWifiEnabled(enable);
391 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700392 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 return true;
395 }
396
Dianne Hackborn617f8772009-03-31 15:04:46 -0700397 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 final int previousWifiState = mWifiState;
399
The Android Open Source Project10592532009-03-18 17:39:46 -0700400 long ident = Binder.clearCallingIdentity();
401 try {
402 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700403 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700404 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700405 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700406 }
407 } catch (RemoteException e) {
408 } finally {
409 Binder.restoreCallingIdentity(ident);
410 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 // Update state
413 mWifiState = wifiState;
414
415 // Broadcast
416 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
417 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
418 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
419 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
420 mContext.sendStickyBroadcast(intent);
421 }
422
423 private void enforceAccessPermission() {
424 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
425 "WifiService");
426 }
427
428 private void enforceChangePermission() {
429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
430 "WifiService");
431
432 }
433
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700434 private void enforceMulticastChangePermission() {
435 mContext.enforceCallingOrSelfPermission(
436 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
437 "WifiService");
438 }
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 /**
441 * see {@link WifiManager#getWifiState()}
442 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
443 * {@link WifiManager#WIFI_STATE_DISABLING},
444 * {@link WifiManager#WIFI_STATE_ENABLED},
445 * {@link WifiManager#WIFI_STATE_ENABLING},
446 * {@link WifiManager#WIFI_STATE_UNKNOWN}
447 */
448 public int getWifiEnabledState() {
449 enforceAccessPermission();
450 return mWifiState;
451 }
452
453 /**
454 * see {@link android.net.wifi.WifiManager#disconnect()}
455 * @return {@code true} if the operation succeeds
456 */
457 public boolean disconnect() {
458 enforceChangePermission();
459 synchronized (mWifiStateTracker) {
460 return WifiNative.disconnectCommand();
461 }
462 }
463
464 /**
465 * see {@link android.net.wifi.WifiManager#reconnect()}
466 * @return {@code true} if the operation succeeds
467 */
468 public boolean reconnect() {
469 enforceChangePermission();
470 synchronized (mWifiStateTracker) {
471 return WifiNative.reconnectCommand();
472 }
473 }
474
475 /**
476 * see {@link android.net.wifi.WifiManager#reassociate()}
477 * @return {@code true} if the operation succeeds
478 */
479 public boolean reassociate() {
480 enforceChangePermission();
481 synchronized (mWifiStateTracker) {
482 return WifiNative.reassociateCommand();
483 }
484 }
485
486 /**
487 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
488 * @return the list of configured networks
489 */
490 public List<WifiConfiguration> getConfiguredNetworks() {
491 enforceAccessPermission();
492 String listStr;
493 /*
494 * We don't cache the list, because we want to allow
495 * for the possibility that the configuration file
496 * has been modified through some external means,
497 * such as the wpa_cli command line program.
498 */
499 synchronized (mWifiStateTracker) {
500 listStr = WifiNative.listNetworksCommand();
501 }
502 List<WifiConfiguration> networks =
503 new ArrayList<WifiConfiguration>();
504 if (listStr == null)
505 return networks;
506
507 String[] lines = listStr.split("\n");
508 // Skip the first line, which is a header
509 for (int i = 1; i < lines.length; i++) {
510 String[] result = lines[i].split("\t");
511 // network-id | ssid | bssid | flags
512 WifiConfiguration config = new WifiConfiguration();
513 try {
514 config.networkId = Integer.parseInt(result[0]);
515 } catch(NumberFormatException e) {
516 continue;
517 }
518 if (result.length > 3) {
519 if (result[3].indexOf("[CURRENT]") != -1)
520 config.status = WifiConfiguration.Status.CURRENT;
521 else if (result[3].indexOf("[DISABLED]") != -1)
522 config.status = WifiConfiguration.Status.DISABLED;
523 else
524 config.status = WifiConfiguration.Status.ENABLED;
525 } else
526 config.status = WifiConfiguration.Status.ENABLED;
527 synchronized (mWifiStateTracker) {
528 readNetworkVariables(config);
529 }
530 networks.add(config);
531 }
532
533 return networks;
534 }
535
536 /**
537 * Read the variables from the supplicant daemon that are needed to
538 * fill in the WifiConfiguration object.
539 * <p/>
540 * The caller must hold the synchronization monitor.
541 * @param config the {@link WifiConfiguration} object to be filled in.
542 */
543 private static void readNetworkVariables(WifiConfiguration config) {
544
545 int netId = config.networkId;
546 if (netId < 0)
547 return;
548
549 /*
550 * TODO: maybe should have a native method that takes an array of
551 * variable names and returns an array of values. But we'd still
552 * be doing a round trip to the supplicant daemon for each variable.
553 */
554 String value;
555
556 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
557 if (!TextUtils.isEmpty(value)) {
558 config.SSID = value;
559 } else {
560 config.SSID = null;
561 }
562
563 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
564 if (!TextUtils.isEmpty(value)) {
565 config.BSSID = value;
566 } else {
567 config.BSSID = null;
568 }
569
570 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
571 config.priority = -1;
572 if (!TextUtils.isEmpty(value)) {
573 try {
574 config.priority = Integer.parseInt(value);
575 } catch (NumberFormatException ignore) {
576 }
577 }
578
579 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
580 config.hiddenSSID = false;
581 if (!TextUtils.isEmpty(value)) {
582 try {
583 config.hiddenSSID = Integer.parseInt(value) != 0;
584 } catch (NumberFormatException ignore) {
585 }
586 }
587
588 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
589 config.wepTxKeyIndex = -1;
590 if (!TextUtils.isEmpty(value)) {
591 try {
592 config.wepTxKeyIndex = Integer.parseInt(value);
593 } catch (NumberFormatException ignore) {
594 }
595 }
596
597 /*
598 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
599 * just a "*" if the key is set, or the null string otherwise.
600 */
601 for (int i = 0; i < 4; i++) {
602 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
603 if (!TextUtils.isEmpty(value)) {
604 config.wepKeys[i] = value;
605 } else {
606 config.wepKeys[i] = null;
607 }
608 }
609
610 /*
611 * Get the private shared key. Note that the actual keys are not passed back,
612 * just a "*" if the key is set, or the null string otherwise.
613 */
614 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
615 if (!TextUtils.isEmpty(value)) {
616 config.preSharedKey = value;
617 } else {
618 config.preSharedKey = null;
619 }
620
621 value = WifiNative.getNetworkVariableCommand(config.networkId,
622 WifiConfiguration.Protocol.varName);
623 if (!TextUtils.isEmpty(value)) {
624 String vals[] = value.split(" ");
625 for (String val : vals) {
626 int index =
627 lookupString(val, WifiConfiguration.Protocol.strings);
628 if (0 <= index) {
629 config.allowedProtocols.set(index);
630 }
631 }
632 }
633
634 value = WifiNative.getNetworkVariableCommand(config.networkId,
635 WifiConfiguration.KeyMgmt.varName);
636 if (!TextUtils.isEmpty(value)) {
637 String vals[] = value.split(" ");
638 for (String val : vals) {
639 int index =
640 lookupString(val, WifiConfiguration.KeyMgmt.strings);
641 if (0 <= index) {
642 config.allowedKeyManagement.set(index);
643 }
644 }
645 }
646
647 value = WifiNative.getNetworkVariableCommand(config.networkId,
648 WifiConfiguration.AuthAlgorithm.varName);
649 if (!TextUtils.isEmpty(value)) {
650 String vals[] = value.split(" ");
651 for (String val : vals) {
652 int index =
653 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
654 if (0 <= index) {
655 config.allowedAuthAlgorithms.set(index);
656 }
657 }
658 }
659
660 value = WifiNative.getNetworkVariableCommand(config.networkId,
661 WifiConfiguration.PairwiseCipher.varName);
662 if (!TextUtils.isEmpty(value)) {
663 String vals[] = value.split(" ");
664 for (String val : vals) {
665 int index =
666 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
667 if (0 <= index) {
668 config.allowedPairwiseCiphers.set(index);
669 }
670 }
671 }
672
673 value = WifiNative.getNetworkVariableCommand(config.networkId,
674 WifiConfiguration.GroupCipher.varName);
675 if (!TextUtils.isEmpty(value)) {
676 String vals[] = value.split(" ");
677 for (String val : vals) {
678 int index =
679 lookupString(val, WifiConfiguration.GroupCipher.strings);
680 if (0 <= index) {
681 config.allowedGroupCiphers.set(index);
682 }
683 }
684 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800685
686 for (WifiConfiguration.EnterpriseField field :
687 config.enterpriseFields) {
688 value = WifiNative.getNetworkVariableCommand(netId,
689 field.varName());
690 if (!TextUtils.isEmpty(value)) {
691 field.setValue(value);
692 }
693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 }
695
696 /**
697 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
698 * @return the supplicant-assigned identifier for the new or updated
699 * network if the operation succeeds, or {@code -1} if it fails
700 */
701 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
702 enforceChangePermission();
703 /*
704 * If the supplied networkId is -1, we create a new empty
705 * network configuration. Otherwise, the networkId should
706 * refer to an existing configuration.
707 */
708 int netId = config.networkId;
709 boolean newNetwork = netId == -1;
710 boolean doReconfig;
711 int currentPriority;
712 // networkId of -1 means we want to create a new network
713 if (newNetwork) {
714 netId = WifiNative.addNetworkCommand();
715 if (netId < 0) {
716 if (DBG) {
717 Log.d(TAG, "Failed to add a network!");
718 }
719 return -1;
720 }
721 doReconfig = true;
722 } else {
723 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
724 currentPriority = -1;
725 if (!TextUtils.isEmpty(priorityVal)) {
726 try {
727 currentPriority = Integer.parseInt(priorityVal);
728 } catch (NumberFormatException ignore) {
729 }
730 }
731 doReconfig = currentPriority != config.priority;
732 }
733 mNeedReconfig = mNeedReconfig || doReconfig;
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 setVariables: {
736 /*
737 * Note that if a networkId for a non-existent network
738 * was supplied, then the first setNetworkVariableCommand()
739 * will fail, so we don't bother to make a separate check
740 * for the validity of the ID up front.
741 */
742
743 if (config.SSID != null &&
744 !WifiNative.setNetworkVariableCommand(
745 netId,
746 WifiConfiguration.ssidVarName,
747 config.SSID)) {
748 if (DBG) {
749 Log.d(TAG, "failed to set SSID: "+config.SSID);
750 }
751 break setVariables;
752 }
753
754 if (config.BSSID != null &&
755 !WifiNative.setNetworkVariableCommand(
756 netId,
757 WifiConfiguration.bssidVarName,
758 config.BSSID)) {
759 if (DBG) {
760 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
761 }
762 break setVariables;
763 }
764
765 String allowedKeyManagementString =
766 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
767 if (config.allowedKeyManagement.cardinality() != 0 &&
768 !WifiNative.setNetworkVariableCommand(
769 netId,
770 WifiConfiguration.KeyMgmt.varName,
771 allowedKeyManagementString)) {
772 if (DBG) {
773 Log.d(TAG, "failed to set key_mgmt: "+
774 allowedKeyManagementString);
775 }
776 break setVariables;
777 }
778
779 String allowedProtocolsString =
780 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
781 if (config.allowedProtocols.cardinality() != 0 &&
782 !WifiNative.setNetworkVariableCommand(
783 netId,
784 WifiConfiguration.Protocol.varName,
785 allowedProtocolsString)) {
786 if (DBG) {
787 Log.d(TAG, "failed to set proto: "+
788 allowedProtocolsString);
789 }
790 break setVariables;
791 }
792
793 String allowedAuthAlgorithmsString =
794 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
795 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
796 !WifiNative.setNetworkVariableCommand(
797 netId,
798 WifiConfiguration.AuthAlgorithm.varName,
799 allowedAuthAlgorithmsString)) {
800 if (DBG) {
801 Log.d(TAG, "failed to set auth_alg: "+
802 allowedAuthAlgorithmsString);
803 }
804 break setVariables;
805 }
806
807 String allowedPairwiseCiphersString =
808 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
809 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
810 !WifiNative.setNetworkVariableCommand(
811 netId,
812 WifiConfiguration.PairwiseCipher.varName,
813 allowedPairwiseCiphersString)) {
814 if (DBG) {
815 Log.d(TAG, "failed to set pairwise: "+
816 allowedPairwiseCiphersString);
817 }
818 break setVariables;
819 }
820
821 String allowedGroupCiphersString =
822 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
823 if (config.allowedGroupCiphers.cardinality() != 0 &&
824 !WifiNative.setNetworkVariableCommand(
825 netId,
826 WifiConfiguration.GroupCipher.varName,
827 allowedGroupCiphersString)) {
828 if (DBG) {
829 Log.d(TAG, "failed to set group: "+
830 allowedGroupCiphersString);
831 }
832 break setVariables;
833 }
834
835 // Prevent client screw-up by passing in a WifiConfiguration we gave it
836 // by preventing "*" as a key.
837 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
838 !WifiNative.setNetworkVariableCommand(
839 netId,
840 WifiConfiguration.pskVarName,
841 config.preSharedKey)) {
842 if (DBG) {
843 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
844 }
845 break setVariables;
846 }
847
848 boolean hasSetKey = false;
849 if (config.wepKeys != null) {
850 for (int i = 0; i < config.wepKeys.length; i++) {
851 // Prevent client screw-up by passing in a WifiConfiguration we gave it
852 // by preventing "*" as a key.
853 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
854 if (!WifiNative.setNetworkVariableCommand(
855 netId,
856 WifiConfiguration.wepKeyVarNames[i],
857 config.wepKeys[i])) {
858 if (DBG) {
859 Log.d(TAG,
860 "failed to set wep_key"+i+": " +
861 config.wepKeys[i]);
862 }
863 break setVariables;
864 }
865 hasSetKey = true;
866 }
867 }
868 }
869
870 if (hasSetKey) {
871 if (!WifiNative.setNetworkVariableCommand(
872 netId,
873 WifiConfiguration.wepTxKeyIdxVarName,
874 Integer.toString(config.wepTxKeyIndex))) {
875 if (DBG) {
876 Log.d(TAG,
877 "failed to set wep_tx_keyidx: "+
878 config.wepTxKeyIndex);
879 }
880 break setVariables;
881 }
882 }
883
884 if (!WifiNative.setNetworkVariableCommand(
885 netId,
886 WifiConfiguration.priorityVarName,
887 Integer.toString(config.priority))) {
888 if (DBG) {
889 Log.d(TAG, config.SSID + ": failed to set priority: "
890 +config.priority);
891 }
892 break setVariables;
893 }
894
895 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
896 netId,
897 WifiConfiguration.hiddenSSIDVarName,
898 Integer.toString(config.hiddenSSID ? 1 : 0))) {
899 if (DBG) {
900 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
901 config.hiddenSSID);
902 }
903 break setVariables;
904 }
905
Chung-yih Wang43374762009-09-16 14:28:42 +0800906 for (WifiConfiguration.EnterpriseField field
907 : config.enterpriseFields) {
908 String varName = field.varName();
909 String value = field.value();
910 if ((value != null) && !WifiNative.setNetworkVariableCommand(
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800911 netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800912 varName,
913 value)) {
914 if (DBG) {
915 Log.d(TAG, config.SSID + ": failed to set " + varName +
916 ": " + value);
917 }
918 break setVariables;
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800919 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800920 }
921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 return netId;
923 }
924
925 /*
926 * For an update, if one of the setNetworkVariable operations fails,
927 * we might want to roll back all the changes already made. But the
928 * chances are that if anything is going to go wrong, it'll happen
929 * the first time we try to set one of the variables.
930 */
931 if (newNetwork) {
932 removeNetwork(netId);
933 if (DBG) {
934 Log.d(TAG,
935 "Failed to set a network variable, removed network: "
936 + netId);
937 }
938 }
939 return -1;
940 }
941
942 private static String makeString(BitSet set, String[] strings) {
943 StringBuffer buf = new StringBuffer();
944 int nextSetBit = -1;
945
946 /* Make sure all set bits are in [0, strings.length) to avoid
947 * going out of bounds on strings. (Shouldn't happen, but...) */
948 set = set.get(0, strings.length);
949
950 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
951 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
952 }
953
954 // remove trailing space
955 if (set.cardinality() > 0) {
956 buf.setLength(buf.length() - 1);
957 }
958
959 return buf.toString();
960 }
961
962 private static int lookupString(String string, String[] strings) {
963 int size = strings.length;
964
965 string = string.replace('-', '_');
966
967 for (int i = 0; i < size; i++)
968 if (string.equals(strings[i]))
969 return i;
970
971 if (DBG) {
972 // if we ever get here, we should probably add the
973 // value to WifiConfiguration to reflect that it's
974 // supported by the WPA supplicant
975 Log.w(TAG, "Failed to look-up a string: " + string);
976 }
977
978 return -1;
979 }
980
981 /**
982 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
983 * @param netId the integer that identifies the network configuration
984 * to the supplicant
985 * @return {@code true} if the operation succeeded
986 */
987 public boolean removeNetwork(int netId) {
988 enforceChangePermission();
989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 return mWifiStateTracker.removeNetwork(netId);
991 }
992
993 /**
994 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
995 * @param netId the integer that identifies the network configuration
996 * to the supplicant
997 * @param disableOthers if true, disable all other networks.
998 * @return {@code true} if the operation succeeded
999 */
1000 public boolean enableNetwork(int netId, boolean disableOthers) {
1001 enforceChangePermission();
1002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001004 String ifname = mWifiStateTracker.getInterfaceName();
1005 NetworkUtils.enableInterface(ifname);
1006 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1007 if (!result) {
1008 NetworkUtils.disableInterface(ifname);
1009 }
1010 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
1012 }
1013
1014 /**
1015 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1016 * @param netId the integer that identifies the network configuration
1017 * to the supplicant
1018 * @return {@code true} if the operation succeeded
1019 */
1020 public boolean disableNetwork(int netId) {
1021 enforceChangePermission();
1022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 synchronized (mWifiStateTracker) {
1024 return WifiNative.disableNetworkCommand(netId);
1025 }
1026 }
1027
1028 /**
1029 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1030 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1031 */
1032 public WifiInfo getConnectionInfo() {
1033 enforceAccessPermission();
1034 /*
1035 * Make sure we have the latest information, by sending
1036 * a status request to the supplicant.
1037 */
1038 return mWifiStateTracker.requestConnectionInfo();
1039 }
1040
1041 /**
1042 * Return the results of the most recent access point scan, in the form of
1043 * a list of {@link ScanResult} objects.
1044 * @return the list of results
1045 */
1046 public List<ScanResult> getScanResults() {
1047 enforceAccessPermission();
1048 String reply;
1049 synchronized (mWifiStateTracker) {
1050 reply = WifiNative.scanResultsCommand();
1051 }
1052 if (reply == null) {
1053 return null;
1054 }
1055
1056 List<ScanResult> scanList = new ArrayList<ScanResult>();
1057
1058 int lineCount = 0;
1059
1060 int replyLen = reply.length();
1061 // Parse the result string, keeping in mind that the last line does
1062 // not end with a newline.
1063 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1064 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1065 ++lineCount;
1066 /*
1067 * Skip the first line, which is a header
1068 */
1069 if (lineCount == 1) {
1070 lineBeg = lineEnd + 1;
1071 continue;
1072 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001073 if (lineEnd > lineBeg) {
1074 String line = reply.substring(lineBeg, lineEnd);
1075 ScanResult scanResult = parseScanResult(line);
1076 if (scanResult != null) {
1077 scanList.add(scanResult);
1078 } else if (DBG) {
1079 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081 }
1082 lineBeg = lineEnd + 1;
1083 }
1084 }
1085 mWifiStateTracker.setScanResultsList(scanList);
1086 return scanList;
1087 }
1088
1089 /**
1090 * Parse the scan result line passed to us by wpa_supplicant (helper).
1091 * @param line the line to parse
1092 * @return the {@link ScanResult} object
1093 */
1094 private ScanResult parseScanResult(String line) {
1095 ScanResult scanResult = null;
1096 if (line != null) {
1097 /*
1098 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1099 * must synchronized here!
1100 */
1101 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001102 String[] result = scanResultPattern.split(line);
1103 if (3 <= result.length && result.length <= 5) {
1104 String bssid = result[0];
1105 // bssid | frequency | level | flags | ssid
1106 int frequency;
1107 int level;
1108 try {
1109 frequency = Integer.parseInt(result[1]);
1110 level = Integer.parseInt(result[2]);
1111 /* some implementations avoid negative values by adding 256
1112 * so we need to adjust for that here.
1113 */
1114 if (level > 0) level -= 256;
1115 } catch (NumberFormatException e) {
1116 frequency = 0;
1117 level = 0;
1118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119
Mike Lockwood1a645052009-06-25 13:01:12 -04001120 /*
1121 * The formatting of the results returned by
1122 * wpa_supplicant is intended to make the fields
1123 * line up nicely when printed,
1124 * not to make them easy to parse. So we have to
1125 * apply some heuristics to figure out which field
1126 * is the SSID and which field is the flags.
1127 */
1128 String ssid;
1129 String flags;
1130 if (result.length == 4) {
1131 if (result[3].charAt(0) == '[') {
1132 flags = result[3];
1133 ssid = "";
1134 } else {
1135 flags = "";
1136 ssid = result[3];
1137 }
1138 } else if (result.length == 5) {
1139 flags = result[3];
1140 ssid = result[4];
1141 } else {
1142 // Here, we must have 3 fields: no flags and ssid
1143 // set
1144 flags = "";
1145 ssid = "";
1146 }
1147
Mike Lockwood00717e22009-08-17 10:09:36 -04001148 // bssid + ssid is the hash key
1149 String key = bssid + ssid;
1150 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001151 if (scanResult != null) {
1152 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001153 scanResult.SSID = ssid;
1154 scanResult.capabilities = flags;
1155 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001156 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 // Do not add scan results that have no SSID set
1158 if (0 < ssid.trim().length()) {
1159 scanResult =
1160 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001161 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001162 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001165 } else {
1166 Log.w(TAG, "Misformatted scan result text with " +
1167 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 }
1170 }
1171
1172 return scanResult;
1173 }
1174
1175 /**
1176 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1177 * and construct a {@code WifiConfiguration} that describes the encryption,
1178 * key management, and authenticaion capabilities of the access point.
1179 * @param flags the string returned by wpa_supplicant
1180 * @return the {@link WifiConfiguration} object, filled in
1181 */
1182 WifiConfiguration parseScanFlags(String flags) {
1183 WifiConfiguration config = new WifiConfiguration();
1184
1185 if (flags.length() == 0) {
1186 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1187 }
1188 // ... to be implemented
1189 return config;
1190 }
1191
1192 /**
1193 * Tell the supplicant to persist the current list of configured networks.
1194 * @return {@code true} if the operation succeeded
1195 */
1196 public boolean saveConfiguration() {
1197 boolean result;
1198 enforceChangePermission();
1199 synchronized (mWifiStateTracker) {
1200 result = WifiNative.saveConfigCommand();
1201 if (result && mNeedReconfig) {
1202 mNeedReconfig = false;
1203 result = WifiNative.reloadConfigCommand();
1204
1205 if (result) {
1206 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1207 mContext.sendBroadcast(intent);
1208 }
1209 }
1210 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001211 // Inform the backup manager about a data change
1212 IBackupManager ibm = IBackupManager.Stub.asInterface(
1213 ServiceManager.getService(Context.BACKUP_SERVICE));
1214 if (ibm != null) {
1215 try {
1216 ibm.dataChanged("com.android.providers.settings");
1217 } catch (Exception e) {
1218 // Try again later
1219 }
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 return result;
1222 }
1223
1224 /**
1225 * Set the number of radio frequency channels that are allowed to be used
1226 * in the current regulatory domain. This method should be used only
1227 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001228 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 * persisted as a Secure setting.
1230 * @param numChannels the number of allowed channels. Must be greater than 0
1231 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001232 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1234 * {@code numChannels} is outside the valid range.
1235 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001236 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1237 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1238 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 enforceChangePermission();
1240 /*
1241 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1242 * but if Wi-Fi isn't currently enabled, that's not possible, and
1243 * we want to persist the setting anyway,so that it will take
1244 * effect when Wi-Fi does become enabled.
1245 */
1246 boolean found = false;
1247 for (int validChan : sValidRegulatoryChannelCounts) {
1248 if (validChan == numChannels) {
1249 found = true;
1250 break;
1251 }
1252 }
1253 if (!found) {
1254 return false;
1255 }
1256
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001257 if (persist) {
1258 Settings.Secure.putInt(mContext.getContentResolver(),
1259 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1260 numChannels);
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 mWifiStateTracker.setNumAllowedChannels(numChannels);
1263 return true;
1264 }
1265
1266 /**
1267 * Return the number of frequency channels that are allowed
1268 * to be used in the current regulatory domain.
1269 * @return the number of allowed channels, or {@code -1} if an error occurs
1270 */
1271 public int getNumAllowedChannels() {
1272 int numChannels;
1273
1274 enforceAccessPermission();
1275 synchronized (mWifiStateTracker) {
1276 /*
1277 * If we can't get the value from the driver (e.g., because
1278 * Wi-Fi is not currently enabled), get the value from
1279 * Settings.
1280 */
1281 numChannels = WifiNative.getNumAllowedChannelsCommand();
1282 if (numChannels < 0) {
1283 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1284 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1285 -1);
1286 }
1287 }
1288 return numChannels;
1289 }
1290
1291 /**
1292 * Return the list of valid values for the number of allowed radio channels
1293 * for various regulatory domains.
1294 * @return the list of channel counts
1295 */
1296 public int[] getValidChannelCounts() {
1297 enforceAccessPermission();
1298 return sValidRegulatoryChannelCounts;
1299 }
1300
1301 /**
1302 * Return the DHCP-assigned addresses from the last successful DHCP request,
1303 * if any.
1304 * @return the DHCP information
1305 */
1306 public DhcpInfo getDhcpInfo() {
1307 enforceAccessPermission();
1308 return mWifiStateTracker.getDhcpInfo();
1309 }
1310
1311 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1312 @Override
1313 public void onReceive(Context context, Intent intent) {
1314 String action = intent.getAction();
1315
1316 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1317 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1318 int stayAwakeConditions =
1319 Settings.System.getInt(mContext.getContentResolver(),
1320 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1321 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001322 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 mAlarmManager.cancel(mIdleIntent);
1324 mDeviceIdle = false;
1325 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001326 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001328 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001330 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 /*
1332 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1333 * AND the "stay on while plugged in" setting doesn't match the
1334 * current power conditions (i.e, not plugged in, plugged in to USB,
1335 * or plugged in to AC).
1336 */
1337 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001338 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1339 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001340 // we used to go to sleep immediately, but this caused some race conditions
1341 // we don't have time to track down for this release. Delay instead, but not
1342 // as long as we would if connected (below)
1343 // TODO - fix the race conditions and switch back to the immediate turn-off
1344 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
1345 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
1346 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1347 // // do not keep Wifi awake when screen is off if Wifi is not associated
1348 // mDeviceIdle = true;
1349 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001350 } else {
1351 long triggerTime = System.currentTimeMillis() + idleMillis;
1352 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1353 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
1356 /* we can return now -- there's nothing to do until we get the idle intent back */
1357 return;
1358 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001359 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 mDeviceIdle = true;
1361 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1362 /*
1363 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1364 * AND we are transitioning from a state in which the device was supposed
1365 * to stay awake to a state in which it is not supposed to stay awake.
1366 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1367 * the already-set timer.
1368 */
1369 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001370 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1372 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1373 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001374 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1376 mPluggedType = pluggedType;
1377 return;
1378 }
1379 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001380 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001381 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1382 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1383 boolean isBluetoothPlaying = false;
1384 for (BluetoothDevice sink : sinks) {
1385 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1386 isBluetoothPlaying = true;
1387 }
1388 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001389 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 } else {
1392 return;
1393 }
1394
1395 updateWifiState();
1396 }
1397
1398 /**
1399 * Determines whether the Wi-Fi chipset should stay awake or be put to
1400 * sleep. Looks at the setting for the sleep policy and the current
1401 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001402 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 * @see #shouldDeviceStayAwake(int, int)
1404 */
1405 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1406 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1407 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1408
1409 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1410 // Never sleep
1411 return true;
1412 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1413 (pluggedType != 0)) {
1414 // Never sleep while plugged, and we're plugged
1415 return true;
1416 } else {
1417 // Default
1418 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1419 }
1420 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 /**
1423 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1424 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1425 * of {@code 0} isn't really a plugged type, but rather an indication that the
1426 * device isn't plugged in at all, there is no bit value corresponding to a
1427 * {@code pluggedType} value of {@code 0}. That is why we shift by
1428 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1429 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1430 * keep the device (and hence Wi-Fi) awake.
1431 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1432 * being made
1433 * @return {@code true} if {@code pluggedType} indicates that the device is
1434 * supposed to stay awake, {@code false} otherwise.
1435 */
1436 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1437 return (stayAwakeConditions & pluggedType) != 0;
1438 }
1439 };
1440
Dianne Hackborn617f8772009-03-31 15:04:46 -07001441 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 Message msg = Message.obtain(mWifiHandler,
1443 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001444 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 msg.sendToTarget();
1446 }
1447
1448 private void sendStartMessage(boolean scanOnlyMode) {
1449 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1450 }
1451
1452 private void updateWifiState() {
1453 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001454 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 boolean lockHeld = mLocks.hasLocks();
1456 int strongestLockMode;
1457 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1458 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1459 if (mDeviceIdle && lockHeld) {
1460 strongestLockMode = mLocks.getStrongestLockMode();
1461 } else {
1462 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1463 }
1464
1465 synchronized (mWifiHandler) {
1466 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1467 return;
1468 }
1469 if (wifiShouldBeEnabled) {
1470 if (wifiShouldBeStarted) {
1471 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001472 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 sWakeLock.acquire();
1474 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1475 } else {
1476 int wakeLockTimeout =
1477 Settings.Secure.getInt(
1478 mContext.getContentResolver(),
1479 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1480 DEFAULT_WAKELOCK_TIMEOUT);
1481 /*
1482 * The following wakelock is held in order to ensure
1483 * that the connectivity manager has time to fail over
1484 * to the mobile data network. The connectivity manager
1485 * releases it once mobile data connectivity has been
1486 * established. If connectivity cannot be established,
1487 * the wakelock is released after wakeLockTimeout
1488 * milliseconds have elapsed.
1489 */
1490 sDriverStopWakeLock.acquire();
1491 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1492 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1493 }
1494 } else {
1495 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001496 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 }
1499 }
1500
1501 private void registerForBroadcasts() {
1502 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1504 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1505 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1506 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001507 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 mContext.registerReceiver(mReceiver, intentFilter);
1509 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 private boolean isAirplaneSensitive() {
1512 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1513 Settings.System.AIRPLANE_MODE_RADIOS);
1514 return airplaneModeRadios == null
1515 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1516 }
1517
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001518 private boolean isAirplaneToggleable() {
1519 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1520 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1521 return toggleableRadios != null
1522 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1523 }
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 /**
1526 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1527 * currently on.
1528 * @return {@code true} if airplane mode is on.
1529 */
1530 private boolean isAirplaneModeOn() {
1531 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1532 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1533 }
1534
1535 /**
1536 * Handler that allows posting to the WifiThread.
1537 */
1538 private class WifiHandler extends Handler {
1539 public WifiHandler(Looper looper) {
1540 super(looper);
1541 }
1542
1543 @Override
1544 public void handleMessage(Message msg) {
1545 switch (msg.what) {
1546
1547 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001548 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 sWakeLock.release();
1550 break;
1551
1552 case MESSAGE_START_WIFI:
1553 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1554 mWifiStateTracker.restart();
1555 sWakeLock.release();
1556 break;
1557
1558 case MESSAGE_DISABLE_WIFI:
1559 // a non-zero msg.arg1 value means the "enabled" setting
1560 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001561 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 sWakeLock.release();
1563 break;
1564
1565 case MESSAGE_STOP_WIFI:
1566 mWifiStateTracker.disconnectAndStop();
1567 // don't release wakelock
1568 break;
1569
1570 case MESSAGE_RELEASE_WAKELOCK:
1571 synchronized (sDriverStopWakeLock) {
1572 if (sDriverStopWakeLock.isHeld()) {
1573 sDriverStopWakeLock.release();
1574 }
1575 }
1576 break;
1577 }
1578 }
1579 }
1580
1581 @Override
1582 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1583 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1584 != PackageManager.PERMISSION_GRANTED) {
1585 pw.println("Permission Denial: can't dump WifiService from from pid="
1586 + Binder.getCallingPid()
1587 + ", uid=" + Binder.getCallingUid());
1588 return;
1589 }
1590 pw.println("Wi-Fi is " + stateName(mWifiState));
1591 pw.println("Stay-awake conditions: " +
1592 Settings.System.getInt(mContext.getContentResolver(),
1593 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1594 pw.println();
1595
1596 pw.println("Internal state:");
1597 pw.println(mWifiStateTracker);
1598 pw.println();
1599 pw.println("Latest scan results:");
1600 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1601 if (scanResults != null && scanResults.size() != 0) {
1602 pw.println(" BSSID Frequency RSSI Flags SSID");
1603 for (ScanResult r : scanResults) {
1604 pw.printf(" %17s %9d %5d %-16s %s%n",
1605 r.BSSID,
1606 r.frequency,
1607 r.level,
1608 r.capabilities,
1609 r.SSID == null ? "" : r.SSID);
1610 }
1611 }
1612 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001613 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1614 mScanLocksAcquired + " scan");
1615 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1616 mScanLocksReleased + " scan");
1617 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 pw.println("Locks held:");
1619 mLocks.dump(pw);
1620 }
1621
1622 private static String stateName(int wifiState) {
1623 switch (wifiState) {
1624 case WIFI_STATE_DISABLING:
1625 return "disabling";
1626 case WIFI_STATE_DISABLED:
1627 return "disabled";
1628 case WIFI_STATE_ENABLING:
1629 return "enabling";
1630 case WIFI_STATE_ENABLED:
1631 return "enabled";
1632 case WIFI_STATE_UNKNOWN:
1633 return "unknown state";
1634 default:
1635 return "[invalid state]";
1636 }
1637 }
1638
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001639 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001641 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
1643
1644 public void binderDied() {
1645 synchronized (mLocks) {
1646 releaseWifiLockLocked(mBinder);
1647 }
1648 }
1649
1650 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001651 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653 }
1654
1655 private class LockList {
1656 private List<WifiLock> mList;
1657
1658 private LockList() {
1659 mList = new ArrayList<WifiLock>();
1660 }
1661
1662 private synchronized boolean hasLocks() {
1663 return !mList.isEmpty();
1664 }
1665
1666 private synchronized int getStrongestLockMode() {
1667 if (mList.isEmpty()) {
1668 return WifiManager.WIFI_MODE_FULL;
1669 }
1670 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001671 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 return WifiManager.WIFI_MODE_FULL;
1673 }
1674 }
1675 return WifiManager.WIFI_MODE_SCAN_ONLY;
1676 }
1677
1678 private void addLock(WifiLock lock) {
1679 if (findLockByBinder(lock.mBinder) < 0) {
1680 mList.add(lock);
1681 }
1682 }
1683
1684 private WifiLock removeLock(IBinder binder) {
1685 int index = findLockByBinder(binder);
1686 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001687 WifiLock ret = mList.remove(index);
1688 ret.unlinkDeathRecipient();
1689 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 } else {
1691 return null;
1692 }
1693 }
1694
1695 private int findLockByBinder(IBinder binder) {
1696 int size = mList.size();
1697 for (int i = size - 1; i >= 0; i--)
1698 if (mList.get(i).mBinder == binder)
1699 return i;
1700 return -1;
1701 }
1702
1703 private void dump(PrintWriter pw) {
1704 for (WifiLock l : mList) {
1705 pw.print(" ");
1706 pw.println(l);
1707 }
1708 }
1709 }
1710
1711 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1712 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1713 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1714 return false;
1715 }
1716 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1717 synchronized (mLocks) {
1718 return acquireWifiLockLocked(wifiLock);
1719 }
1720 }
1721
1722 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001723 Log.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001726
The Android Open Source Project10592532009-03-18 17:39:46 -07001727 int uid = Binder.getCallingUid();
1728 long ident = Binder.clearCallingIdentity();
1729 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001730 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001731 case WifiManager.WIFI_MODE_FULL:
1732 ++mFullLocksAcquired;
1733 mBatteryStats.noteFullWifiLockAcquired(uid);
1734 break;
1735 case WifiManager.WIFI_MODE_SCAN_ONLY:
1736 ++mScanLocksAcquired;
1737 mBatteryStats.noteScanWifiLockAcquired(uid);
1738 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001739 }
1740 } catch (RemoteException e) {
1741 } finally {
1742 Binder.restoreCallingIdentity(ident);
1743 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 updateWifiState();
1746 return true;
1747 }
1748
1749 public boolean releaseWifiLock(IBinder lock) {
1750 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1751 synchronized (mLocks) {
1752 return releaseWifiLockLocked(lock);
1753 }
1754 }
1755
1756 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001757 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001758
The Android Open Source Project10592532009-03-18 17:39:46 -07001759 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001760
1761 Log.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1762
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001763 hadLock = (wifiLock != null);
1764
1765 if (hadLock) {
1766 int uid = Binder.getCallingUid();
1767 long ident = Binder.clearCallingIdentity();
1768 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001769 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001770 case WifiManager.WIFI_MODE_FULL:
1771 ++mFullLocksReleased;
1772 mBatteryStats.noteFullWifiLockReleased(uid);
1773 break;
1774 case WifiManager.WIFI_MODE_SCAN_ONLY:
1775 ++mScanLocksReleased;
1776 mBatteryStats.noteScanWifiLockReleased(uid);
1777 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001778 }
1779 } catch (RemoteException e) {
1780 } finally {
1781 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001782 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001783 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001784 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001786 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001788
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001789 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001790 implements IBinder.DeathRecipient {
1791 String mTag;
1792 int mMode;
1793 IBinder mBinder;
1794
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001795 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001796 super();
1797 mTag = tag;
1798 mMode = mode;
1799 mBinder = binder;
1800 try {
1801 mBinder.linkToDeath(this, 0);
1802 } catch (RemoteException e) {
1803 binderDied();
1804 }
1805 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001806
1807 void unlinkDeathRecipient() {
1808 mBinder.unlinkToDeath(this, 0);
1809 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001810 }
1811
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001812 private class Multicaster extends DeathRecipient {
1813 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001814 super(Binder.getCallingUid(), tag, binder);
1815 }
1816
1817 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001818 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001819 synchronized (mMulticasters) {
1820 int i = mMulticasters.indexOf(this);
1821 if (i != -1) {
1822 removeMulticasterLocked(i, mMode);
1823 }
1824 }
1825 }
1826
1827 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001828 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001829 }
1830
1831 public int getUid() {
1832 return mMode;
1833 }
1834 }
1835
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001836 public void acquireMulticastLock(IBinder binder, String tag) {
1837 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001838
1839 synchronized (mMulticasters) {
1840 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001841 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001842 // Note that we could call stopPacketFiltering only when
1843 // our new size == 1 (first call), but this function won't
1844 // be called often and by making the stopPacket call each
1845 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001846 synchronized (mWifiStateTracker) {
1847 WifiNative.stopPacketFiltering();
1848 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001849 }
1850
1851 int uid = Binder.getCallingUid();
1852 Long ident = Binder.clearCallingIdentity();
1853 try {
1854 mBatteryStats.noteWifiMulticastEnabled(uid);
1855 } catch (RemoteException e) {
1856 } finally {
1857 Binder.restoreCallingIdentity(ident);
1858 }
1859 }
1860
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001861 public void releaseMulticastLock() {
1862 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001863
1864 int uid = Binder.getCallingUid();
1865 synchronized (mMulticasters) {
1866 mMulticastDisabled++;
1867 int size = mMulticasters.size();
1868 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001869 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001870 if ((m != null) && (m.getUid() == uid)) {
1871 removeMulticasterLocked(i, uid);
1872 }
1873 }
1874 }
1875 }
1876
1877 private void removeMulticasterLocked(int i, int uid)
1878 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001879 Multicaster removed = mMulticasters.remove(i);
1880 if (removed != null) {
1881 removed.unlinkDeathRecipient();
1882 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001883 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001884 synchronized (mWifiStateTracker) {
1885 WifiNative.startPacketFiltering();
1886 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001887 }
1888
1889 Long ident = Binder.clearCallingIdentity();
1890 try {
1891 mBatteryStats.noteWifiMulticastDisabled(uid);
1892 } catch (RemoteException e) {
1893 } finally {
1894 Binder.restoreCallingIdentity(ident);
1895 }
1896 }
1897
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001898 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001899 enforceAccessPermission();
1900
1901 synchronized (mMulticasters) {
1902 return (mMulticasters.size() > 0);
1903 }
1904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905}