blob: e91798b23d5ead8d4ef2bf93999ab68d4d75f8f5 [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;
41import android.net.NetworkStateTracker;
42import android.net.DhcpInfo;
43import android.os.Binder;
44import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.Looper;
48import android.os.Message;
49import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070050import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.RemoteException;
52import android.provider.Settings;
53import android.util.Log;
54import android.text.TextUtils;
55
56import java.util.ArrayList;
57import java.util.BitSet;
58import java.util.HashMap;
59import java.util.LinkedHashMap;
60import java.util.List;
61import java.util.Map;
62import java.util.regex.Pattern;
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066import com.android.internal.app.IBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.server.am.BatteryStatsService;
68
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069/**
70 * WifiService handles remote WiFi operation requests by implementing
71 * the IWifiManager interface. It also creates a WifiMonitor to listen
72 * for Wifi-related events.
73 *
74 * @hide
75 */
76public class WifiService extends IWifiManager.Stub {
77 private static final String TAG = "WifiService";
78 private static final boolean DBG = false;
79 private static final Pattern scanResultPattern = Pattern.compile("\t+");
80 private final WifiStateTracker mWifiStateTracker;
81
82 private Context mContext;
83 private int mWifiState;
84
85 private AlarmManager mAlarmManager;
86 private PendingIntent mIdleIntent;
87 private static final int IDLE_REQUEST = 0;
88 private boolean mScreenOff;
89 private boolean mDeviceIdle;
90 private int mPluggedType;
91
92 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070093 // some wifi lock statistics
94 private int mFullLocksAcquired;
95 private int mFullLocksReleased;
96 private int mScanLocksAcquired;
97 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -070098
Robert Greenwalt58ff0212009-05-19 15:53:54 -070099 private final List<Multicaster> mMulticasters =
100 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700101 private int mMulticastEnabled;
102 private int mMulticastDisabled;
103
The Android Open Source Project10592532009-03-18 17:39:46 -0700104 private final IBatteryStats mBatteryStats;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
108 * Settings.Gservices value is not present. This timeout value is chosen as
109 * the approximate point at which the battery drain caused by Wi-Fi
110 * being enabled but not active exceeds the battery drain caused by
111 * re-establishing a connection to the mobile data network.
112 */
113 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
114
115 private static final String WAKELOCK_TAG = "WifiService";
116
117 /**
118 * The maximum amount of time to hold the wake lock after a disconnect
119 * caused by stopping the driver. Establishing an EDGE connection has been
120 * observed to take about 5 seconds under normal circumstances. This
121 * provides a bit of extra margin.
122 * <p>
123 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
124 * This is the default value if a Settings.Secure value is not present.
125 */
126 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
127
128 // Wake lock used by driver-stop operation
129 private static PowerManager.WakeLock sDriverStopWakeLock;
130 // Wake lock used by other operations
131 private static PowerManager.WakeLock sWakeLock;
132
133 private static final int MESSAGE_ENABLE_WIFI = 0;
134 private static final int MESSAGE_DISABLE_WIFI = 1;
135 private static final int MESSAGE_STOP_WIFI = 2;
136 private static final int MESSAGE_START_WIFI = 3;
137 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
138
139 private final WifiHandler mWifiHandler;
140
141 /*
142 * Map used to keep track of hidden networks presence, which
143 * is needed to switch between active and passive scan modes.
144 * If there is at least one hidden network that is currently
145 * present (enabled), we want to do active scans instead of
146 * passive.
147 */
148 private final Map<Integer, Boolean> mIsHiddenNetworkPresent;
149 /*
150 * The number of currently present hidden networks. When this
151 * counter goes from 0 to 1 or from 1 to 0, we change the
152 * scan mode to active or passive respectively. Initially, we
153 * set the counter to 0 and we increment it every time we add
154 * a new present (enabled) hidden network.
155 */
156 private int mNumHiddenNetworkPresent;
157 /*
158 * Whether we change the scan mode is due to a hidden network
159 * (in this class, this is always the case)
160 */
161 private final static boolean SET_DUE_TO_A_HIDDEN_NETWORK = true;
162
163 /*
164 * Cache of scan results objects (size is somewhat arbitrary)
165 */
166 private static final int SCAN_RESULT_CACHE_SIZE = 80;
167 private final LinkedHashMap<String, ScanResult> mScanResultCache;
168
169 /*
170 * Character buffer used to parse scan results (optimization)
171 */
172 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 private boolean mNeedReconfig;
174
Dianne Hackborn617f8772009-03-31 15:04:46 -0700175 /*
176 * Last UID that asked to enable WIFI.
177 */
178 private int mLastEnableUid = Process.myUid();
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 /**
181 * Number of allowed radio frequency channels in various regulatory domains.
182 * This list is sufficient for 802.11b/g networks (2.4GHz range).
183 */
184 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
185
186 private static final String ACTION_DEVICE_IDLE =
187 "com.android.server.WifiManager.action.DEVICE_IDLE";
188
189 WifiService(Context context, WifiStateTracker tracker) {
190 mContext = context;
191 mWifiStateTracker = tracker;
The Android Open Source Project10592532009-03-18 17:39:46 -0700192 mBatteryStats = BatteryStatsService.getService();
193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 /*
195 * Initialize the hidden-networks state
196 */
197 mIsHiddenNetworkPresent = new HashMap<Integer, Boolean>();
198 mNumHiddenNetworkPresent = 0;
199
200 mScanResultCache = new LinkedHashMap<String, ScanResult>(
201 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
202 /*
203 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
204 * elements
205 */
206 public boolean removeEldestEntry(Map.Entry eldest) {
207 return SCAN_RESULT_CACHE_SIZE < this.size();
208 }
209 };
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 HandlerThread wifiThread = new HandlerThread("WifiService");
212 wifiThread.start();
213 mWifiHandler = new WifiHandler(wifiThread.getLooper());
214
215 mWifiState = WIFI_STATE_DISABLED;
216 boolean wifiEnabled = getPersistedWifiEnabled();
217
218 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
219 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
220 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
221
222 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
223 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
224 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
225 mWifiStateTracker.setReleaseWakeLockCallback(
226 new Runnable() {
227 public void run() {
228 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
229 synchronized (sDriverStopWakeLock) {
230 if (sDriverStopWakeLock.isHeld()) {
231 sDriverStopWakeLock.release();
232 }
233 }
234 }
235 }
236 );
237
238 Log.i(TAG, "WifiService starting up with Wi-Fi " +
239 (wifiEnabled ? "enabled" : "disabled"));
240
241 mContext.registerReceiver(
242 new BroadcastReceiver() {
243 @Override
244 public void onReceive(Context context, Intent intent) {
245 updateWifiState();
246 }
247 },
248 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
249
Dianne Hackborn617f8772009-03-31 15:04:46 -0700250 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 }
252
253 /**
254 * Initializes the hidden networks state. Must be called when we
255 * enable Wi-Fi.
256 */
257 private synchronized void initializeHiddenNetworksState() {
258 // First, reset the state
259 resetHiddenNetworksState();
260
261 // ... then add networks that are marked as hidden
262 List<WifiConfiguration> networks = getConfiguredNetworks();
263 if (!networks.isEmpty()) {
264 for (WifiConfiguration config : networks) {
265 if (config != null && config.hiddenSSID) {
266 addOrUpdateHiddenNetwork(
267 config.networkId,
268 config.status != WifiConfiguration.Status.DISABLED);
269 }
270 }
271
272 }
273 }
274
275 /**
276 * Resets the hidden networks state.
277 */
278 private synchronized void resetHiddenNetworksState() {
279 mNumHiddenNetworkPresent = 0;
280 mIsHiddenNetworkPresent.clear();
281 }
282
283 /**
284 * Marks all but netId network as not present.
285 */
286 private synchronized void markAllHiddenNetworksButOneAsNotPresent(int netId) {
287 for (Map.Entry<Integer, Boolean> entry : mIsHiddenNetworkPresent.entrySet()) {
288 if (entry != null) {
289 Integer networkId = entry.getKey();
290 if (networkId != netId) {
291 updateNetworkIfHidden(
292 networkId, false);
293 }
294 }
295 }
296 }
297
298 /**
299 * Updates the netId network presence status if netId is an existing
300 * hidden network.
301 */
302 private synchronized void updateNetworkIfHidden(int netId, boolean present) {
303 if (isHiddenNetwork(netId)) {
304 addOrUpdateHiddenNetwork(netId, present);
305 }
306 }
307
308 /**
309 * Updates the netId network presence status if netId is an existing
310 * hidden network. If the network does not exist, adds the network.
311 */
312 private synchronized void addOrUpdateHiddenNetwork(int netId, boolean present) {
313 if (0 <= netId) {
314
315 // If we are adding a new entry or modifying an existing one
316 Boolean isPresent = mIsHiddenNetworkPresent.get(netId);
317 if (isPresent == null || isPresent != present) {
318 if (present) {
319 incrementHiddentNetworkPresentCounter();
320 } else {
321 // If we add a new hidden network, no need to change
322 // the counter (it must be 0)
323 if (isPresent != null) {
324 decrementHiddentNetworkPresentCounter();
325 }
326 }
327 mIsHiddenNetworkPresent.put(netId, present);
328 }
329 } else {
330 Log.e(TAG, "addOrUpdateHiddenNetwork(): Invalid (negative) network id!");
331 }
332 }
333
334 /**
335 * Removes the netId network if it is hidden (being kept track of).
336 */
337 private synchronized void removeNetworkIfHidden(int netId) {
338 if (isHiddenNetwork(netId)) {
339 removeHiddenNetwork(netId);
340 }
341 }
342
343 /**
344 * Removes the netId network. For the call to be successful, the network
345 * must be hidden.
346 */
347 private synchronized void removeHiddenNetwork(int netId) {
348 if (0 <= netId) {
349 Boolean isPresent =
350 mIsHiddenNetworkPresent.remove(netId);
351 if (isPresent != null) {
352 // If we remove an existing hidden network that is not
353 // present, no need to change the counter
354 if (isPresent) {
355 decrementHiddentNetworkPresentCounter();
356 }
357 } else {
358 if (DBG) {
359 Log.d(TAG, "removeHiddenNetwork(): Removing a non-existent network!");
360 }
361 }
362 } else {
363 Log.e(TAG, "removeHiddenNetwork(): Invalid (negative) network id!");
364 }
365 }
366
367 /**
368 * Returns true if netId is an existing hidden network.
369 */
370 private synchronized boolean isHiddenNetwork(int netId) {
371 return mIsHiddenNetworkPresent.containsKey(netId);
372 }
373
374 /**
375 * Increments the present (enabled) hidden networks counter. If the
376 * counter value goes from 0 to 1, changes the scan mode to active.
377 */
378 private void incrementHiddentNetworkPresentCounter() {
379 ++mNumHiddenNetworkPresent;
380 if (1 == mNumHiddenNetworkPresent) {
381 // Switch the scan mode to "active"
382 mWifiStateTracker.setScanMode(true, SET_DUE_TO_A_HIDDEN_NETWORK);
383 }
384 }
385
386 /**
387 * Decrements the present (enabled) hidden networks counter. If the
388 * counter goes from 1 to 0, changes the scan mode back to passive.
389 */
390 private void decrementHiddentNetworkPresentCounter() {
391 if (0 < mNumHiddenNetworkPresent) {
392 --mNumHiddenNetworkPresent;
393 if (0 == mNumHiddenNetworkPresent) {
394 // Switch the scan mode to "passive"
395 mWifiStateTracker.setScanMode(false, SET_DUE_TO_A_HIDDEN_NETWORK);
396 }
397 } else {
398 Log.e(TAG, "Hidden-network counter invariant violation!");
399 }
400 }
401
402 private boolean getPersistedWifiEnabled() {
403 final ContentResolver cr = mContext.getContentResolver();
404 try {
405 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
406 } catch (Settings.SettingNotFoundException e) {
407 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
408 return false;
409 }
410 }
411
412 private void persistWifiEnabled(boolean enabled) {
413 final ContentResolver cr = mContext.getContentResolver();
414 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
415 }
416
417 NetworkStateTracker getNetworkStateTracker() {
418 return mWifiStateTracker;
419 }
420
421 /**
422 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
423 * @return {@code true} if the operation succeeds
424 */
425 public boolean pingSupplicant() {
426 enforceChangePermission();
427 synchronized (mWifiStateTracker) {
428 return WifiNative.pingCommand();
429 }
430 }
431
432 /**
433 * see {@link android.net.wifi.WifiManager#startScan()}
434 * @return {@code true} if the operation succeeds
435 */
436 public boolean startScan() {
437 enforceChangePermission();
438 synchronized (mWifiStateTracker) {
439 switch (mWifiStateTracker.getSupplicantState()) {
440 case DISCONNECTED:
441 case INACTIVE:
442 case SCANNING:
443 case DORMANT:
444 break;
445 default:
446 WifiNative.setScanResultHandlingCommand(
447 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
448 break;
449 }
450 return WifiNative.scanCommand();
451 }
452 }
453
454 /**
455 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
456 * @param enable {@code true} to enable, {@code false} to disable.
457 * @return {@code true} if the enable/disable operation was
458 * started or is already in the queue.
459 */
460 public boolean setWifiEnabled(boolean enable) {
461 enforceChangePermission();
462 if (mWifiHandler == null) return false;
463
464 synchronized (mWifiHandler) {
465 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700466 mLastEnableUid = Binder.getCallingUid();
467 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 }
469
470 return true;
471 }
472
473 /**
474 * Enables/disables Wi-Fi synchronously.
475 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
476 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700477 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 * @return {@code true} if the operation succeeds (or if the existing state
479 * is the same as the requested state)
480 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700481 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
483
484 if (mWifiState == eventualWifiState) {
485 return true;
486 }
487 if (enable && isAirplaneModeOn()) {
488 return false;
489 }
490
Dianne Hackborn617f8772009-03-31 15:04:46 -0700491 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492
493 if (enable) {
494 if (!WifiNative.loadDriver()) {
495 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700496 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 return false;
498 }
499 if (!WifiNative.startSupplicant()) {
500 WifiNative.unloadDriver();
501 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700502 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 return false;
504 }
505 registerForBroadcasts();
506 mWifiStateTracker.startEventLoop();
507 } else {
508
509 mContext.unregisterReceiver(mReceiver);
510 // Remove notification (it will no-op if it isn't visible)
511 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
512
513 boolean failedToStopSupplicantOrUnloadDriver = false;
514 if (!WifiNative.stopSupplicant()) {
515 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700516 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 failedToStopSupplicantOrUnloadDriver = true;
518 }
519
520 // We must reset the interface before we unload the driver
521 mWifiStateTracker.resetInterface();
522
523 if (!WifiNative.unloadDriver()) {
524 Log.e(TAG, "Failed to unload Wi-Fi driver.");
525 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700526 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 failedToStopSupplicantOrUnloadDriver = true;
528 }
529 }
530 if (failedToStopSupplicantOrUnloadDriver) {
531 return false;
532 }
533 }
534
535 // Success!
536
537 if (persist) {
538 persistWifiEnabled(enable);
539 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700540 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541
542 /*
543 * Initialize the hidden networks state and the number of allowed
544 * radio channels if Wi-Fi is being turned on.
545 */
546 if (enable) {
547 mWifiStateTracker.setNumAllowedChannels();
548 initializeHiddenNetworksState();
549 }
550
551 return true;
552 }
553
Dianne Hackborn617f8772009-03-31 15:04:46 -0700554 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 final int previousWifiState = mWifiState;
556
The Android Open Source Project10592532009-03-18 17:39:46 -0700557 long ident = Binder.clearCallingIdentity();
558 try {
559 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700560 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700561 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700562 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700563 }
564 } catch (RemoteException e) {
565 } finally {
566 Binder.restoreCallingIdentity(ident);
567 }
568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 // Update state
570 mWifiState = wifiState;
571
572 // Broadcast
573 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
574 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
575 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
576 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
577 mContext.sendStickyBroadcast(intent);
578 }
579
580 private void enforceAccessPermission() {
581 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
582 "WifiService");
583 }
584
585 private void enforceChangePermission() {
586 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
587 "WifiService");
588
589 }
590
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700591 private void enforceMulticastChangePermission() {
592 mContext.enforceCallingOrSelfPermission(
593 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
594 "WifiService");
595 }
596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 /**
598 * see {@link WifiManager#getWifiState()}
599 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
600 * {@link WifiManager#WIFI_STATE_DISABLING},
601 * {@link WifiManager#WIFI_STATE_ENABLED},
602 * {@link WifiManager#WIFI_STATE_ENABLING},
603 * {@link WifiManager#WIFI_STATE_UNKNOWN}
604 */
605 public int getWifiEnabledState() {
606 enforceAccessPermission();
607 return mWifiState;
608 }
609
610 /**
611 * see {@link android.net.wifi.WifiManager#disconnect()}
612 * @return {@code true} if the operation succeeds
613 */
614 public boolean disconnect() {
615 enforceChangePermission();
616 synchronized (mWifiStateTracker) {
617 return WifiNative.disconnectCommand();
618 }
619 }
620
621 /**
622 * see {@link android.net.wifi.WifiManager#reconnect()}
623 * @return {@code true} if the operation succeeds
624 */
625 public boolean reconnect() {
626 enforceChangePermission();
627 synchronized (mWifiStateTracker) {
628 return WifiNative.reconnectCommand();
629 }
630 }
631
632 /**
633 * see {@link android.net.wifi.WifiManager#reassociate()}
634 * @return {@code true} if the operation succeeds
635 */
636 public boolean reassociate() {
637 enforceChangePermission();
638 synchronized (mWifiStateTracker) {
639 return WifiNative.reassociateCommand();
640 }
641 }
642
643 /**
644 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
645 * @return the list of configured networks
646 */
647 public List<WifiConfiguration> getConfiguredNetworks() {
648 enforceAccessPermission();
649 String listStr;
650 /*
651 * We don't cache the list, because we want to allow
652 * for the possibility that the configuration file
653 * has been modified through some external means,
654 * such as the wpa_cli command line program.
655 */
656 synchronized (mWifiStateTracker) {
657 listStr = WifiNative.listNetworksCommand();
658 }
659 List<WifiConfiguration> networks =
660 new ArrayList<WifiConfiguration>();
661 if (listStr == null)
662 return networks;
663
664 String[] lines = listStr.split("\n");
665 // Skip the first line, which is a header
666 for (int i = 1; i < lines.length; i++) {
667 String[] result = lines[i].split("\t");
668 // network-id | ssid | bssid | flags
669 WifiConfiguration config = new WifiConfiguration();
670 try {
671 config.networkId = Integer.parseInt(result[0]);
672 } catch(NumberFormatException e) {
673 continue;
674 }
675 if (result.length > 3) {
676 if (result[3].indexOf("[CURRENT]") != -1)
677 config.status = WifiConfiguration.Status.CURRENT;
678 else if (result[3].indexOf("[DISABLED]") != -1)
679 config.status = WifiConfiguration.Status.DISABLED;
680 else
681 config.status = WifiConfiguration.Status.ENABLED;
682 } else
683 config.status = WifiConfiguration.Status.ENABLED;
684 synchronized (mWifiStateTracker) {
685 readNetworkVariables(config);
686 }
687 networks.add(config);
688 }
689
690 return networks;
691 }
692
693 /**
694 * Read the variables from the supplicant daemon that are needed to
695 * fill in the WifiConfiguration object.
696 * <p/>
697 * The caller must hold the synchronization monitor.
698 * @param config the {@link WifiConfiguration} object to be filled in.
699 */
700 private static void readNetworkVariables(WifiConfiguration config) {
701
702 int netId = config.networkId;
703 if (netId < 0)
704 return;
705
706 /*
707 * TODO: maybe should have a native method that takes an array of
708 * variable names and returns an array of values. But we'd still
709 * be doing a round trip to the supplicant daemon for each variable.
710 */
711 String value;
712
713 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
714 if (!TextUtils.isEmpty(value)) {
715 config.SSID = value;
716 } else {
717 config.SSID = null;
718 }
719
720 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
721 if (!TextUtils.isEmpty(value)) {
722 config.BSSID = value;
723 } else {
724 config.BSSID = null;
725 }
726
727 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
728 config.priority = -1;
729 if (!TextUtils.isEmpty(value)) {
730 try {
731 config.priority = Integer.parseInt(value);
732 } catch (NumberFormatException ignore) {
733 }
734 }
735
736 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
737 config.hiddenSSID = false;
738 if (!TextUtils.isEmpty(value)) {
739 try {
740 config.hiddenSSID = Integer.parseInt(value) != 0;
741 } catch (NumberFormatException ignore) {
742 }
743 }
744
745 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
746 config.wepTxKeyIndex = -1;
747 if (!TextUtils.isEmpty(value)) {
748 try {
749 config.wepTxKeyIndex = Integer.parseInt(value);
750 } catch (NumberFormatException ignore) {
751 }
752 }
753
754 /*
755 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
756 * just a "*" if the key is set, or the null string otherwise.
757 */
758 for (int i = 0; i < 4; i++) {
759 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
760 if (!TextUtils.isEmpty(value)) {
761 config.wepKeys[i] = value;
762 } else {
763 config.wepKeys[i] = null;
764 }
765 }
766
767 /*
768 * Get the private shared key. Note that the actual keys are not passed back,
769 * just a "*" if the key is set, or the null string otherwise.
770 */
771 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
772 if (!TextUtils.isEmpty(value)) {
773 config.preSharedKey = value;
774 } else {
775 config.preSharedKey = null;
776 }
777
778 value = WifiNative.getNetworkVariableCommand(config.networkId,
779 WifiConfiguration.Protocol.varName);
780 if (!TextUtils.isEmpty(value)) {
781 String vals[] = value.split(" ");
782 for (String val : vals) {
783 int index =
784 lookupString(val, WifiConfiguration.Protocol.strings);
785 if (0 <= index) {
786 config.allowedProtocols.set(index);
787 }
788 }
789 }
790
791 value = WifiNative.getNetworkVariableCommand(config.networkId,
792 WifiConfiguration.KeyMgmt.varName);
793 if (!TextUtils.isEmpty(value)) {
794 String vals[] = value.split(" ");
795 for (String val : vals) {
796 int index =
797 lookupString(val, WifiConfiguration.KeyMgmt.strings);
798 if (0 <= index) {
799 config.allowedKeyManagement.set(index);
800 }
801 }
802 }
803
804 value = WifiNative.getNetworkVariableCommand(config.networkId,
805 WifiConfiguration.AuthAlgorithm.varName);
806 if (!TextUtils.isEmpty(value)) {
807 String vals[] = value.split(" ");
808 for (String val : vals) {
809 int index =
810 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
811 if (0 <= index) {
812 config.allowedAuthAlgorithms.set(index);
813 }
814 }
815 }
816
817 value = WifiNative.getNetworkVariableCommand(config.networkId,
818 WifiConfiguration.PairwiseCipher.varName);
819 if (!TextUtils.isEmpty(value)) {
820 String vals[] = value.split(" ");
821 for (String val : vals) {
822 int index =
823 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
824 if (0 <= index) {
825 config.allowedPairwiseCiphers.set(index);
826 }
827 }
828 }
829
830 value = WifiNative.getNetworkVariableCommand(config.networkId,
831 WifiConfiguration.GroupCipher.varName);
832 if (!TextUtils.isEmpty(value)) {
833 String vals[] = value.split(" ");
834 for (String val : vals) {
835 int index =
836 lookupString(val, WifiConfiguration.GroupCipher.strings);
837 if (0 <= index) {
838 config.allowedGroupCiphers.set(index);
839 }
840 }
841 }
842 }
843
844 /**
845 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
846 * @return the supplicant-assigned identifier for the new or updated
847 * network if the operation succeeds, or {@code -1} if it fails
848 */
849 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
850 enforceChangePermission();
851 /*
852 * If the supplied networkId is -1, we create a new empty
853 * network configuration. Otherwise, the networkId should
854 * refer to an existing configuration.
855 */
856 int netId = config.networkId;
857 boolean newNetwork = netId == -1;
858 boolean doReconfig;
859 int currentPriority;
860 // networkId of -1 means we want to create a new network
861 if (newNetwork) {
862 netId = WifiNative.addNetworkCommand();
863 if (netId < 0) {
864 if (DBG) {
865 Log.d(TAG, "Failed to add a network!");
866 }
867 return -1;
868 }
869 doReconfig = true;
870 } else {
871 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
872 currentPriority = -1;
873 if (!TextUtils.isEmpty(priorityVal)) {
874 try {
875 currentPriority = Integer.parseInt(priorityVal);
876 } catch (NumberFormatException ignore) {
877 }
878 }
879 doReconfig = currentPriority != config.priority;
880 }
881 mNeedReconfig = mNeedReconfig || doReconfig;
882
883 /*
884 * If we have hidden networks, we may have to change the scan mode
885 */
886 if (config.hiddenSSID) {
887 // Mark the network as present unless it is disabled
888 addOrUpdateHiddenNetwork(
889 netId, config.status != WifiConfiguration.Status.DISABLED);
890 }
891
892 setVariables: {
893 /*
894 * Note that if a networkId for a non-existent network
895 * was supplied, then the first setNetworkVariableCommand()
896 * will fail, so we don't bother to make a separate check
897 * for the validity of the ID up front.
898 */
899
900 if (config.SSID != null &&
901 !WifiNative.setNetworkVariableCommand(
902 netId,
903 WifiConfiguration.ssidVarName,
904 config.SSID)) {
905 if (DBG) {
906 Log.d(TAG, "failed to set SSID: "+config.SSID);
907 }
908 break setVariables;
909 }
910
911 if (config.BSSID != null &&
912 !WifiNative.setNetworkVariableCommand(
913 netId,
914 WifiConfiguration.bssidVarName,
915 config.BSSID)) {
916 if (DBG) {
917 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
918 }
919 break setVariables;
920 }
921
922 String allowedKeyManagementString =
923 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
924 if (config.allowedKeyManagement.cardinality() != 0 &&
925 !WifiNative.setNetworkVariableCommand(
926 netId,
927 WifiConfiguration.KeyMgmt.varName,
928 allowedKeyManagementString)) {
929 if (DBG) {
930 Log.d(TAG, "failed to set key_mgmt: "+
931 allowedKeyManagementString);
932 }
933 break setVariables;
934 }
935
936 String allowedProtocolsString =
937 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
938 if (config.allowedProtocols.cardinality() != 0 &&
939 !WifiNative.setNetworkVariableCommand(
940 netId,
941 WifiConfiguration.Protocol.varName,
942 allowedProtocolsString)) {
943 if (DBG) {
944 Log.d(TAG, "failed to set proto: "+
945 allowedProtocolsString);
946 }
947 break setVariables;
948 }
949
950 String allowedAuthAlgorithmsString =
951 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
952 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
953 !WifiNative.setNetworkVariableCommand(
954 netId,
955 WifiConfiguration.AuthAlgorithm.varName,
956 allowedAuthAlgorithmsString)) {
957 if (DBG) {
958 Log.d(TAG, "failed to set auth_alg: "+
959 allowedAuthAlgorithmsString);
960 }
961 break setVariables;
962 }
963
964 String allowedPairwiseCiphersString =
965 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
966 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
967 !WifiNative.setNetworkVariableCommand(
968 netId,
969 WifiConfiguration.PairwiseCipher.varName,
970 allowedPairwiseCiphersString)) {
971 if (DBG) {
972 Log.d(TAG, "failed to set pairwise: "+
973 allowedPairwiseCiphersString);
974 }
975 break setVariables;
976 }
977
978 String allowedGroupCiphersString =
979 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
980 if (config.allowedGroupCiphers.cardinality() != 0 &&
981 !WifiNative.setNetworkVariableCommand(
982 netId,
983 WifiConfiguration.GroupCipher.varName,
984 allowedGroupCiphersString)) {
985 if (DBG) {
986 Log.d(TAG, "failed to set group: "+
987 allowedGroupCiphersString);
988 }
989 break setVariables;
990 }
991
992 // Prevent client screw-up by passing in a WifiConfiguration we gave it
993 // by preventing "*" as a key.
994 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
995 !WifiNative.setNetworkVariableCommand(
996 netId,
997 WifiConfiguration.pskVarName,
998 config.preSharedKey)) {
999 if (DBG) {
1000 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
1001 }
1002 break setVariables;
1003 }
1004
1005 boolean hasSetKey = false;
1006 if (config.wepKeys != null) {
1007 for (int i = 0; i < config.wepKeys.length; i++) {
1008 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1009 // by preventing "*" as a key.
1010 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
1011 if (!WifiNative.setNetworkVariableCommand(
1012 netId,
1013 WifiConfiguration.wepKeyVarNames[i],
1014 config.wepKeys[i])) {
1015 if (DBG) {
1016 Log.d(TAG,
1017 "failed to set wep_key"+i+": " +
1018 config.wepKeys[i]);
1019 }
1020 break setVariables;
1021 }
1022 hasSetKey = true;
1023 }
1024 }
1025 }
1026
1027 if (hasSetKey) {
1028 if (!WifiNative.setNetworkVariableCommand(
1029 netId,
1030 WifiConfiguration.wepTxKeyIdxVarName,
1031 Integer.toString(config.wepTxKeyIndex))) {
1032 if (DBG) {
1033 Log.d(TAG,
1034 "failed to set wep_tx_keyidx: "+
1035 config.wepTxKeyIndex);
1036 }
1037 break setVariables;
1038 }
1039 }
1040
1041 if (!WifiNative.setNetworkVariableCommand(
1042 netId,
1043 WifiConfiguration.priorityVarName,
1044 Integer.toString(config.priority))) {
1045 if (DBG) {
1046 Log.d(TAG, config.SSID + ": failed to set priority: "
1047 +config.priority);
1048 }
1049 break setVariables;
1050 }
1051
1052 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
1053 netId,
1054 WifiConfiguration.hiddenSSIDVarName,
1055 Integer.toString(config.hiddenSSID ? 1 : 0))) {
1056 if (DBG) {
1057 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
1058 config.hiddenSSID);
1059 }
1060 break setVariables;
1061 }
1062
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001063 if ((config.eap != null) && !WifiNative.setNetworkVariableCommand(
1064 netId,
1065 WifiConfiguration.eapVarName,
1066 config.eap)) {
1067 if (DBG) {
1068 Log.d(TAG, config.SSID + ": failed to set eap: "+
1069 config.eap);
1070 }
1071 break setVariables;
1072 }
1073
1074 if ((config.identity != null) && !WifiNative.setNetworkVariableCommand(
1075 netId,
1076 WifiConfiguration.identityVarName,
1077 config.identity)) {
1078 if (DBG) {
1079 Log.d(TAG, config.SSID + ": failed to set identity: "+
1080 config.identity);
1081 }
1082 break setVariables;
1083 }
1084
1085 if ((config.anonymousIdentity != null) && !WifiNative.setNetworkVariableCommand(
1086 netId,
1087 WifiConfiguration.anonymousIdentityVarName,
1088 config.anonymousIdentity)) {
1089 if (DBG) {
1090 Log.d(TAG, config.SSID + ": failed to set anonymousIdentity: "+
1091 config.anonymousIdentity);
1092 }
1093 break setVariables;
1094 }
1095
1096 if ((config.clientCert != null) && !WifiNative.setNetworkVariableCommand(
1097 netId,
1098 WifiConfiguration.clientCertVarName,
1099 config.clientCert)) {
1100 if (DBG) {
1101 Log.d(TAG, config.SSID + ": failed to set clientCert: "+
1102 config.clientCert);
1103 }
1104 break setVariables;
1105 }
1106
1107 if ((config.caCert != null) && !WifiNative.setNetworkVariableCommand(
1108 netId,
1109 WifiConfiguration.caCertVarName,
1110 config.caCert)) {
1111 if (DBG) {
1112 Log.d(TAG, config.SSID + ": failed to set caCert: "+
1113 config.caCert);
1114 }
1115 break setVariables;
1116 }
1117
1118 if ((config.privateKey != null) && !WifiNative.setNetworkVariableCommand(
1119 netId,
1120 WifiConfiguration.privateKeyVarName,
1121 config.privateKey)) {
1122 if (DBG) {
1123 Log.d(TAG, config.SSID + ": failed to set privateKey: "+
1124 config.privateKey);
1125 }
1126 break setVariables;
1127 }
1128
1129 if ((config.privateKeyPasswd != null) && !WifiNative.setNetworkVariableCommand(
1130 netId,
1131 WifiConfiguration.privateKeyPasswdVarName,
1132 config.privateKeyPasswd)) {
1133 if (DBG) {
1134 Log.d(TAG, config.SSID + ": failed to set privateKeyPasswd: "+
1135 config.privateKeyPasswd);
1136 }
1137 break setVariables;
1138 }
1139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 return netId;
1141 }
1142
1143 /*
1144 * For an update, if one of the setNetworkVariable operations fails,
1145 * we might want to roll back all the changes already made. But the
1146 * chances are that if anything is going to go wrong, it'll happen
1147 * the first time we try to set one of the variables.
1148 */
1149 if (newNetwork) {
1150 removeNetwork(netId);
1151 if (DBG) {
1152 Log.d(TAG,
1153 "Failed to set a network variable, removed network: "
1154 + netId);
1155 }
1156 }
1157 return -1;
1158 }
1159
1160 private static String makeString(BitSet set, String[] strings) {
1161 StringBuffer buf = new StringBuffer();
1162 int nextSetBit = -1;
1163
1164 /* Make sure all set bits are in [0, strings.length) to avoid
1165 * going out of bounds on strings. (Shouldn't happen, but...) */
1166 set = set.get(0, strings.length);
1167
1168 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1169 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1170 }
1171
1172 // remove trailing space
1173 if (set.cardinality() > 0) {
1174 buf.setLength(buf.length() - 1);
1175 }
1176
1177 return buf.toString();
1178 }
1179
1180 private static int lookupString(String string, String[] strings) {
1181 int size = strings.length;
1182
1183 string = string.replace('-', '_');
1184
1185 for (int i = 0; i < size; i++)
1186 if (string.equals(strings[i]))
1187 return i;
1188
1189 if (DBG) {
1190 // if we ever get here, we should probably add the
1191 // value to WifiConfiguration to reflect that it's
1192 // supported by the WPA supplicant
1193 Log.w(TAG, "Failed to look-up a string: " + string);
1194 }
1195
1196 return -1;
1197 }
1198
1199 /**
1200 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1201 * @param netId the integer that identifies the network configuration
1202 * to the supplicant
1203 * @return {@code true} if the operation succeeded
1204 */
1205 public boolean removeNetwork(int netId) {
1206 enforceChangePermission();
1207
1208 /*
1209 * If we have hidden networks, we may have to change the scan mode
1210 */
1211 removeNetworkIfHidden(netId);
1212
1213 return mWifiStateTracker.removeNetwork(netId);
1214 }
1215
1216 /**
1217 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1218 * @param netId the integer that identifies the network configuration
1219 * to the supplicant
1220 * @param disableOthers if true, disable all other networks.
1221 * @return {@code true} if the operation succeeded
1222 */
1223 public boolean enableNetwork(int netId, boolean disableOthers) {
1224 enforceChangePermission();
1225
1226 /*
1227 * If we have hidden networks, we may have to change the scan mode
1228 */
1229 synchronized(this) {
1230 if (disableOthers) {
1231 markAllHiddenNetworksButOneAsNotPresent(netId);
1232 }
1233 updateNetworkIfHidden(netId, true);
1234 }
1235
1236 synchronized (mWifiStateTracker) {
1237 return WifiNative.enableNetworkCommand(netId, disableOthers);
1238 }
1239 }
1240
1241 /**
1242 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1243 * @param netId the integer that identifies the network configuration
1244 * to the supplicant
1245 * @return {@code true} if the operation succeeded
1246 */
1247 public boolean disableNetwork(int netId) {
1248 enforceChangePermission();
1249
1250 /*
1251 * If we have hidden networks, we may have to change the scan mode
1252 */
1253 updateNetworkIfHidden(netId, false);
1254
1255 synchronized (mWifiStateTracker) {
1256 return WifiNative.disableNetworkCommand(netId);
1257 }
1258 }
1259
1260 /**
1261 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1262 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1263 */
1264 public WifiInfo getConnectionInfo() {
1265 enforceAccessPermission();
1266 /*
1267 * Make sure we have the latest information, by sending
1268 * a status request to the supplicant.
1269 */
1270 return mWifiStateTracker.requestConnectionInfo();
1271 }
1272
1273 /**
1274 * Return the results of the most recent access point scan, in the form of
1275 * a list of {@link ScanResult} objects.
1276 * @return the list of results
1277 */
1278 public List<ScanResult> getScanResults() {
1279 enforceAccessPermission();
1280 String reply;
1281 synchronized (mWifiStateTracker) {
1282 reply = WifiNative.scanResultsCommand();
1283 }
1284 if (reply == null) {
1285 return null;
1286 }
1287
1288 List<ScanResult> scanList = new ArrayList<ScanResult>();
1289
1290 int lineCount = 0;
1291
1292 int replyLen = reply.length();
1293 // Parse the result string, keeping in mind that the last line does
1294 // not end with a newline.
1295 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1296 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1297 ++lineCount;
1298 /*
1299 * Skip the first line, which is a header
1300 */
1301 if (lineCount == 1) {
1302 lineBeg = lineEnd + 1;
1303 continue;
1304 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001305 if (lineEnd > lineBeg) {
1306 String line = reply.substring(lineBeg, lineEnd);
1307 ScanResult scanResult = parseScanResult(line);
1308 if (scanResult != null) {
1309 scanList.add(scanResult);
1310 } else if (DBG) {
1311 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
1313 }
1314 lineBeg = lineEnd + 1;
1315 }
1316 }
1317 mWifiStateTracker.setScanResultsList(scanList);
1318 return scanList;
1319 }
1320
1321 /**
1322 * Parse the scan result line passed to us by wpa_supplicant (helper).
1323 * @param line the line to parse
1324 * @return the {@link ScanResult} object
1325 */
1326 private ScanResult parseScanResult(String line) {
1327 ScanResult scanResult = null;
1328 if (line != null) {
1329 /*
1330 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1331 * must synchronized here!
1332 */
1333 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001334 String[] result = scanResultPattern.split(line);
1335 if (3 <= result.length && result.length <= 5) {
1336 String bssid = result[0];
1337 // bssid | frequency | level | flags | ssid
1338 int frequency;
1339 int level;
1340 try {
1341 frequency = Integer.parseInt(result[1]);
1342 level = Integer.parseInt(result[2]);
1343 /* some implementations avoid negative values by adding 256
1344 * so we need to adjust for that here.
1345 */
1346 if (level > 0) level -= 256;
1347 } catch (NumberFormatException e) {
1348 frequency = 0;
1349 level = 0;
1350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351
Mike Lockwood1a645052009-06-25 13:01:12 -04001352 /*
1353 * The formatting of the results returned by
1354 * wpa_supplicant is intended to make the fields
1355 * line up nicely when printed,
1356 * not to make them easy to parse. So we have to
1357 * apply some heuristics to figure out which field
1358 * is the SSID and which field is the flags.
1359 */
1360 String ssid;
1361 String flags;
1362 if (result.length == 4) {
1363 if (result[3].charAt(0) == '[') {
1364 flags = result[3];
1365 ssid = "";
1366 } else {
1367 flags = "";
1368 ssid = result[3];
1369 }
1370 } else if (result.length == 5) {
1371 flags = result[3];
1372 ssid = result[4];
1373 } else {
1374 // Here, we must have 3 fields: no flags and ssid
1375 // set
1376 flags = "";
1377 ssid = "";
1378 }
1379
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001380 // bssid is the hash key
1381 scanResult = mScanResultCache.get(bssid);
1382 if (scanResult != null) {
1383 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001384 scanResult.SSID = ssid;
1385 scanResult.capabilities = flags;
1386 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001387 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 // Do not add scan results that have no SSID set
1389 if (0 < ssid.trim().length()) {
1390 scanResult =
1391 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001392 ssid, bssid, flags, level, frequency);
1393 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001396 } else {
1397 Log.w(TAG, "Misformatted scan result text with " +
1398 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 }
1401 }
1402
1403 return scanResult;
1404 }
1405
1406 /**
1407 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1408 * and construct a {@code WifiConfiguration} that describes the encryption,
1409 * key management, and authenticaion capabilities of the access point.
1410 * @param flags the string returned by wpa_supplicant
1411 * @return the {@link WifiConfiguration} object, filled in
1412 */
1413 WifiConfiguration parseScanFlags(String flags) {
1414 WifiConfiguration config = new WifiConfiguration();
1415
1416 if (flags.length() == 0) {
1417 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1418 }
1419 // ... to be implemented
1420 return config;
1421 }
1422
1423 /**
1424 * Tell the supplicant to persist the current list of configured networks.
1425 * @return {@code true} if the operation succeeded
1426 */
1427 public boolean saveConfiguration() {
1428 boolean result;
1429 enforceChangePermission();
1430 synchronized (mWifiStateTracker) {
1431 result = WifiNative.saveConfigCommand();
1432 if (result && mNeedReconfig) {
1433 mNeedReconfig = false;
1434 result = WifiNative.reloadConfigCommand();
1435
1436 if (result) {
1437 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1438 mContext.sendBroadcast(intent);
1439 }
1440 }
1441 }
1442 return result;
1443 }
1444
1445 /**
1446 * Set the number of radio frequency channels that are allowed to be used
1447 * in the current regulatory domain. This method should be used only
1448 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001449 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 * persisted as a Secure setting.
1451 * @param numChannels the number of allowed channels. Must be greater than 0
1452 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001453 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1455 * {@code numChannels} is outside the valid range.
1456 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001457 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
1458 Log.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
1459 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 enforceChangePermission();
1461 /*
1462 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1463 * but if Wi-Fi isn't currently enabled, that's not possible, and
1464 * we want to persist the setting anyway,so that it will take
1465 * effect when Wi-Fi does become enabled.
1466 */
1467 boolean found = false;
1468 for (int validChan : sValidRegulatoryChannelCounts) {
1469 if (validChan == numChannels) {
1470 found = true;
1471 break;
1472 }
1473 }
1474 if (!found) {
1475 return false;
1476 }
1477
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001478 if (persist) {
1479 Settings.Secure.putInt(mContext.getContentResolver(),
1480 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1481 numChannels);
1482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 mWifiStateTracker.setNumAllowedChannels(numChannels);
1484 return true;
1485 }
1486
1487 /**
1488 * Return the number of frequency channels that are allowed
1489 * to be used in the current regulatory domain.
1490 * @return the number of allowed channels, or {@code -1} if an error occurs
1491 */
1492 public int getNumAllowedChannels() {
1493 int numChannels;
1494
1495 enforceAccessPermission();
1496 synchronized (mWifiStateTracker) {
1497 /*
1498 * If we can't get the value from the driver (e.g., because
1499 * Wi-Fi is not currently enabled), get the value from
1500 * Settings.
1501 */
1502 numChannels = WifiNative.getNumAllowedChannelsCommand();
1503 if (numChannels < 0) {
1504 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1505 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1506 -1);
1507 }
1508 }
1509 return numChannels;
1510 }
1511
1512 /**
1513 * Return the list of valid values for the number of allowed radio channels
1514 * for various regulatory domains.
1515 * @return the list of channel counts
1516 */
1517 public int[] getValidChannelCounts() {
1518 enforceAccessPermission();
1519 return sValidRegulatoryChannelCounts;
1520 }
1521
1522 /**
1523 * Return the DHCP-assigned addresses from the last successful DHCP request,
1524 * if any.
1525 * @return the DHCP information
1526 */
1527 public DhcpInfo getDhcpInfo() {
1528 enforceAccessPermission();
1529 return mWifiStateTracker.getDhcpInfo();
1530 }
1531
1532 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1533 @Override
1534 public void onReceive(Context context, Intent intent) {
1535 String action = intent.getAction();
1536
1537 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1538 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1539 int stayAwakeConditions =
1540 Settings.System.getInt(mContext.getContentResolver(),
1541 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1542 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001543 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 mAlarmManager.cancel(mIdleIntent);
1545 mDeviceIdle = false;
1546 mScreenOff = false;
1547 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001548 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 mScreenOff = true;
1550 /*
1551 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1552 * AND the "stay on while plugged in" setting doesn't match the
1553 * current power conditions (i.e, not plugged in, plugged in to USB,
1554 * or plugged in to AC).
1555 */
1556 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001557 if (!mWifiStateTracker.hasIpAddress()) {
1558 // do not keep Wifi awake when screen is off if Wifi is not fully active
1559 mDeviceIdle = true;
1560 updateWifiState();
1561 } else {
1562 long triggerTime = System.currentTimeMillis() + idleMillis;
1563 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1564 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567 /* we can return now -- there's nothing to do until we get the idle intent back */
1568 return;
1569 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001570 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 mDeviceIdle = true;
1572 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1573 /*
1574 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1575 * AND we are transitioning from a state in which the device was supposed
1576 * to stay awake to a state in which it is not supposed to stay awake.
1577 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1578 * the already-set timer.
1579 */
1580 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001581 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1583 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1584 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001585 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1587 mPluggedType = pluggedType;
1588 return;
1589 }
1590 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001591 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1592 boolean isBluetoothPlaying =
1593 intent.getIntExtra(
1594 BluetoothA2dp.SINK_STATE,
1595 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1596 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 } else {
1598 return;
1599 }
1600
1601 updateWifiState();
1602 }
1603
1604 /**
1605 * Determines whether the Wi-Fi chipset should stay awake or be put to
1606 * sleep. Looks at the setting for the sleep policy and the current
1607 * conditions.
1608 *
1609 * @see #shouldDeviceStayAwake(int, int)
1610 */
1611 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1612 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1613 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1614
1615 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1616 // Never sleep
1617 return true;
1618 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1619 (pluggedType != 0)) {
1620 // Never sleep while plugged, and we're plugged
1621 return true;
1622 } else {
1623 // Default
1624 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1625 }
1626 }
1627
1628 /**
1629 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1630 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1631 * of {@code 0} isn't really a plugged type, but rather an indication that the
1632 * device isn't plugged in at all, there is no bit value corresponding to a
1633 * {@code pluggedType} value of {@code 0}. That is why we shift by
1634 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1635 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1636 * keep the device (and hence Wi-Fi) awake.
1637 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1638 * being made
1639 * @return {@code true} if {@code pluggedType} indicates that the device is
1640 * supposed to stay awake, {@code false} otherwise.
1641 */
1642 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1643 return (stayAwakeConditions & pluggedType) != 0;
1644 }
1645 };
1646
Dianne Hackborn617f8772009-03-31 15:04:46 -07001647 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 Message msg = Message.obtain(mWifiHandler,
1649 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001650 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 msg.sendToTarget();
1652 }
1653
1654 private void sendStartMessage(boolean scanOnlyMode) {
1655 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1656 }
1657
1658 private void updateWifiState() {
1659 boolean wifiEnabled = getPersistedWifiEnabled();
1660 boolean airplaneMode = isAirplaneModeOn();
1661 boolean lockHeld = mLocks.hasLocks();
1662 int strongestLockMode;
1663 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1664 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1665 if (mDeviceIdle && lockHeld) {
1666 strongestLockMode = mLocks.getStrongestLockMode();
1667 } else {
1668 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1669 }
1670
1671 synchronized (mWifiHandler) {
1672 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1673 return;
1674 }
1675 if (wifiShouldBeEnabled) {
1676 if (wifiShouldBeStarted) {
1677 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001678 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 sWakeLock.acquire();
1680 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1681 } else {
1682 int wakeLockTimeout =
1683 Settings.Secure.getInt(
1684 mContext.getContentResolver(),
1685 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1686 DEFAULT_WAKELOCK_TIMEOUT);
1687 /*
1688 * The following wakelock is held in order to ensure
1689 * that the connectivity manager has time to fail over
1690 * to the mobile data network. The connectivity manager
1691 * releases it once mobile data connectivity has been
1692 * established. If connectivity cannot be established,
1693 * the wakelock is released after wakeLockTimeout
1694 * milliseconds have elapsed.
1695 */
1696 sDriverStopWakeLock.acquire();
1697 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1698 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1699 }
1700 } else {
1701 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001702 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704 }
1705 }
1706
1707 private void registerForBroadcasts() {
1708 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1710 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1711 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1712 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001713 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 mContext.registerReceiver(mReceiver, intentFilter);
1715 }
1716
1717 private boolean isAirplaneSensitive() {
1718 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1719 Settings.System.AIRPLANE_MODE_RADIOS);
1720 return airplaneModeRadios == null
1721 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1722 }
1723
1724 /**
1725 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1726 * currently on.
1727 * @return {@code true} if airplane mode is on.
1728 */
1729 private boolean isAirplaneModeOn() {
1730 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1731 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1732 }
1733
1734 /**
1735 * Handler that allows posting to the WifiThread.
1736 */
1737 private class WifiHandler extends Handler {
1738 public WifiHandler(Looper looper) {
1739 super(looper);
1740 }
1741
1742 @Override
1743 public void handleMessage(Message msg) {
1744 switch (msg.what) {
1745
1746 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001747 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 sWakeLock.release();
1749 break;
1750
1751 case MESSAGE_START_WIFI:
1752 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1753 mWifiStateTracker.restart();
1754 sWakeLock.release();
1755 break;
1756
1757 case MESSAGE_DISABLE_WIFI:
1758 // a non-zero msg.arg1 value means the "enabled" setting
1759 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001760 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 sWakeLock.release();
1762 break;
1763
1764 case MESSAGE_STOP_WIFI:
1765 mWifiStateTracker.disconnectAndStop();
1766 // don't release wakelock
1767 break;
1768
1769 case MESSAGE_RELEASE_WAKELOCK:
1770 synchronized (sDriverStopWakeLock) {
1771 if (sDriverStopWakeLock.isHeld()) {
1772 sDriverStopWakeLock.release();
1773 }
1774 }
1775 break;
1776 }
1777 }
1778 }
1779
1780 @Override
1781 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1782 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1783 != PackageManager.PERMISSION_GRANTED) {
1784 pw.println("Permission Denial: can't dump WifiService from from pid="
1785 + Binder.getCallingPid()
1786 + ", uid=" + Binder.getCallingUid());
1787 return;
1788 }
1789 pw.println("Wi-Fi is " + stateName(mWifiState));
1790 pw.println("Stay-awake conditions: " +
1791 Settings.System.getInt(mContext.getContentResolver(),
1792 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1793 pw.println();
1794
1795 pw.println("Internal state:");
1796 pw.println(mWifiStateTracker);
1797 pw.println();
1798 pw.println("Latest scan results:");
1799 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1800 if (scanResults != null && scanResults.size() != 0) {
1801 pw.println(" BSSID Frequency RSSI Flags SSID");
1802 for (ScanResult r : scanResults) {
1803 pw.printf(" %17s %9d %5d %-16s %s%n",
1804 r.BSSID,
1805 r.frequency,
1806 r.level,
1807 r.capabilities,
1808 r.SSID == null ? "" : r.SSID);
1809 }
1810 }
1811 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001812 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1813 mScanLocksAcquired + " scan");
1814 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1815 mScanLocksReleased + " scan");
1816 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 pw.println("Locks held:");
1818 mLocks.dump(pw);
1819 }
1820
1821 private static String stateName(int wifiState) {
1822 switch (wifiState) {
1823 case WIFI_STATE_DISABLING:
1824 return "disabling";
1825 case WIFI_STATE_DISABLED:
1826 return "disabled";
1827 case WIFI_STATE_ENABLING:
1828 return "enabling";
1829 case WIFI_STATE_ENABLED:
1830 return "enabled";
1831 case WIFI_STATE_UNKNOWN:
1832 return "unknown state";
1833 default:
1834 return "[invalid state]";
1835 }
1836 }
1837
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001838 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001840 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842
1843 public void binderDied() {
1844 synchronized (mLocks) {
1845 releaseWifiLockLocked(mBinder);
1846 }
1847 }
1848
1849 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001850 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
1852 }
1853
1854 private class LockList {
1855 private List<WifiLock> mList;
1856
1857 private LockList() {
1858 mList = new ArrayList<WifiLock>();
1859 }
1860
1861 private synchronized boolean hasLocks() {
1862 return !mList.isEmpty();
1863 }
1864
1865 private synchronized int getStrongestLockMode() {
1866 if (mList.isEmpty()) {
1867 return WifiManager.WIFI_MODE_FULL;
1868 }
1869 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001870 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 return WifiManager.WIFI_MODE_FULL;
1872 }
1873 }
1874 return WifiManager.WIFI_MODE_SCAN_ONLY;
1875 }
1876
1877 private void addLock(WifiLock lock) {
1878 if (findLockByBinder(lock.mBinder) < 0) {
1879 mList.add(lock);
1880 }
1881 }
1882
1883 private WifiLock removeLock(IBinder binder) {
1884 int index = findLockByBinder(binder);
1885 if (index >= 0) {
1886 return mList.remove(index);
1887 } else {
1888 return null;
1889 }
1890 }
1891
1892 private int findLockByBinder(IBinder binder) {
1893 int size = mList.size();
1894 for (int i = size - 1; i >= 0; i--)
1895 if (mList.get(i).mBinder == binder)
1896 return i;
1897 return -1;
1898 }
1899
1900 private void dump(PrintWriter pw) {
1901 for (WifiLock l : mList) {
1902 pw.print(" ");
1903 pw.println(l);
1904 }
1905 }
1906 }
1907
1908 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1909 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1910 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1911 return false;
1912 }
1913 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1914 synchronized (mLocks) {
1915 return acquireWifiLockLocked(wifiLock);
1916 }
1917 }
1918
1919 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1920 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001921
1922 int uid = Binder.getCallingUid();
1923 long ident = Binder.clearCallingIdentity();
1924 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001925 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001926 case WifiManager.WIFI_MODE_FULL:
1927 ++mFullLocksAcquired;
1928 mBatteryStats.noteFullWifiLockAcquired(uid);
1929 break;
1930 case WifiManager.WIFI_MODE_SCAN_ONLY:
1931 ++mScanLocksAcquired;
1932 mBatteryStats.noteScanWifiLockAcquired(uid);
1933 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001934 }
1935 } catch (RemoteException e) {
1936 } finally {
1937 Binder.restoreCallingIdentity(ident);
1938 }
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 updateWifiState();
1941 return true;
1942 }
1943
1944 public boolean releaseWifiLock(IBinder lock) {
1945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1946 synchronized (mLocks) {
1947 return releaseWifiLockLocked(lock);
1948 }
1949 }
1950
1951 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001952 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001953
1954 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001955 hadLock = (wifiLock != null);
1956
1957 if (hadLock) {
1958 int uid = Binder.getCallingUid();
1959 long ident = Binder.clearCallingIdentity();
1960 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001961 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001962 case WifiManager.WIFI_MODE_FULL:
1963 ++mFullLocksReleased;
1964 mBatteryStats.noteFullWifiLockReleased(uid);
1965 break;
1966 case WifiManager.WIFI_MODE_SCAN_ONLY:
1967 ++mScanLocksReleased;
1968 mBatteryStats.noteScanWifiLockReleased(uid);
1969 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001970 }
1971 } catch (RemoteException e) {
1972 } finally {
1973 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001974 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001975 }
1976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001978 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001980
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001981 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001982 implements IBinder.DeathRecipient {
1983 String mTag;
1984 int mMode;
1985 IBinder mBinder;
1986
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001987 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001988 super();
1989 mTag = tag;
1990 mMode = mode;
1991 mBinder = binder;
1992 try {
1993 mBinder.linkToDeath(this, 0);
1994 } catch (RemoteException e) {
1995 binderDied();
1996 }
1997 }
1998 }
1999
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002000 private class Multicaster extends DeathRecipient {
2001 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002002 super(Binder.getCallingUid(), tag, binder);
2003 }
2004
2005 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002006 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002007 synchronized (mMulticasters) {
2008 int i = mMulticasters.indexOf(this);
2009 if (i != -1) {
2010 removeMulticasterLocked(i, mMode);
2011 }
2012 }
2013 }
2014
2015 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002016 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002017 }
2018
2019 public int getUid() {
2020 return mMode;
2021 }
2022 }
2023
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002024 public void acquireMulticastLock(IBinder binder, String tag) {
2025 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002026
2027 synchronized (mMulticasters) {
2028 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002029 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002030 // Note that we could call stopPacketFiltering only when
2031 // our new size == 1 (first call), but this function won't
2032 // be called often and by making the stopPacket call each
2033 // time we're less fragile and self-healing.
2034 WifiNative.stopPacketFiltering();
2035 }
2036
2037 int uid = Binder.getCallingUid();
2038 Long ident = Binder.clearCallingIdentity();
2039 try {
2040 mBatteryStats.noteWifiMulticastEnabled(uid);
2041 } catch (RemoteException e) {
2042 } finally {
2043 Binder.restoreCallingIdentity(ident);
2044 }
2045 }
2046
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002047 public void releaseMulticastLock() {
2048 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002049
2050 int uid = Binder.getCallingUid();
2051 synchronized (mMulticasters) {
2052 mMulticastDisabled++;
2053 int size = mMulticasters.size();
2054 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002055 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002056 if ((m != null) && (m.getUid() == uid)) {
2057 removeMulticasterLocked(i, uid);
2058 }
2059 }
2060 }
2061 }
2062
2063 private void removeMulticasterLocked(int i, int uid)
2064 {
2065 mMulticasters.remove(i);
2066 if (mMulticasters.size() == 0) {
2067 WifiNative.startPacketFiltering();
2068 }
2069
2070 Long ident = Binder.clearCallingIdentity();
2071 try {
2072 mBatteryStats.noteWifiMulticastDisabled(uid);
2073 } catch (RemoteException e) {
2074 } finally {
2075 Binder.restoreCallingIdentity(ident);
2076 }
2077 }
2078
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002079 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002080 enforceAccessPermission();
2081
2082 synchronized (mMulticasters) {
2083 return (mMulticasters.size() > 0);
2084 }
2085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086}