blob: 53ff78e6160bc3fa6590b184d4e835708a94ee0b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.app.AlarmManager;
26import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070027import android.bluetooth.BluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
34import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
37import android.net.wifi.WifiNative;
38import android.net.wifi.WifiStateTracker;
39import android.net.wifi.ScanResult;
40import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070041import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.NetworkStateTracker;
43import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040044import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
46import android.os.Handler;
47import android.os.HandlerThread;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070052import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070054import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.provider.Settings;
56import android.util.Log;
57import android.text.TextUtils;
58
59import java.util.ArrayList;
60import java.util.BitSet;
61import java.util.HashMap;
62import java.util.LinkedHashMap;
63import java.util.List;
64import java.util.Map;
65import java.util.regex.Pattern;
66import java.io.FileDescriptor;
67import java.io.PrintWriter;
68
The Android Open Source Project10592532009-03-18 17:39:46 -070069import com.android.internal.app.IBatteryStats;
Amith Yamasani47873e52009-07-02 12:05:32 -070070import android.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.server.am.BatteryStatsService;
72
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073/**
74 * WifiService handles remote WiFi operation requests by implementing
75 * the IWifiManager interface. It also creates a WifiMonitor to listen
76 * for Wifi-related events.
77 *
78 * @hide
79 */
80public class WifiService extends IWifiManager.Stub {
81 private static final String TAG = "WifiService";
82 private static final boolean DBG = false;
83 private static final Pattern scanResultPattern = Pattern.compile("\t+");
84 private final WifiStateTracker mWifiStateTracker;
85
86 private Context mContext;
87 private int mWifiState;
88
89 private AlarmManager mAlarmManager;
90 private PendingIntent mIdleIntent;
91 private static final int IDLE_REQUEST = 0;
92 private boolean mScreenOff;
93 private boolean mDeviceIdle;
94 private int mPluggedType;
95
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070096 // true if the user enabled Wifi while in airplane mode
97 private boolean mAirplaneModeOverwridden;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700100 // some wifi lock statistics
101 private int mFullLocksAcquired;
102 private int mFullLocksReleased;
103 private int mScanLocksAcquired;
104 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700105
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700106 private final List<Multicaster> mMulticasters =
107 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700108 private int mMulticastEnabled;
109 private int mMulticastDisabled;
110
The Android Open Source Project10592532009-03-18 17:39:46 -0700111 private final IBatteryStats mBatteryStats;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 /**
114 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
115 * Settings.Gservices value is not present. This timeout value is chosen as
116 * the approximate point at which the battery drain caused by Wi-Fi
117 * being enabled but not active exceeds the battery drain caused by
118 * re-establishing a connection to the mobile data network.
119 */
120 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
121
122 private static final String WAKELOCK_TAG = "WifiService";
123
124 /**
125 * The maximum amount of time to hold the wake lock after a disconnect
126 * caused by stopping the driver. Establishing an EDGE connection has been
127 * observed to take about 5 seconds under normal circumstances. This
128 * provides a bit of extra margin.
129 * <p>
130 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
131 * This is the default value if a Settings.Secure value is not present.
132 */
133 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
134
135 // Wake lock used by driver-stop operation
136 private static PowerManager.WakeLock sDriverStopWakeLock;
137 // Wake lock used by other operations
138 private static PowerManager.WakeLock sWakeLock;
139
140 private static final int MESSAGE_ENABLE_WIFI = 0;
141 private static final int MESSAGE_DISABLE_WIFI = 1;
142 private static final int MESSAGE_STOP_WIFI = 2;
143 private static final int MESSAGE_START_WIFI = 3;
144 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
145
146 private final WifiHandler mWifiHandler;
147
148 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 * Cache of scan results objects (size is somewhat arbitrary)
150 */
151 private static final int SCAN_RESULT_CACHE_SIZE = 80;
152 private final LinkedHashMap<String, ScanResult> mScanResultCache;
153
154 /*
155 * Character buffer used to parse scan results (optimization)
156 */
157 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private boolean mNeedReconfig;
159
Dianne Hackborn617f8772009-03-31 15:04:46 -0700160 /*
161 * Last UID that asked to enable WIFI.
162 */
163 private int mLastEnableUid = Process.myUid();
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 /**
166 * Number of allowed radio frequency channels in various regulatory domains.
167 * This list is sufficient for 802.11b/g networks (2.4GHz range).
168 */
169 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
170
171 private static final String ACTION_DEVICE_IDLE =
172 "com.android.server.WifiManager.action.DEVICE_IDLE";
173
174 WifiService(Context context, WifiStateTracker tracker) {
175 mContext = context;
176 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400177 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700178 mBatteryStats = BatteryStatsService.getService();
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 mScanResultCache = new LinkedHashMap<String, ScanResult>(
181 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
182 /*
183 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
184 * elements
185 */
186 public boolean removeEldestEntry(Map.Entry eldest) {
187 return SCAN_RESULT_CACHE_SIZE < this.size();
188 }
189 };
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 HandlerThread wifiThread = new HandlerThread("WifiService");
192 wifiThread.start();
193 mWifiHandler = new WifiHandler(wifiThread.getLooper());
194
195 mWifiState = WIFI_STATE_DISABLED;
196 boolean wifiEnabled = getPersistedWifiEnabled();
197
198 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
199 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
200 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
201
202 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
203 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
204 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
205 mWifiStateTracker.setReleaseWakeLockCallback(
206 new Runnable() {
207 public void run() {
208 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
209 synchronized (sDriverStopWakeLock) {
210 if (sDriverStopWakeLock.isHeld()) {
211 sDriverStopWakeLock.release();
212 }
213 }
214 }
215 }
216 );
217
218 Log.i(TAG, "WifiService starting up with Wi-Fi " +
219 (wifiEnabled ? "enabled" : "disabled"));
220
221 mContext.registerReceiver(
222 new BroadcastReceiver() {
223 @Override
224 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700225 // clear our flag indicating the user has overwridden airplane mode
226 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 updateWifiState();
228 }
229 },
230 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
231
Dianne Hackborn617f8772009-03-31 15:04:46 -0700232 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 }
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private boolean getPersistedWifiEnabled() {
236 final ContentResolver cr = mContext.getContentResolver();
237 try {
238 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
239 } catch (Settings.SettingNotFoundException e) {
240 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
241 return false;
242 }
243 }
244
245 private void persistWifiEnabled(boolean enabled) {
246 final ContentResolver cr = mContext.getContentResolver();
247 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
248 }
249
250 NetworkStateTracker getNetworkStateTracker() {
251 return mWifiStateTracker;
252 }
253
254 /**
255 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
256 * @return {@code true} if the operation succeeds
257 */
258 public boolean pingSupplicant() {
259 enforceChangePermission();
260 synchronized (mWifiStateTracker) {
261 return WifiNative.pingCommand();
262 }
263 }
264
265 /**
266 * see {@link android.net.wifi.WifiManager#startScan()}
267 * @return {@code true} if the operation succeeds
268 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400269 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 enforceChangePermission();
271 synchronized (mWifiStateTracker) {
272 switch (mWifiStateTracker.getSupplicantState()) {
273 case DISCONNECTED:
274 case INACTIVE:
275 case SCANNING:
276 case DORMANT:
277 break;
278 default:
279 WifiNative.setScanResultHandlingCommand(
280 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
281 break;
282 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400283 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 }
286
287 /**
288 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
289 * @param enable {@code true} to enable, {@code false} to disable.
290 * @return {@code true} if the enable/disable operation was
291 * started or is already in the queue.
292 */
293 public boolean setWifiEnabled(boolean enable) {
294 enforceChangePermission();
295 if (mWifiHandler == null) return false;
296
297 synchronized (mWifiHandler) {
298 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700299 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700300 // set a flag if the user is enabling Wifi while in airplane mode
301 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700302 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 }
304
305 return true;
306 }
307
308 /**
309 * Enables/disables Wi-Fi synchronously.
310 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
311 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700312 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 * @return {@code true} if the operation succeeds (or if the existing state
314 * is the same as the requested state)
315 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700316 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
318
319 if (mWifiState == eventualWifiState) {
320 return true;
321 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700322 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 return false;
324 }
325
Dianne Hackborn617f8772009-03-31 15:04:46 -0700326 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327
328 if (enable) {
329 if (!WifiNative.loadDriver()) {
330 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700331 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 return false;
333 }
334 if (!WifiNative.startSupplicant()) {
335 WifiNative.unloadDriver();
336 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700337 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 return false;
339 }
340 registerForBroadcasts();
341 mWifiStateTracker.startEventLoop();
342 } else {
343
344 mContext.unregisterReceiver(mReceiver);
345 // Remove notification (it will no-op if it isn't visible)
346 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
347
348 boolean failedToStopSupplicantOrUnloadDriver = false;
349 if (!WifiNative.stopSupplicant()) {
350 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700351 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 failedToStopSupplicantOrUnloadDriver = true;
353 }
354
355 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400356 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
358 if (!WifiNative.unloadDriver()) {
359 Log.e(TAG, "Failed to unload Wi-Fi driver.");
360 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700361 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 failedToStopSupplicantOrUnloadDriver = true;
363 }
364 }
365 if (failedToStopSupplicantOrUnloadDriver) {
366 return false;
367 }
368 }
369
370 // Success!
371
372 if (persist) {
373 persistWifiEnabled(enable);
374 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700375 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 return true;
378 }
379
Dianne Hackborn617f8772009-03-31 15:04:46 -0700380 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 final int previousWifiState = mWifiState;
382
The Android Open Source Project10592532009-03-18 17:39:46 -0700383 long ident = Binder.clearCallingIdentity();
384 try {
385 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700386 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700387 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700388 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700389 }
390 } catch (RemoteException e) {
391 } finally {
392 Binder.restoreCallingIdentity(ident);
393 }
394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 // Update state
396 mWifiState = wifiState;
397
398 // Broadcast
399 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
401 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
402 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
403 mContext.sendStickyBroadcast(intent);
404 }
405
406 private void enforceAccessPermission() {
407 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
408 "WifiService");
409 }
410
411 private void enforceChangePermission() {
412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
413 "WifiService");
414
415 }
416
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700417 private void enforceMulticastChangePermission() {
418 mContext.enforceCallingOrSelfPermission(
419 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
420 "WifiService");
421 }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 /**
424 * see {@link WifiManager#getWifiState()}
425 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
426 * {@link WifiManager#WIFI_STATE_DISABLING},
427 * {@link WifiManager#WIFI_STATE_ENABLED},
428 * {@link WifiManager#WIFI_STATE_ENABLING},
429 * {@link WifiManager#WIFI_STATE_UNKNOWN}
430 */
431 public int getWifiEnabledState() {
432 enforceAccessPermission();
433 return mWifiState;
434 }
435
436 /**
437 * see {@link android.net.wifi.WifiManager#disconnect()}
438 * @return {@code true} if the operation succeeds
439 */
440 public boolean disconnect() {
441 enforceChangePermission();
442 synchronized (mWifiStateTracker) {
443 return WifiNative.disconnectCommand();
444 }
445 }
446
447 /**
448 * see {@link android.net.wifi.WifiManager#reconnect()}
449 * @return {@code true} if the operation succeeds
450 */
451 public boolean reconnect() {
452 enforceChangePermission();
453 synchronized (mWifiStateTracker) {
454 return WifiNative.reconnectCommand();
455 }
456 }
457
458 /**
459 * see {@link android.net.wifi.WifiManager#reassociate()}
460 * @return {@code true} if the operation succeeds
461 */
462 public boolean reassociate() {
463 enforceChangePermission();
464 synchronized (mWifiStateTracker) {
465 return WifiNative.reassociateCommand();
466 }
467 }
468
469 /**
470 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
471 * @return the list of configured networks
472 */
473 public List<WifiConfiguration> getConfiguredNetworks() {
474 enforceAccessPermission();
475 String listStr;
476 /*
477 * We don't cache the list, because we want to allow
478 * for the possibility that the configuration file
479 * has been modified through some external means,
480 * such as the wpa_cli command line program.
481 */
482 synchronized (mWifiStateTracker) {
483 listStr = WifiNative.listNetworksCommand();
484 }
485 List<WifiConfiguration> networks =
486 new ArrayList<WifiConfiguration>();
487 if (listStr == null)
488 return networks;
489
490 String[] lines = listStr.split("\n");
491 // Skip the first line, which is a header
492 for (int i = 1; i < lines.length; i++) {
493 String[] result = lines[i].split("\t");
494 // network-id | ssid | bssid | flags
495 WifiConfiguration config = new WifiConfiguration();
496 try {
497 config.networkId = Integer.parseInt(result[0]);
498 } catch(NumberFormatException e) {
499 continue;
500 }
501 if (result.length > 3) {
502 if (result[3].indexOf("[CURRENT]") != -1)
503 config.status = WifiConfiguration.Status.CURRENT;
504 else if (result[3].indexOf("[DISABLED]") != -1)
505 config.status = WifiConfiguration.Status.DISABLED;
506 else
507 config.status = WifiConfiguration.Status.ENABLED;
508 } else
509 config.status = WifiConfiguration.Status.ENABLED;
510 synchronized (mWifiStateTracker) {
511 readNetworkVariables(config);
512 }
513 networks.add(config);
514 }
515
516 return networks;
517 }
518
519 /**
520 * Read the variables from the supplicant daemon that are needed to
521 * fill in the WifiConfiguration object.
522 * <p/>
523 * The caller must hold the synchronization monitor.
524 * @param config the {@link WifiConfiguration} object to be filled in.
525 */
526 private static void readNetworkVariables(WifiConfiguration config) {
527
528 int netId = config.networkId;
529 if (netId < 0)
530 return;
531
532 /*
533 * TODO: maybe should have a native method that takes an array of
534 * variable names and returns an array of values. But we'd still
535 * be doing a round trip to the supplicant daemon for each variable.
536 */
537 String value;
538
539 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
540 if (!TextUtils.isEmpty(value)) {
541 config.SSID = value;
542 } else {
543 config.SSID = null;
544 }
545
546 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
547 if (!TextUtils.isEmpty(value)) {
548 config.BSSID = value;
549 } else {
550 config.BSSID = null;
551 }
552
553 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
554 config.priority = -1;
555 if (!TextUtils.isEmpty(value)) {
556 try {
557 config.priority = Integer.parseInt(value);
558 } catch (NumberFormatException ignore) {
559 }
560 }
561
562 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
563 config.hiddenSSID = false;
564 if (!TextUtils.isEmpty(value)) {
565 try {
566 config.hiddenSSID = Integer.parseInt(value) != 0;
567 } catch (NumberFormatException ignore) {
568 }
569 }
570
571 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
572 config.wepTxKeyIndex = -1;
573 if (!TextUtils.isEmpty(value)) {
574 try {
575 config.wepTxKeyIndex = Integer.parseInt(value);
576 } catch (NumberFormatException ignore) {
577 }
578 }
579
580 /*
581 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
582 * just a "*" if the key is set, or the null string otherwise.
583 */
584 for (int i = 0; i < 4; i++) {
585 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
586 if (!TextUtils.isEmpty(value)) {
587 config.wepKeys[i] = value;
588 } else {
589 config.wepKeys[i] = null;
590 }
591 }
592
593 /*
594 * Get the private shared key. Note that the actual keys are not passed back,
595 * just a "*" if the key is set, or the null string otherwise.
596 */
597 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
598 if (!TextUtils.isEmpty(value)) {
599 config.preSharedKey = value;
600 } else {
601 config.preSharedKey = null;
602 }
603
604 value = WifiNative.getNetworkVariableCommand(config.networkId,
605 WifiConfiguration.Protocol.varName);
606 if (!TextUtils.isEmpty(value)) {
607 String vals[] = value.split(" ");
608 for (String val : vals) {
609 int index =
610 lookupString(val, WifiConfiguration.Protocol.strings);
611 if (0 <= index) {
612 config.allowedProtocols.set(index);
613 }
614 }
615 }
616
617 value = WifiNative.getNetworkVariableCommand(config.networkId,
618 WifiConfiguration.KeyMgmt.varName);
619 if (!TextUtils.isEmpty(value)) {
620 String vals[] = value.split(" ");
621 for (String val : vals) {
622 int index =
623 lookupString(val, WifiConfiguration.KeyMgmt.strings);
624 if (0 <= index) {
625 config.allowedKeyManagement.set(index);
626 }
627 }
628 }
629
630 value = WifiNative.getNetworkVariableCommand(config.networkId,
631 WifiConfiguration.AuthAlgorithm.varName);
632 if (!TextUtils.isEmpty(value)) {
633 String vals[] = value.split(" ");
634 for (String val : vals) {
635 int index =
636 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
637 if (0 <= index) {
638 config.allowedAuthAlgorithms.set(index);
639 }
640 }
641 }
642
643 value = WifiNative.getNetworkVariableCommand(config.networkId,
644 WifiConfiguration.PairwiseCipher.varName);
645 if (!TextUtils.isEmpty(value)) {
646 String vals[] = value.split(" ");
647 for (String val : vals) {
648 int index =
649 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
650 if (0 <= index) {
651 config.allowedPairwiseCiphers.set(index);
652 }
653 }
654 }
655
656 value = WifiNative.getNetworkVariableCommand(config.networkId,
657 WifiConfiguration.GroupCipher.varName);
658 if (!TextUtils.isEmpty(value)) {
659 String vals[] = value.split(" ");
660 for (String val : vals) {
661 int index =
662 lookupString(val, WifiConfiguration.GroupCipher.strings);
663 if (0 <= index) {
664 config.allowedGroupCiphers.set(index);
665 }
666 }
667 }
668 }
669
670 /**
671 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
672 * @return the supplicant-assigned identifier for the new or updated
673 * network if the operation succeeds, or {@code -1} if it fails
674 */
675 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
676 enforceChangePermission();
677 /*
678 * If the supplied networkId is -1, we create a new empty
679 * network configuration. Otherwise, the networkId should
680 * refer to an existing configuration.
681 */
682 int netId = config.networkId;
683 boolean newNetwork = netId == -1;
684 boolean doReconfig;
685 int currentPriority;
686 // networkId of -1 means we want to create a new network
687 if (newNetwork) {
688 netId = WifiNative.addNetworkCommand();
689 if (netId < 0) {
690 if (DBG) {
691 Log.d(TAG, "Failed to add a network!");
692 }
693 return -1;
694 }
695 doReconfig = true;
696 } else {
697 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
698 currentPriority = -1;
699 if (!TextUtils.isEmpty(priorityVal)) {
700 try {
701 currentPriority = Integer.parseInt(priorityVal);
702 } catch (NumberFormatException ignore) {
703 }
704 }
705 doReconfig = currentPriority != config.priority;
706 }
707 mNeedReconfig = mNeedReconfig || doReconfig;
708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 setVariables: {
710 /*
711 * Note that if a networkId for a non-existent network
712 * was supplied, then the first setNetworkVariableCommand()
713 * will fail, so we don't bother to make a separate check
714 * for the validity of the ID up front.
715 */
716
717 if (config.SSID != null &&
718 !WifiNative.setNetworkVariableCommand(
719 netId,
720 WifiConfiguration.ssidVarName,
721 config.SSID)) {
722 if (DBG) {
723 Log.d(TAG, "failed to set SSID: "+config.SSID);
724 }
725 break setVariables;
726 }
727
728 if (config.BSSID != null &&
729 !WifiNative.setNetworkVariableCommand(
730 netId,
731 WifiConfiguration.bssidVarName,
732 config.BSSID)) {
733 if (DBG) {
734 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
735 }
736 break setVariables;
737 }
738
739 String allowedKeyManagementString =
740 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
741 if (config.allowedKeyManagement.cardinality() != 0 &&
742 !WifiNative.setNetworkVariableCommand(
743 netId,
744 WifiConfiguration.KeyMgmt.varName,
745 allowedKeyManagementString)) {
746 if (DBG) {
747 Log.d(TAG, "failed to set key_mgmt: "+
748 allowedKeyManagementString);
749 }
750 break setVariables;
751 }
752
753 String allowedProtocolsString =
754 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
755 if (config.allowedProtocols.cardinality() != 0 &&
756 !WifiNative.setNetworkVariableCommand(
757 netId,
758 WifiConfiguration.Protocol.varName,
759 allowedProtocolsString)) {
760 if (DBG) {
761 Log.d(TAG, "failed to set proto: "+
762 allowedProtocolsString);
763 }
764 break setVariables;
765 }
766
767 String allowedAuthAlgorithmsString =
768 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
769 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
770 !WifiNative.setNetworkVariableCommand(
771 netId,
772 WifiConfiguration.AuthAlgorithm.varName,
773 allowedAuthAlgorithmsString)) {
774 if (DBG) {
775 Log.d(TAG, "failed to set auth_alg: "+
776 allowedAuthAlgorithmsString);
777 }
778 break setVariables;
779 }
780
781 String allowedPairwiseCiphersString =
782 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
783 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
784 !WifiNative.setNetworkVariableCommand(
785 netId,
786 WifiConfiguration.PairwiseCipher.varName,
787 allowedPairwiseCiphersString)) {
788 if (DBG) {
789 Log.d(TAG, "failed to set pairwise: "+
790 allowedPairwiseCiphersString);
791 }
792 break setVariables;
793 }
794
795 String allowedGroupCiphersString =
796 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
797 if (config.allowedGroupCiphers.cardinality() != 0 &&
798 !WifiNative.setNetworkVariableCommand(
799 netId,
800 WifiConfiguration.GroupCipher.varName,
801 allowedGroupCiphersString)) {
802 if (DBG) {
803 Log.d(TAG, "failed to set group: "+
804 allowedGroupCiphersString);
805 }
806 break setVariables;
807 }
808
809 // Prevent client screw-up by passing in a WifiConfiguration we gave it
810 // by preventing "*" as a key.
811 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
812 !WifiNative.setNetworkVariableCommand(
813 netId,
814 WifiConfiguration.pskVarName,
815 config.preSharedKey)) {
816 if (DBG) {
817 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
818 }
819 break setVariables;
820 }
821
822 boolean hasSetKey = false;
823 if (config.wepKeys != null) {
824 for (int i = 0; i < config.wepKeys.length; i++) {
825 // Prevent client screw-up by passing in a WifiConfiguration we gave it
826 // by preventing "*" as a key.
827 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
828 if (!WifiNative.setNetworkVariableCommand(
829 netId,
830 WifiConfiguration.wepKeyVarNames[i],
831 config.wepKeys[i])) {
832 if (DBG) {
833 Log.d(TAG,
834 "failed to set wep_key"+i+": " +
835 config.wepKeys[i]);
836 }
837 break setVariables;
838 }
839 hasSetKey = true;
840 }
841 }
842 }
843
844 if (hasSetKey) {
845 if (!WifiNative.setNetworkVariableCommand(
846 netId,
847 WifiConfiguration.wepTxKeyIdxVarName,
848 Integer.toString(config.wepTxKeyIndex))) {
849 if (DBG) {
850 Log.d(TAG,
851 "failed to set wep_tx_keyidx: "+
852 config.wepTxKeyIndex);
853 }
854 break setVariables;
855 }
856 }
857
858 if (!WifiNative.setNetworkVariableCommand(
859 netId,
860 WifiConfiguration.priorityVarName,
861 Integer.toString(config.priority))) {
862 if (DBG) {
863 Log.d(TAG, config.SSID + ": failed to set priority: "
864 +config.priority);
865 }
866 break setVariables;
867 }
868
869 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
870 netId,
871 WifiConfiguration.hiddenSSIDVarName,
872 Integer.toString(config.hiddenSSID ? 1 : 0))) {
873 if (DBG) {
874 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
875 config.hiddenSSID);
876 }
877 break setVariables;
878 }
879
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800880 if ((config.eap != null) && !WifiNative.setNetworkVariableCommand(
881 netId,
882 WifiConfiguration.eapVarName,
883 config.eap)) {
884 if (DBG) {
885 Log.d(TAG, config.SSID + ": failed to set eap: "+
886 config.eap);
887 }
888 break setVariables;
889 }
890
Chung-yih Wangb96ea202009-07-22 15:56:04 +0800891 if ((config.phase2 != null) && !WifiNative.setNetworkVariableCommand(
892 netId,
893 WifiConfiguration.phase2VarName,
894 config.phase2)) {
895 if (DBG) {
896 Log.d(TAG, config.SSID + ": failed to set phase2: "+
897 config.phase2);
898 }
899 break setVariables;
900 }
901
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800902 if ((config.identity != null) && !WifiNative.setNetworkVariableCommand(
903 netId,
904 WifiConfiguration.identityVarName,
905 config.identity)) {
906 if (DBG) {
907 Log.d(TAG, config.SSID + ": failed to set identity: "+
908 config.identity);
909 }
910 break setVariables;
911 }
912
913 if ((config.anonymousIdentity != null) && !WifiNative.setNetworkVariableCommand(
914 netId,
915 WifiConfiguration.anonymousIdentityVarName,
916 config.anonymousIdentity)) {
917 if (DBG) {
918 Log.d(TAG, config.SSID + ": failed to set anonymousIdentity: "+
919 config.anonymousIdentity);
920 }
921 break setVariables;
922 }
923
Chung-yih Wang699ca3f2009-07-04 22:19:51 +0800924 if ((config.password != null) && !WifiNative.setNetworkVariableCommand(
925 netId,
926 WifiConfiguration.passwordVarName,
927 config.password)) {
928 if (DBG) {
929 Log.d(TAG, config.SSID + ": failed to set password: "+
930 config.password);
931 }
932 break setVariables;
933 }
934
Chung-yih Wang5069cc72009-06-03 17:33:47 +0800935 if ((config.clientCert != null) && !WifiNative.setNetworkVariableCommand(
936 netId,
937 WifiConfiguration.clientCertVarName,
938 config.clientCert)) {
939 if (DBG) {
940 Log.d(TAG, config.SSID + ": failed to set clientCert: "+
941 config.clientCert);
942 }
943 break setVariables;
944 }
945
946 if ((config.caCert != null) && !WifiNative.setNetworkVariableCommand(
947 netId,
948 WifiConfiguration.caCertVarName,
949 config.caCert)) {
950 if (DBG) {
951 Log.d(TAG, config.SSID + ": failed to set caCert: "+
952 config.caCert);
953 }
954 break setVariables;
955 }
956
957 if ((config.privateKey != null) && !WifiNative.setNetworkVariableCommand(
958 netId,
959 WifiConfiguration.privateKeyVarName,
960 config.privateKey)) {
961 if (DBG) {
962 Log.d(TAG, config.SSID + ": failed to set privateKey: "+
963 config.privateKey);
964 }
965 break setVariables;
966 }
967
968 if ((config.privateKeyPasswd != null) && !WifiNative.setNetworkVariableCommand(
969 netId,
970 WifiConfiguration.privateKeyPasswdVarName,
971 config.privateKeyPasswd)) {
972 if (DBG) {
973 Log.d(TAG, config.SSID + ": failed to set privateKeyPasswd: "+
974 config.privateKeyPasswd);
975 }
976 break setVariables;
977 }
978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 return netId;
980 }
981
982 /*
983 * For an update, if one of the setNetworkVariable operations fails,
984 * we might want to roll back all the changes already made. But the
985 * chances are that if anything is going to go wrong, it'll happen
986 * the first time we try to set one of the variables.
987 */
988 if (newNetwork) {
989 removeNetwork(netId);
990 if (DBG) {
991 Log.d(TAG,
992 "Failed to set a network variable, removed network: "
993 + netId);
994 }
995 }
996 return -1;
997 }
998
999 private static String makeString(BitSet set, String[] strings) {
1000 StringBuffer buf = new StringBuffer();
1001 int nextSetBit = -1;
1002
1003 /* Make sure all set bits are in [0, strings.length) to avoid
1004 * going out of bounds on strings. (Shouldn't happen, but...) */
1005 set = set.get(0, strings.length);
1006
1007 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1008 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1009 }
1010
1011 // remove trailing space
1012 if (set.cardinality() > 0) {
1013 buf.setLength(buf.length() - 1);
1014 }
1015
1016 return buf.toString();
1017 }
1018
1019 private static int lookupString(String string, String[] strings) {
1020 int size = strings.length;
1021
1022 string = string.replace('-', '_');
1023
1024 for (int i = 0; i < size; i++)
1025 if (string.equals(strings[i]))
1026 return i;
1027
1028 if (DBG) {
1029 // if we ever get here, we should probably add the
1030 // value to WifiConfiguration to reflect that it's
1031 // supported by the WPA supplicant
1032 Log.w(TAG, "Failed to look-up a string: " + string);
1033 }
1034
1035 return -1;
1036 }
1037
1038 /**
1039 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1040 * @param netId the integer that identifies the network configuration
1041 * to the supplicant
1042 * @return {@code true} if the operation succeeded
1043 */
1044 public boolean removeNetwork(int netId) {
1045 enforceChangePermission();
1046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 return mWifiStateTracker.removeNetwork(netId);
1048 }
1049
1050 /**
1051 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1052 * @param netId the integer that identifies the network configuration
1053 * to the supplicant
1054 * @param disableOthers if true, disable all other networks.
1055 * @return {@code true} if the operation succeeded
1056 */
1057 public boolean enableNetwork(int netId, boolean disableOthers) {
1058 enforceChangePermission();
1059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001061 String ifname = mWifiStateTracker.getInterfaceName();
1062 NetworkUtils.enableInterface(ifname);
1063 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1064 if (!result) {
1065 NetworkUtils.disableInterface(ifname);
1066 }
1067 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069 }
1070
1071 /**
1072 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1073 * @param netId the integer that identifies the network configuration
1074 * to the supplicant
1075 * @return {@code true} if the operation succeeded
1076 */
1077 public boolean disableNetwork(int netId) {
1078 enforceChangePermission();
1079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 synchronized (mWifiStateTracker) {
1081 return WifiNative.disableNetworkCommand(netId);
1082 }
1083 }
1084
1085 /**
1086 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1087 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1088 */
1089 public WifiInfo getConnectionInfo() {
1090 enforceAccessPermission();
1091 /*
1092 * Make sure we have the latest information, by sending
1093 * a status request to the supplicant.
1094 */
1095 return mWifiStateTracker.requestConnectionInfo();
1096 }
1097
1098 /**
1099 * Return the results of the most recent access point scan, in the form of
1100 * a list of {@link ScanResult} objects.
1101 * @return the list of results
1102 */
1103 public List<ScanResult> getScanResults() {
1104 enforceAccessPermission();
1105 String reply;
1106 synchronized (mWifiStateTracker) {
1107 reply = WifiNative.scanResultsCommand();
1108 }
1109 if (reply == null) {
1110 return null;
1111 }
1112
1113 List<ScanResult> scanList = new ArrayList<ScanResult>();
1114
1115 int lineCount = 0;
1116
1117 int replyLen = reply.length();
1118 // Parse the result string, keeping in mind that the last line does
1119 // not end with a newline.
1120 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1121 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1122 ++lineCount;
1123 /*
1124 * Skip the first line, which is a header
1125 */
1126 if (lineCount == 1) {
1127 lineBeg = lineEnd + 1;
1128 continue;
1129 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001130 if (lineEnd > lineBeg) {
1131 String line = reply.substring(lineBeg, lineEnd);
1132 ScanResult scanResult = parseScanResult(line);
1133 if (scanResult != null) {
1134 scanList.add(scanResult);
1135 } else if (DBG) {
1136 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
1138 }
1139 lineBeg = lineEnd + 1;
1140 }
1141 }
1142 mWifiStateTracker.setScanResultsList(scanList);
1143 return scanList;
1144 }
1145
1146 /**
1147 * Parse the scan result line passed to us by wpa_supplicant (helper).
1148 * @param line the line to parse
1149 * @return the {@link ScanResult} object
1150 */
1151 private ScanResult parseScanResult(String line) {
1152 ScanResult scanResult = null;
1153 if (line != null) {
1154 /*
1155 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1156 * must synchronized here!
1157 */
1158 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001159 String[] result = scanResultPattern.split(line);
1160 if (3 <= result.length && result.length <= 5) {
1161 String bssid = result[0];
1162 // bssid | frequency | level | flags | ssid
1163 int frequency;
1164 int level;
1165 try {
1166 frequency = Integer.parseInt(result[1]);
1167 level = Integer.parseInt(result[2]);
1168 /* some implementations avoid negative values by adding 256
1169 * so we need to adjust for that here.
1170 */
1171 if (level > 0) level -= 256;
1172 } catch (NumberFormatException e) {
1173 frequency = 0;
1174 level = 0;
1175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176
Mike Lockwood1a645052009-06-25 13:01:12 -04001177 /*
1178 * The formatting of the results returned by
1179 * wpa_supplicant is intended to make the fields
1180 * line up nicely when printed,
1181 * not to make them easy to parse. So we have to
1182 * apply some heuristics to figure out which field
1183 * is the SSID and which field is the flags.
1184 */
1185 String ssid;
1186 String flags;
1187 if (result.length == 4) {
1188 if (result[3].charAt(0) == '[') {
1189 flags = result[3];
1190 ssid = "";
1191 } else {
1192 flags = "";
1193 ssid = result[3];
1194 }
1195 } else if (result.length == 5) {
1196 flags = result[3];
1197 ssid = result[4];
1198 } else {
1199 // Here, we must have 3 fields: no flags and ssid
1200 // set
1201 flags = "";
1202 ssid = "";
1203 }
1204
Mike Lockwood00717e22009-08-17 10:09:36 -04001205 // bssid + ssid is the hash key
1206 String key = bssid + ssid;
1207 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001208 if (scanResult != null) {
1209 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001210 scanResult.SSID = ssid;
1211 scanResult.capabilities = flags;
1212 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001213 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 // Do not add scan results that have no SSID set
1215 if (0 < ssid.trim().length()) {
1216 scanResult =
1217 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001218 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001219 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001222 } else {
1223 Log.w(TAG, "Misformatted scan result text with " +
1224 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 }
1227 }
1228
1229 return scanResult;
1230 }
1231
1232 /**
1233 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1234 * and construct a {@code WifiConfiguration} that describes the encryption,
1235 * key management, and authenticaion capabilities of the access point.
1236 * @param flags the string returned by wpa_supplicant
1237 * @return the {@link WifiConfiguration} object, filled in
1238 */
1239 WifiConfiguration parseScanFlags(String flags) {
1240 WifiConfiguration config = new WifiConfiguration();
1241
1242 if (flags.length() == 0) {
1243 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1244 }
1245 // ... to be implemented
1246 return config;
1247 }
1248
1249 /**
1250 * Tell the supplicant to persist the current list of configured networks.
1251 * @return {@code true} if the operation succeeded
1252 */
1253 public boolean saveConfiguration() {
1254 boolean result;
1255 enforceChangePermission();
1256 synchronized (mWifiStateTracker) {
1257 result = WifiNative.saveConfigCommand();
1258 if (result && mNeedReconfig) {
1259 mNeedReconfig = false;
1260 result = WifiNative.reloadConfigCommand();
1261
1262 if (result) {
1263 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1264 mContext.sendBroadcast(intent);
1265 }
1266 }
1267 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001268 // Inform the backup manager about a data change
1269 IBackupManager ibm = IBackupManager.Stub.asInterface(
1270 ServiceManager.getService(Context.BACKUP_SERVICE));
1271 if (ibm != null) {
1272 try {
1273 ibm.dataChanged("com.android.providers.settings");
1274 } catch (Exception e) {
1275 // Try again later
1276 }
1277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 return result;
1279 }
1280
1281 /**
1282 * Set the number of radio frequency channels that are allowed to be used
1283 * in the current regulatory domain. This method should be used only
1284 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001285 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * persisted as a Secure setting.
1287 * @param numChannels the number of allowed channels. Must be greater than 0
1288 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001289 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1291 * {@code numChannels} is outside the valid range.
1292 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001293 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1294 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1295 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 enforceChangePermission();
1297 /*
1298 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1299 * but if Wi-Fi isn't currently enabled, that's not possible, and
1300 * we want to persist the setting anyway,so that it will take
1301 * effect when Wi-Fi does become enabled.
1302 */
1303 boolean found = false;
1304 for (int validChan : sValidRegulatoryChannelCounts) {
1305 if (validChan == numChannels) {
1306 found = true;
1307 break;
1308 }
1309 }
1310 if (!found) {
1311 return false;
1312 }
1313
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001314 if (persist) {
1315 Settings.Secure.putInt(mContext.getContentResolver(),
1316 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1317 numChannels);
1318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 mWifiStateTracker.setNumAllowedChannels(numChannels);
1320 return true;
1321 }
1322
1323 /**
1324 * Return the number of frequency channels that are allowed
1325 * to be used in the current regulatory domain.
1326 * @return the number of allowed channels, or {@code -1} if an error occurs
1327 */
1328 public int getNumAllowedChannels() {
1329 int numChannels;
1330
1331 enforceAccessPermission();
1332 synchronized (mWifiStateTracker) {
1333 /*
1334 * If we can't get the value from the driver (e.g., because
1335 * Wi-Fi is not currently enabled), get the value from
1336 * Settings.
1337 */
1338 numChannels = WifiNative.getNumAllowedChannelsCommand();
1339 if (numChannels < 0) {
1340 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1341 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1342 -1);
1343 }
1344 }
1345 return numChannels;
1346 }
1347
1348 /**
1349 * Return the list of valid values for the number of allowed radio channels
1350 * for various regulatory domains.
1351 * @return the list of channel counts
1352 */
1353 public int[] getValidChannelCounts() {
1354 enforceAccessPermission();
1355 return sValidRegulatoryChannelCounts;
1356 }
1357
1358 /**
1359 * Return the DHCP-assigned addresses from the last successful DHCP request,
1360 * if any.
1361 * @return the DHCP information
1362 */
1363 public DhcpInfo getDhcpInfo() {
1364 enforceAccessPermission();
1365 return mWifiStateTracker.getDhcpInfo();
1366 }
1367
1368 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1369 @Override
1370 public void onReceive(Context context, Intent intent) {
1371 String action = intent.getAction();
1372
1373 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1374 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1375 int stayAwakeConditions =
1376 Settings.System.getInt(mContext.getContentResolver(),
1377 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1378 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001379 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 mAlarmManager.cancel(mIdleIntent);
1381 mDeviceIdle = false;
1382 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001383 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001385 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001387 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 /*
1389 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1390 * AND the "stay on while plugged in" setting doesn't match the
1391 * current power conditions (i.e, not plugged in, plugged in to USB,
1392 * or plugged in to AC).
1393 */
1394 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001395 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1396 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1397 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001398 mDeviceIdle = true;
1399 updateWifiState();
1400 } else {
1401 long triggerTime = System.currentTimeMillis() + idleMillis;
1402 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1403 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406 /* we can return now -- there's nothing to do until we get the idle intent back */
1407 return;
1408 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001409 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 mDeviceIdle = true;
1411 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1412 /*
1413 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1414 * AND we are transitioning from a state in which the device was supposed
1415 * to stay awake to a state in which it is not supposed to stay awake.
1416 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1417 * the already-set timer.
1418 */
1419 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001420 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1422 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1423 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001424 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1426 mPluggedType = pluggedType;
1427 return;
1428 }
1429 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001430 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001431 boolean isBluetoothPlaying =
1432 intent.getIntExtra(
Nick Pelly005b2282009-09-10 10:21:56 -07001433 BluetoothA2dp.EXTRA_SINK_STATE,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001434 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1435 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 } else {
1437 return;
1438 }
1439
1440 updateWifiState();
1441 }
1442
1443 /**
1444 * Determines whether the Wi-Fi chipset should stay awake or be put to
1445 * sleep. Looks at the setting for the sleep policy and the current
1446 * conditions.
1447 *
1448 * @see #shouldDeviceStayAwake(int, int)
1449 */
1450 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1451 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1452 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1453
1454 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1455 // Never sleep
1456 return true;
1457 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1458 (pluggedType != 0)) {
1459 // Never sleep while plugged, and we're plugged
1460 return true;
1461 } else {
1462 // Default
1463 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1464 }
1465 }
1466
1467 /**
1468 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1469 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1470 * of {@code 0} isn't really a plugged type, but rather an indication that the
1471 * device isn't plugged in at all, there is no bit value corresponding to a
1472 * {@code pluggedType} value of {@code 0}. That is why we shift by
1473 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1474 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1475 * keep the device (and hence Wi-Fi) awake.
1476 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1477 * being made
1478 * @return {@code true} if {@code pluggedType} indicates that the device is
1479 * supposed to stay awake, {@code false} otherwise.
1480 */
1481 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1482 return (stayAwakeConditions & pluggedType) != 0;
1483 }
1484 };
1485
Dianne Hackborn617f8772009-03-31 15:04:46 -07001486 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 Message msg = Message.obtain(mWifiHandler,
1488 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001489 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 msg.sendToTarget();
1491 }
1492
1493 private void sendStartMessage(boolean scanOnlyMode) {
1494 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1495 }
1496
1497 private void updateWifiState() {
1498 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001499 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 boolean lockHeld = mLocks.hasLocks();
1501 int strongestLockMode;
1502 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1503 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1504 if (mDeviceIdle && lockHeld) {
1505 strongestLockMode = mLocks.getStrongestLockMode();
1506 } else {
1507 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1508 }
1509
1510 synchronized (mWifiHandler) {
1511 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1512 return;
1513 }
1514 if (wifiShouldBeEnabled) {
1515 if (wifiShouldBeStarted) {
1516 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001517 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 sWakeLock.acquire();
1519 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1520 } else {
1521 int wakeLockTimeout =
1522 Settings.Secure.getInt(
1523 mContext.getContentResolver(),
1524 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1525 DEFAULT_WAKELOCK_TIMEOUT);
1526 /*
1527 * The following wakelock is held in order to ensure
1528 * that the connectivity manager has time to fail over
1529 * to the mobile data network. The connectivity manager
1530 * releases it once mobile data connectivity has been
1531 * established. If connectivity cannot be established,
1532 * the wakelock is released after wakeLockTimeout
1533 * milliseconds have elapsed.
1534 */
1535 sDriverStopWakeLock.acquire();
1536 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1537 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1538 }
1539 } else {
1540 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001541 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543 }
1544 }
1545
1546 private void registerForBroadcasts() {
1547 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1549 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1550 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1551 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001552 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 mContext.registerReceiver(mReceiver, intentFilter);
1554 }
1555
1556 private boolean isAirplaneSensitive() {
1557 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1558 Settings.System.AIRPLANE_MODE_RADIOS);
1559 return airplaneModeRadios == null
1560 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1561 }
1562
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001563 private boolean isAirplaneToggleable() {
1564 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1565 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1566 return toggleableRadios != null
1567 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1568 }
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 /**
1571 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1572 * currently on.
1573 * @return {@code true} if airplane mode is on.
1574 */
1575 private boolean isAirplaneModeOn() {
1576 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1577 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1578 }
1579
1580 /**
1581 * Handler that allows posting to the WifiThread.
1582 */
1583 private class WifiHandler extends Handler {
1584 public WifiHandler(Looper looper) {
1585 super(looper);
1586 }
1587
1588 @Override
1589 public void handleMessage(Message msg) {
1590 switch (msg.what) {
1591
1592 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001593 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 sWakeLock.release();
1595 break;
1596
1597 case MESSAGE_START_WIFI:
1598 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1599 mWifiStateTracker.restart();
1600 sWakeLock.release();
1601 break;
1602
1603 case MESSAGE_DISABLE_WIFI:
1604 // a non-zero msg.arg1 value means the "enabled" setting
1605 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001606 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 sWakeLock.release();
1608 break;
1609
1610 case MESSAGE_STOP_WIFI:
1611 mWifiStateTracker.disconnectAndStop();
1612 // don't release wakelock
1613 break;
1614
1615 case MESSAGE_RELEASE_WAKELOCK:
1616 synchronized (sDriverStopWakeLock) {
1617 if (sDriverStopWakeLock.isHeld()) {
1618 sDriverStopWakeLock.release();
1619 }
1620 }
1621 break;
1622 }
1623 }
1624 }
1625
1626 @Override
1627 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1628 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1629 != PackageManager.PERMISSION_GRANTED) {
1630 pw.println("Permission Denial: can't dump WifiService from from pid="
1631 + Binder.getCallingPid()
1632 + ", uid=" + Binder.getCallingUid());
1633 return;
1634 }
1635 pw.println("Wi-Fi is " + stateName(mWifiState));
1636 pw.println("Stay-awake conditions: " +
1637 Settings.System.getInt(mContext.getContentResolver(),
1638 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1639 pw.println();
1640
1641 pw.println("Internal state:");
1642 pw.println(mWifiStateTracker);
1643 pw.println();
1644 pw.println("Latest scan results:");
1645 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1646 if (scanResults != null && scanResults.size() != 0) {
1647 pw.println(" BSSID Frequency RSSI Flags SSID");
1648 for (ScanResult r : scanResults) {
1649 pw.printf(" %17s %9d %5d %-16s %s%n",
1650 r.BSSID,
1651 r.frequency,
1652 r.level,
1653 r.capabilities,
1654 r.SSID == null ? "" : r.SSID);
1655 }
1656 }
1657 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001658 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1659 mScanLocksAcquired + " scan");
1660 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1661 mScanLocksReleased + " scan");
1662 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 pw.println("Locks held:");
1664 mLocks.dump(pw);
1665 }
1666
1667 private static String stateName(int wifiState) {
1668 switch (wifiState) {
1669 case WIFI_STATE_DISABLING:
1670 return "disabling";
1671 case WIFI_STATE_DISABLED:
1672 return "disabled";
1673 case WIFI_STATE_ENABLING:
1674 return "enabling";
1675 case WIFI_STATE_ENABLED:
1676 return "enabled";
1677 case WIFI_STATE_UNKNOWN:
1678 return "unknown state";
1679 default:
1680 return "[invalid state]";
1681 }
1682 }
1683
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001684 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001686 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688
1689 public void binderDied() {
1690 synchronized (mLocks) {
1691 releaseWifiLockLocked(mBinder);
1692 }
1693 }
1694
1695 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001696 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699
1700 private class LockList {
1701 private List<WifiLock> mList;
1702
1703 private LockList() {
1704 mList = new ArrayList<WifiLock>();
1705 }
1706
1707 private synchronized boolean hasLocks() {
1708 return !mList.isEmpty();
1709 }
1710
1711 private synchronized int getStrongestLockMode() {
1712 if (mList.isEmpty()) {
1713 return WifiManager.WIFI_MODE_FULL;
1714 }
1715 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001716 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 return WifiManager.WIFI_MODE_FULL;
1718 }
1719 }
1720 return WifiManager.WIFI_MODE_SCAN_ONLY;
1721 }
1722
1723 private void addLock(WifiLock lock) {
1724 if (findLockByBinder(lock.mBinder) < 0) {
1725 mList.add(lock);
1726 }
1727 }
1728
1729 private WifiLock removeLock(IBinder binder) {
1730 int index = findLockByBinder(binder);
1731 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001732 WifiLock ret = mList.remove(index);
1733 ret.unlinkDeathRecipient();
1734 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 } else {
1736 return null;
1737 }
1738 }
1739
1740 private int findLockByBinder(IBinder binder) {
1741 int size = mList.size();
1742 for (int i = size - 1; i >= 0; i--)
1743 if (mList.get(i).mBinder == binder)
1744 return i;
1745 return -1;
1746 }
1747
1748 private void dump(PrintWriter pw) {
1749 for (WifiLock l : mList) {
1750 pw.print(" ");
1751 pw.println(l);
1752 }
1753 }
1754 }
1755
1756 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1757 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1758 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1759 return false;
1760 }
1761 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1762 synchronized (mLocks) {
1763 return acquireWifiLockLocked(wifiLock);
1764 }
1765 }
1766
1767 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1768 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001769
1770 int uid = Binder.getCallingUid();
1771 long ident = Binder.clearCallingIdentity();
1772 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001773 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001774 case WifiManager.WIFI_MODE_FULL:
1775 ++mFullLocksAcquired;
1776 mBatteryStats.noteFullWifiLockAcquired(uid);
1777 break;
1778 case WifiManager.WIFI_MODE_SCAN_ONLY:
1779 ++mScanLocksAcquired;
1780 mBatteryStats.noteScanWifiLockAcquired(uid);
1781 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001782 }
1783 } catch (RemoteException e) {
1784 } finally {
1785 Binder.restoreCallingIdentity(ident);
1786 }
1787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 updateWifiState();
1789 return true;
1790 }
1791
1792 public boolean releaseWifiLock(IBinder lock) {
1793 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1794 synchronized (mLocks) {
1795 return releaseWifiLockLocked(lock);
1796 }
1797 }
1798
1799 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001800 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001801
1802 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001803 hadLock = (wifiLock != null);
1804
1805 if (hadLock) {
1806 int uid = Binder.getCallingUid();
1807 long ident = Binder.clearCallingIdentity();
1808 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001809 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001810 case WifiManager.WIFI_MODE_FULL:
1811 ++mFullLocksReleased;
1812 mBatteryStats.noteFullWifiLockReleased(uid);
1813 break;
1814 case WifiManager.WIFI_MODE_SCAN_ONLY:
1815 ++mScanLocksReleased;
1816 mBatteryStats.noteScanWifiLockReleased(uid);
1817 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001818 }
1819 } catch (RemoteException e) {
1820 } finally {
1821 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001822 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001823 }
1824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001826 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001828
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001829 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001830 implements IBinder.DeathRecipient {
1831 String mTag;
1832 int mMode;
1833 IBinder mBinder;
1834
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001835 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001836 super();
1837 mTag = tag;
1838 mMode = mode;
1839 mBinder = binder;
1840 try {
1841 mBinder.linkToDeath(this, 0);
1842 } catch (RemoteException e) {
1843 binderDied();
1844 }
1845 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001846
1847 void unlinkDeathRecipient() {
1848 mBinder.unlinkToDeath(this, 0);
1849 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001850 }
1851
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001852 private class Multicaster extends DeathRecipient {
1853 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001854 super(Binder.getCallingUid(), tag, binder);
1855 }
1856
1857 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001858 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001859 synchronized (mMulticasters) {
1860 int i = mMulticasters.indexOf(this);
1861 if (i != -1) {
1862 removeMulticasterLocked(i, mMode);
1863 }
1864 }
1865 }
1866
1867 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001868 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001869 }
1870
1871 public int getUid() {
1872 return mMode;
1873 }
1874 }
1875
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001876 public void acquireMulticastLock(IBinder binder, String tag) {
1877 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001878
1879 synchronized (mMulticasters) {
1880 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001881 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001882 // Note that we could call stopPacketFiltering only when
1883 // our new size == 1 (first call), but this function won't
1884 // be called often and by making the stopPacket call each
1885 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001886 synchronized (mWifiStateTracker) {
1887 WifiNative.stopPacketFiltering();
1888 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001889 }
1890
1891 int uid = Binder.getCallingUid();
1892 Long ident = Binder.clearCallingIdentity();
1893 try {
1894 mBatteryStats.noteWifiMulticastEnabled(uid);
1895 } catch (RemoteException e) {
1896 } finally {
1897 Binder.restoreCallingIdentity(ident);
1898 }
1899 }
1900
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001901 public void releaseMulticastLock() {
1902 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001903
1904 int uid = Binder.getCallingUid();
1905 synchronized (mMulticasters) {
1906 mMulticastDisabled++;
1907 int size = mMulticasters.size();
1908 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001909 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001910 if ((m != null) && (m.getUid() == uid)) {
1911 removeMulticasterLocked(i, uid);
1912 }
1913 }
1914 }
1915 }
1916
1917 private void removeMulticasterLocked(int i, int uid)
1918 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001919 Multicaster removed = mMulticasters.remove(i);
1920 if (removed != null) {
1921 removed.unlinkDeathRecipient();
1922 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001923 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04001924 synchronized (mWifiStateTracker) {
1925 WifiNative.startPacketFiltering();
1926 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001927 }
1928
1929 Long ident = Binder.clearCallingIdentity();
1930 try {
1931 mBatteryStats.noteWifiMulticastDisabled(uid);
1932 } catch (RemoteException e) {
1933 } finally {
1934 Binder.restoreCallingIdentity(ident);
1935 }
1936 }
1937
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001938 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001939 enforceAccessPermission();
1940
1941 synchronized (mMulticasters) {
1942 return (mMulticasters.size() > 0);
1943 }
1944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945}