blob: f25c221dc457eff2a17c5178675abaaf241d3ab6 [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
96 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070097 // some wifi lock statistics
98 private int mFullLocksAcquired;
99 private int mFullLocksReleased;
100 private int mScanLocksAcquired;
101 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700102
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700103 private final List<Multicaster> mMulticasters =
104 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700105 private int mMulticastEnabled;
106 private int mMulticastDisabled;
107
The Android Open Source Project10592532009-03-18 17:39:46 -0700108 private final IBatteryStats mBatteryStats;
109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 /**
111 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
112 * Settings.Gservices value is not present. This timeout value is chosen as
113 * the approximate point at which the battery drain caused by Wi-Fi
114 * being enabled but not active exceeds the battery drain caused by
115 * re-establishing a connection to the mobile data network.
116 */
117 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
118
119 private static final String WAKELOCK_TAG = "WifiService";
120
121 /**
122 * The maximum amount of time to hold the wake lock after a disconnect
123 * caused by stopping the driver. Establishing an EDGE connection has been
124 * observed to take about 5 seconds under normal circumstances. This
125 * provides a bit of extra margin.
126 * <p>
127 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
128 * This is the default value if a Settings.Secure value is not present.
129 */
130 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
131
132 // Wake lock used by driver-stop operation
133 private static PowerManager.WakeLock sDriverStopWakeLock;
134 // Wake lock used by other operations
135 private static PowerManager.WakeLock sWakeLock;
136
137 private static final int MESSAGE_ENABLE_WIFI = 0;
138 private static final int MESSAGE_DISABLE_WIFI = 1;
139 private static final int MESSAGE_STOP_WIFI = 2;
140 private static final int MESSAGE_START_WIFI = 3;
141 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
142
143 private final WifiHandler mWifiHandler;
144
145 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 * Cache of scan results objects (size is somewhat arbitrary)
147 */
148 private static final int SCAN_RESULT_CACHE_SIZE = 80;
149 private final LinkedHashMap<String, ScanResult> mScanResultCache;
150
151 /*
152 * Character buffer used to parse scan results (optimization)
153 */
154 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private boolean mNeedReconfig;
156
Dianne Hackborn617f8772009-03-31 15:04:46 -0700157 /*
158 * Last UID that asked to enable WIFI.
159 */
160 private int mLastEnableUid = Process.myUid();
161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 /**
163 * Number of allowed radio frequency channels in various regulatory domains.
164 * This list is sufficient for 802.11b/g networks (2.4GHz range).
165 */
166 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
167
168 private static final String ACTION_DEVICE_IDLE =
169 "com.android.server.WifiManager.action.DEVICE_IDLE";
170
171 WifiService(Context context, WifiStateTracker tracker) {
172 mContext = context;
173 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400174 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700175 mBatteryStats = BatteryStatsService.getService();
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 mScanResultCache = new LinkedHashMap<String, ScanResult>(
178 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
179 /*
180 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
181 * elements
182 */
183 public boolean removeEldestEntry(Map.Entry eldest) {
184 return SCAN_RESULT_CACHE_SIZE < this.size();
185 }
186 };
187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 HandlerThread wifiThread = new HandlerThread("WifiService");
189 wifiThread.start();
190 mWifiHandler = new WifiHandler(wifiThread.getLooper());
191
192 mWifiState = WIFI_STATE_DISABLED;
193 boolean wifiEnabled = getPersistedWifiEnabled();
194
195 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
196 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
197 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
198
199 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
200 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
201 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
202 mWifiStateTracker.setReleaseWakeLockCallback(
203 new Runnable() {
204 public void run() {
205 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
206 synchronized (sDriverStopWakeLock) {
207 if (sDriverStopWakeLock.isHeld()) {
208 sDriverStopWakeLock.release();
209 }
210 }
211 }
212 }
213 );
214
215 Log.i(TAG, "WifiService starting up with Wi-Fi " +
216 (wifiEnabled ? "enabled" : "disabled"));
217
218 mContext.registerReceiver(
219 new BroadcastReceiver() {
220 @Override
221 public void onReceive(Context context, Intent intent) {
222 updateWifiState();
223 }
224 },
225 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
226
Dianne Hackborn617f8772009-03-31 15:04:46 -0700227 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 }
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private boolean getPersistedWifiEnabled() {
231 final ContentResolver cr = mContext.getContentResolver();
232 try {
233 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
234 } catch (Settings.SettingNotFoundException e) {
235 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
236 return false;
237 }
238 }
239
240 private void persistWifiEnabled(boolean enabled) {
241 final ContentResolver cr = mContext.getContentResolver();
242 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
243 }
244
245 NetworkStateTracker getNetworkStateTracker() {
246 return mWifiStateTracker;
247 }
248
249 /**
250 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
251 * @return {@code true} if the operation succeeds
252 */
253 public boolean pingSupplicant() {
254 enforceChangePermission();
255 synchronized (mWifiStateTracker) {
256 return WifiNative.pingCommand();
257 }
258 }
259
260 /**
261 * see {@link android.net.wifi.WifiManager#startScan()}
262 * @return {@code true} if the operation succeeds
263 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400264 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 enforceChangePermission();
266 synchronized (mWifiStateTracker) {
267 switch (mWifiStateTracker.getSupplicantState()) {
268 case DISCONNECTED:
269 case INACTIVE:
270 case SCANNING:
271 case DORMANT:
272 break;
273 default:
274 WifiNative.setScanResultHandlingCommand(
275 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
276 break;
277 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400278 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280 }
281
282 /**
283 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
284 * @param enable {@code true} to enable, {@code false} to disable.
285 * @return {@code true} if the enable/disable operation was
286 * started or is already in the queue.
287 */
288 public boolean setWifiEnabled(boolean enable) {
289 enforceChangePermission();
290 if (mWifiHandler == null) return false;
291
292 synchronized (mWifiHandler) {
293 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700294 mLastEnableUid = Binder.getCallingUid();
295 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 }
297
298 return true;
299 }
300
301 /**
302 * Enables/disables Wi-Fi synchronously.
303 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
304 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700305 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 * @return {@code true} if the operation succeeds (or if the existing state
307 * is the same as the requested state)
308 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700309 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
311
312 if (mWifiState == eventualWifiState) {
313 return true;
314 }
315 if (enable && isAirplaneModeOn()) {
316 return false;
317 }
318
Dianne Hackborn617f8772009-03-31 15:04:46 -0700319 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320
321 if (enable) {
322 if (!WifiNative.loadDriver()) {
323 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700324 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 return false;
326 }
327 if (!WifiNative.startSupplicant()) {
328 WifiNative.unloadDriver();
329 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700330 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 return false;
332 }
333 registerForBroadcasts();
334 mWifiStateTracker.startEventLoop();
335 } else {
336
337 mContext.unregisterReceiver(mReceiver);
338 // Remove notification (it will no-op if it isn't visible)
339 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
340
341 boolean failedToStopSupplicantOrUnloadDriver = false;
342 if (!WifiNative.stopSupplicant()) {
343 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700344 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 failedToStopSupplicantOrUnloadDriver = true;
346 }
347
348 // We must reset the interface before we unload the driver
Mike Lockwood0900f362009-07-10 17:24:07 -0400349 mWifiStateTracker.resetInterface(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350
351 if (!WifiNative.unloadDriver()) {
352 Log.e(TAG, "Failed to unload Wi-Fi driver.");
353 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700354 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 failedToStopSupplicantOrUnloadDriver = true;
356 }
357 }
358 if (failedToStopSupplicantOrUnloadDriver) {
359 return false;
360 }
361 }
362
363 // Success!
364
365 if (persist) {
366 persistWifiEnabled(enable);
367 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700368 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369
370 /*
Mike Lockwood622f82a2009-07-09 23:39:01 -0400371 * Initialize the number of allowed radio channels if Wi-Fi is being turned on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 */
373 if (enable) {
374 mWifiStateTracker.setNumAllowedChannels();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
376
377 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 Lockwoodb30475e2009-04-21 13:55:07 -07001205 // bssid is the hash key
1206 scanResult = mScanResultCache.get(bssid);
1207 if (scanResult != null) {
1208 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001209 scanResult.SSID = ssid;
1210 scanResult.capabilities = flags;
1211 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001212 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 // Do not add scan results that have no SSID set
1214 if (0 < ssid.trim().length()) {
1215 scanResult =
1216 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001217 ssid, bssid, flags, level, frequency);
1218 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001221 } else {
1222 Log.w(TAG, "Misformatted scan result text with " +
1223 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226 }
1227
1228 return scanResult;
1229 }
1230
1231 /**
1232 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1233 * and construct a {@code WifiConfiguration} that describes the encryption,
1234 * key management, and authenticaion capabilities of the access point.
1235 * @param flags the string returned by wpa_supplicant
1236 * @return the {@link WifiConfiguration} object, filled in
1237 */
1238 WifiConfiguration parseScanFlags(String flags) {
1239 WifiConfiguration config = new WifiConfiguration();
1240
1241 if (flags.length() == 0) {
1242 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1243 }
1244 // ... to be implemented
1245 return config;
1246 }
1247
1248 /**
1249 * Tell the supplicant to persist the current list of configured networks.
1250 * @return {@code true} if the operation succeeded
1251 */
1252 public boolean saveConfiguration() {
1253 boolean result;
1254 enforceChangePermission();
1255 synchronized (mWifiStateTracker) {
1256 result = WifiNative.saveConfigCommand();
1257 if (result && mNeedReconfig) {
1258 mNeedReconfig = false;
1259 result = WifiNative.reloadConfigCommand();
1260
1261 if (result) {
1262 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1263 mContext.sendBroadcast(intent);
1264 }
1265 }
1266 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001267 // Inform the backup manager about a data change
1268 IBackupManager ibm = IBackupManager.Stub.asInterface(
1269 ServiceManager.getService(Context.BACKUP_SERVICE));
1270 if (ibm != null) {
1271 try {
1272 ibm.dataChanged("com.android.providers.settings");
1273 } catch (Exception e) {
1274 // Try again later
1275 }
1276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 return result;
1278 }
1279
1280 /**
1281 * Set the number of radio frequency channels that are allowed to be used
1282 * in the current regulatory domain. This method should be used only
1283 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001284 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * persisted as a Secure setting.
1286 * @param numChannels the number of allowed channels. Must be greater than 0
1287 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001288 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1290 * {@code numChannels} is outside the valid range.
1291 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001292 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1293 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1294 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 enforceChangePermission();
1296 /*
1297 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1298 * but if Wi-Fi isn't currently enabled, that's not possible, and
1299 * we want to persist the setting anyway,so that it will take
1300 * effect when Wi-Fi does become enabled.
1301 */
1302 boolean found = false;
1303 for (int validChan : sValidRegulatoryChannelCounts) {
1304 if (validChan == numChannels) {
1305 found = true;
1306 break;
1307 }
1308 }
1309 if (!found) {
1310 return false;
1311 }
1312
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001313 if (persist) {
1314 Settings.Secure.putInt(mContext.getContentResolver(),
1315 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1316 numChannels);
1317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 mWifiStateTracker.setNumAllowedChannels(numChannels);
1319 return true;
1320 }
1321
1322 /**
1323 * Return the number of frequency channels that are allowed
1324 * to be used in the current regulatory domain.
1325 * @return the number of allowed channels, or {@code -1} if an error occurs
1326 */
1327 public int getNumAllowedChannels() {
1328 int numChannels;
1329
1330 enforceAccessPermission();
1331 synchronized (mWifiStateTracker) {
1332 /*
1333 * If we can't get the value from the driver (e.g., because
1334 * Wi-Fi is not currently enabled), get the value from
1335 * Settings.
1336 */
1337 numChannels = WifiNative.getNumAllowedChannelsCommand();
1338 if (numChannels < 0) {
1339 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1340 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1341 -1);
1342 }
1343 }
1344 return numChannels;
1345 }
1346
1347 /**
1348 * Return the list of valid values for the number of allowed radio channels
1349 * for various regulatory domains.
1350 * @return the list of channel counts
1351 */
1352 public int[] getValidChannelCounts() {
1353 enforceAccessPermission();
1354 return sValidRegulatoryChannelCounts;
1355 }
1356
1357 /**
1358 * Return the DHCP-assigned addresses from the last successful DHCP request,
1359 * if any.
1360 * @return the DHCP information
1361 */
1362 public DhcpInfo getDhcpInfo() {
1363 enforceAccessPermission();
1364 return mWifiStateTracker.getDhcpInfo();
1365 }
1366
1367 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1368 @Override
1369 public void onReceive(Context context, Intent intent) {
1370 String action = intent.getAction();
1371
1372 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1373 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1374 int stayAwakeConditions =
1375 Settings.System.getInt(mContext.getContentResolver(),
1376 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1377 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001378 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 mAlarmManager.cancel(mIdleIntent);
1380 mDeviceIdle = false;
1381 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001382 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001384 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001386 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 /*
1388 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1389 * AND the "stay on while plugged in" setting doesn't match the
1390 * current power conditions (i.e, not plugged in, plugged in to USB,
1391 * or plugged in to AC).
1392 */
1393 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001394 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1395 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
1396 // do not keep Wifi awake when screen is off if Wifi is not associated
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001397 mDeviceIdle = true;
1398 updateWifiState();
1399 } else {
1400 long triggerTime = System.currentTimeMillis() + idleMillis;
1401 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1402 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 /* we can return now -- there's nothing to do until we get the idle intent back */
1406 return;
1407 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001408 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 mDeviceIdle = true;
1410 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1411 /*
1412 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1413 * AND we are transitioning from a state in which the device was supposed
1414 * to stay awake to a state in which it is not supposed to stay awake.
1415 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1416 * the already-set timer.
1417 */
1418 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001419 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1421 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1422 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001423 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1425 mPluggedType = pluggedType;
1426 return;
1427 }
1428 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001429 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1430 boolean isBluetoothPlaying =
1431 intent.getIntExtra(
1432 BluetoothA2dp.SINK_STATE,
1433 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1434 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 } else {
1436 return;
1437 }
1438
1439 updateWifiState();
1440 }
1441
1442 /**
1443 * Determines whether the Wi-Fi chipset should stay awake or be put to
1444 * sleep. Looks at the setting for the sleep policy and the current
1445 * conditions.
1446 *
1447 * @see #shouldDeviceStayAwake(int, int)
1448 */
1449 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1450 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1451 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1452
1453 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1454 // Never sleep
1455 return true;
1456 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1457 (pluggedType != 0)) {
1458 // Never sleep while plugged, and we're plugged
1459 return true;
1460 } else {
1461 // Default
1462 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1463 }
1464 }
1465
1466 /**
1467 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1468 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1469 * of {@code 0} isn't really a plugged type, but rather an indication that the
1470 * device isn't plugged in at all, there is no bit value corresponding to a
1471 * {@code pluggedType} value of {@code 0}. That is why we shift by
1472 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1473 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1474 * keep the device (and hence Wi-Fi) awake.
1475 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1476 * being made
1477 * @return {@code true} if {@code pluggedType} indicates that the device is
1478 * supposed to stay awake, {@code false} otherwise.
1479 */
1480 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1481 return (stayAwakeConditions & pluggedType) != 0;
1482 }
1483 };
1484
Dianne Hackborn617f8772009-03-31 15:04:46 -07001485 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 Message msg = Message.obtain(mWifiHandler,
1487 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001488 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 msg.sendToTarget();
1490 }
1491
1492 private void sendStartMessage(boolean scanOnlyMode) {
1493 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1494 }
1495
1496 private void updateWifiState() {
1497 boolean wifiEnabled = getPersistedWifiEnabled();
1498 boolean airplaneMode = isAirplaneModeOn();
1499 boolean lockHeld = mLocks.hasLocks();
1500 int strongestLockMode;
1501 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1502 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1503 if (mDeviceIdle && lockHeld) {
1504 strongestLockMode = mLocks.getStrongestLockMode();
1505 } else {
1506 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1507 }
1508
1509 synchronized (mWifiHandler) {
1510 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1511 return;
1512 }
1513 if (wifiShouldBeEnabled) {
1514 if (wifiShouldBeStarted) {
1515 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001516 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 sWakeLock.acquire();
1518 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1519 } else {
1520 int wakeLockTimeout =
1521 Settings.Secure.getInt(
1522 mContext.getContentResolver(),
1523 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1524 DEFAULT_WAKELOCK_TIMEOUT);
1525 /*
1526 * The following wakelock is held in order to ensure
1527 * that the connectivity manager has time to fail over
1528 * to the mobile data network. The connectivity manager
1529 * releases it once mobile data connectivity has been
1530 * established. If connectivity cannot be established,
1531 * the wakelock is released after wakeLockTimeout
1532 * milliseconds have elapsed.
1533 */
1534 sDriverStopWakeLock.acquire();
1535 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1536 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1537 }
1538 } else {
1539 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001540 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543 }
1544
1545 private void registerForBroadcasts() {
1546 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1548 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1549 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1550 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001551 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 mContext.registerReceiver(mReceiver, intentFilter);
1553 }
1554
1555 private boolean isAirplaneSensitive() {
1556 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1557 Settings.System.AIRPLANE_MODE_RADIOS);
1558 return airplaneModeRadios == null
1559 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1560 }
1561
1562 /**
1563 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1564 * currently on.
1565 * @return {@code true} if airplane mode is on.
1566 */
1567 private boolean isAirplaneModeOn() {
1568 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1569 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1570 }
1571
1572 /**
1573 * Handler that allows posting to the WifiThread.
1574 */
1575 private class WifiHandler extends Handler {
1576 public WifiHandler(Looper looper) {
1577 super(looper);
1578 }
1579
1580 @Override
1581 public void handleMessage(Message msg) {
1582 switch (msg.what) {
1583
1584 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001585 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 sWakeLock.release();
1587 break;
1588
1589 case MESSAGE_START_WIFI:
1590 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1591 mWifiStateTracker.restart();
1592 sWakeLock.release();
1593 break;
1594
1595 case MESSAGE_DISABLE_WIFI:
1596 // a non-zero msg.arg1 value means the "enabled" setting
1597 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001598 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 sWakeLock.release();
1600 break;
1601
1602 case MESSAGE_STOP_WIFI:
1603 mWifiStateTracker.disconnectAndStop();
1604 // don't release wakelock
1605 break;
1606
1607 case MESSAGE_RELEASE_WAKELOCK:
1608 synchronized (sDriverStopWakeLock) {
1609 if (sDriverStopWakeLock.isHeld()) {
1610 sDriverStopWakeLock.release();
1611 }
1612 }
1613 break;
1614 }
1615 }
1616 }
1617
1618 @Override
1619 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1620 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1621 != PackageManager.PERMISSION_GRANTED) {
1622 pw.println("Permission Denial: can't dump WifiService from from pid="
1623 + Binder.getCallingPid()
1624 + ", uid=" + Binder.getCallingUid());
1625 return;
1626 }
1627 pw.println("Wi-Fi is " + stateName(mWifiState));
1628 pw.println("Stay-awake conditions: " +
1629 Settings.System.getInt(mContext.getContentResolver(),
1630 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1631 pw.println();
1632
1633 pw.println("Internal state:");
1634 pw.println(mWifiStateTracker);
1635 pw.println();
1636 pw.println("Latest scan results:");
1637 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1638 if (scanResults != null && scanResults.size() != 0) {
1639 pw.println(" BSSID Frequency RSSI Flags SSID");
1640 for (ScanResult r : scanResults) {
1641 pw.printf(" %17s %9d %5d %-16s %s%n",
1642 r.BSSID,
1643 r.frequency,
1644 r.level,
1645 r.capabilities,
1646 r.SSID == null ? "" : r.SSID);
1647 }
1648 }
1649 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001650 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1651 mScanLocksAcquired + " scan");
1652 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1653 mScanLocksReleased + " scan");
1654 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 pw.println("Locks held:");
1656 mLocks.dump(pw);
1657 }
1658
1659 private static String stateName(int wifiState) {
1660 switch (wifiState) {
1661 case WIFI_STATE_DISABLING:
1662 return "disabling";
1663 case WIFI_STATE_DISABLED:
1664 return "disabled";
1665 case WIFI_STATE_ENABLING:
1666 return "enabling";
1667 case WIFI_STATE_ENABLED:
1668 return "enabled";
1669 case WIFI_STATE_UNKNOWN:
1670 return "unknown state";
1671 default:
1672 return "[invalid state]";
1673 }
1674 }
1675
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001676 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001678 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680
1681 public void binderDied() {
1682 synchronized (mLocks) {
1683 releaseWifiLockLocked(mBinder);
1684 }
1685 }
1686
1687 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001688 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
1691
1692 private class LockList {
1693 private List<WifiLock> mList;
1694
1695 private LockList() {
1696 mList = new ArrayList<WifiLock>();
1697 }
1698
1699 private synchronized boolean hasLocks() {
1700 return !mList.isEmpty();
1701 }
1702
1703 private synchronized int getStrongestLockMode() {
1704 if (mList.isEmpty()) {
1705 return WifiManager.WIFI_MODE_FULL;
1706 }
1707 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001708 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 return WifiManager.WIFI_MODE_FULL;
1710 }
1711 }
1712 return WifiManager.WIFI_MODE_SCAN_ONLY;
1713 }
1714
1715 private void addLock(WifiLock lock) {
1716 if (findLockByBinder(lock.mBinder) < 0) {
1717 mList.add(lock);
1718 }
1719 }
1720
1721 private WifiLock removeLock(IBinder binder) {
1722 int index = findLockByBinder(binder);
1723 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001724 WifiLock ret = mList.remove(index);
1725 ret.unlinkDeathRecipient();
1726 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 } else {
1728 return null;
1729 }
1730 }
1731
1732 private int findLockByBinder(IBinder binder) {
1733 int size = mList.size();
1734 for (int i = size - 1; i >= 0; i--)
1735 if (mList.get(i).mBinder == binder)
1736 return i;
1737 return -1;
1738 }
1739
1740 private void dump(PrintWriter pw) {
1741 for (WifiLock l : mList) {
1742 pw.print(" ");
1743 pw.println(l);
1744 }
1745 }
1746 }
1747
1748 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1750 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1751 return false;
1752 }
1753 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1754 synchronized (mLocks) {
1755 return acquireWifiLockLocked(wifiLock);
1756 }
1757 }
1758
1759 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1760 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001761
1762 int uid = Binder.getCallingUid();
1763 long ident = Binder.clearCallingIdentity();
1764 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001765 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001766 case WifiManager.WIFI_MODE_FULL:
1767 ++mFullLocksAcquired;
1768 mBatteryStats.noteFullWifiLockAcquired(uid);
1769 break;
1770 case WifiManager.WIFI_MODE_SCAN_ONLY:
1771 ++mScanLocksAcquired;
1772 mBatteryStats.noteScanWifiLockAcquired(uid);
1773 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001774 }
1775 } catch (RemoteException e) {
1776 } finally {
1777 Binder.restoreCallingIdentity(ident);
1778 }
1779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 updateWifiState();
1781 return true;
1782 }
1783
1784 public boolean releaseWifiLock(IBinder lock) {
1785 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1786 synchronized (mLocks) {
1787 return releaseWifiLockLocked(lock);
1788 }
1789 }
1790
1791 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001792 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001793
1794 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001795 hadLock = (wifiLock != null);
1796
1797 if (hadLock) {
1798 int uid = Binder.getCallingUid();
1799 long ident = Binder.clearCallingIdentity();
1800 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001801 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001802 case WifiManager.WIFI_MODE_FULL:
1803 ++mFullLocksReleased;
1804 mBatteryStats.noteFullWifiLockReleased(uid);
1805 break;
1806 case WifiManager.WIFI_MODE_SCAN_ONLY:
1807 ++mScanLocksReleased;
1808 mBatteryStats.noteScanWifiLockReleased(uid);
1809 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001810 }
1811 } catch (RemoteException e) {
1812 } finally {
1813 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001814 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001815 }
1816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001818 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001820
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001821 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001822 implements IBinder.DeathRecipient {
1823 String mTag;
1824 int mMode;
1825 IBinder mBinder;
1826
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001827 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001828 super();
1829 mTag = tag;
1830 mMode = mode;
1831 mBinder = binder;
1832 try {
1833 mBinder.linkToDeath(this, 0);
1834 } catch (RemoteException e) {
1835 binderDied();
1836 }
1837 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001838
1839 void unlinkDeathRecipient() {
1840 mBinder.unlinkToDeath(this, 0);
1841 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001842 }
1843
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001844 private class Multicaster extends DeathRecipient {
1845 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001846 super(Binder.getCallingUid(), tag, binder);
1847 }
1848
1849 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001850 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001851 synchronized (mMulticasters) {
1852 int i = mMulticasters.indexOf(this);
1853 if (i != -1) {
1854 removeMulticasterLocked(i, mMode);
1855 }
1856 }
1857 }
1858
1859 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001860 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001861 }
1862
1863 public int getUid() {
1864 return mMode;
1865 }
1866 }
1867
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001868 public void acquireMulticastLock(IBinder binder, String tag) {
1869 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001870
1871 synchronized (mMulticasters) {
1872 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001873 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001874 // Note that we could call stopPacketFiltering only when
1875 // our new size == 1 (first call), but this function won't
1876 // be called often and by making the stopPacket call each
1877 // time we're less fragile and self-healing.
1878 WifiNative.stopPacketFiltering();
1879 }
1880
1881 int uid = Binder.getCallingUid();
1882 Long ident = Binder.clearCallingIdentity();
1883 try {
1884 mBatteryStats.noteWifiMulticastEnabled(uid);
1885 } catch (RemoteException e) {
1886 } finally {
1887 Binder.restoreCallingIdentity(ident);
1888 }
1889 }
1890
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001891 public void releaseMulticastLock() {
1892 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001893
1894 int uid = Binder.getCallingUid();
1895 synchronized (mMulticasters) {
1896 mMulticastDisabled++;
1897 int size = mMulticasters.size();
1898 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001899 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001900 if ((m != null) && (m.getUid() == uid)) {
1901 removeMulticasterLocked(i, uid);
1902 }
1903 }
1904 }
1905 }
1906
1907 private void removeMulticasterLocked(int i, int uid)
1908 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001909 Multicaster removed = mMulticasters.remove(i);
1910 if (removed != null) {
1911 removed.unlinkDeathRecipient();
1912 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001913 if (mMulticasters.size() == 0) {
1914 WifiNative.startPacketFiltering();
1915 }
1916
1917 Long ident = Binder.clearCallingIdentity();
1918 try {
1919 mBatteryStats.noteWifiMulticastDisabled(uid);
1920 } catch (RemoteException e) {
1921 } finally {
1922 Binder.restoreCallingIdentity(ident);
1923 }
1924 }
1925
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001926 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001927 enforceAccessPermission();
1928
1929 synchronized (mMulticasters) {
1930 return (mMulticasters.size() > 0);
1931 }
1932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933}