blob: 5df88b26f8f570e4102097e9558c75b07ba8815d [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 Lockwoodb30475e2009-04-21 13:55:07 -07001352 // bssid is the hash key
1353 scanResult = mScanResultCache.get(bssid);
1354 if (scanResult != null) {
1355 scanResult.level = level;
1356 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 /*
1358 * The formatting of the results returned by
1359 * wpa_supplicant is intended to make the fields
1360 * line up nicely when printed,
1361 * not to make them easy to parse. So we have to
1362 * apply some heuristics to figure out which field
1363 * is the SSID and which field is the flags.
1364 */
1365 String ssid;
1366 String flags;
1367 if (result.length == 4) {
1368 if (result[3].charAt(0) == '[') {
1369 flags = result[3];
1370 ssid = "";
1371 } else {
1372 flags = "";
1373 ssid = result[3];
1374 }
1375 } else if (result.length == 5) {
1376 flags = result[3];
1377 ssid = result[4];
1378 } else {
1379 // Here, we must have 3 fields: no flags and ssid
1380 // set
1381 flags = "";
1382 ssid = "";
1383 }
1384
1385 // Do not add scan results that have no SSID set
1386 if (0 < ssid.trim().length()) {
1387 scanResult =
1388 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001389 ssid, bssid, flags, level, frequency);
1390 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001393 } else {
1394 Log.w(TAG, "Misformatted scan result text with " +
1395 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 }
1398 }
1399
1400 return scanResult;
1401 }
1402
1403 /**
1404 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1405 * and construct a {@code WifiConfiguration} that describes the encryption,
1406 * key management, and authenticaion capabilities of the access point.
1407 * @param flags the string returned by wpa_supplicant
1408 * @return the {@link WifiConfiguration} object, filled in
1409 */
1410 WifiConfiguration parseScanFlags(String flags) {
1411 WifiConfiguration config = new WifiConfiguration();
1412
1413 if (flags.length() == 0) {
1414 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1415 }
1416 // ... to be implemented
1417 return config;
1418 }
1419
1420 /**
1421 * Tell the supplicant to persist the current list of configured networks.
1422 * @return {@code true} if the operation succeeded
1423 */
1424 public boolean saveConfiguration() {
1425 boolean result;
1426 enforceChangePermission();
1427 synchronized (mWifiStateTracker) {
1428 result = WifiNative.saveConfigCommand();
1429 if (result && mNeedReconfig) {
1430 mNeedReconfig = false;
1431 result = WifiNative.reloadConfigCommand();
1432
1433 if (result) {
1434 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1435 mContext.sendBroadcast(intent);
1436 }
1437 }
1438 }
1439 return result;
1440 }
1441
1442 /**
1443 * Set the number of radio frequency channels that are allowed to be used
1444 * in the current regulatory domain. This method should be used only
1445 * if the correct number of channels cannot be determined automatically
1446 * for some reason. If the operation is successful, the new value is
1447 * persisted as a Secure setting.
1448 * @param numChannels the number of allowed channels. Must be greater than 0
1449 * and less than or equal to 16.
1450 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1451 * {@code numChannels} is outside the valid range.
1452 */
1453 public boolean setNumAllowedChannels(int numChannels) {
1454 enforceChangePermission();
1455 /*
1456 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1457 * but if Wi-Fi isn't currently enabled, that's not possible, and
1458 * we want to persist the setting anyway,so that it will take
1459 * effect when Wi-Fi does become enabled.
1460 */
1461 boolean found = false;
1462 for (int validChan : sValidRegulatoryChannelCounts) {
1463 if (validChan == numChannels) {
1464 found = true;
1465 break;
1466 }
1467 }
1468 if (!found) {
1469 return false;
1470 }
1471
1472 Settings.Secure.putInt(mContext.getContentResolver(),
1473 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1474 numChannels);
1475 mWifiStateTracker.setNumAllowedChannels(numChannels);
1476 return true;
1477 }
1478
1479 /**
1480 * Return the number of frequency channels that are allowed
1481 * to be used in the current regulatory domain.
1482 * @return the number of allowed channels, or {@code -1} if an error occurs
1483 */
1484 public int getNumAllowedChannels() {
1485 int numChannels;
1486
1487 enforceAccessPermission();
1488 synchronized (mWifiStateTracker) {
1489 /*
1490 * If we can't get the value from the driver (e.g., because
1491 * Wi-Fi is not currently enabled), get the value from
1492 * Settings.
1493 */
1494 numChannels = WifiNative.getNumAllowedChannelsCommand();
1495 if (numChannels < 0) {
1496 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1497 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1498 -1);
1499 }
1500 }
1501 return numChannels;
1502 }
1503
1504 /**
1505 * Return the list of valid values for the number of allowed radio channels
1506 * for various regulatory domains.
1507 * @return the list of channel counts
1508 */
1509 public int[] getValidChannelCounts() {
1510 enforceAccessPermission();
1511 return sValidRegulatoryChannelCounts;
1512 }
1513
1514 /**
1515 * Return the DHCP-assigned addresses from the last successful DHCP request,
1516 * if any.
1517 * @return the DHCP information
1518 */
1519 public DhcpInfo getDhcpInfo() {
1520 enforceAccessPermission();
1521 return mWifiStateTracker.getDhcpInfo();
1522 }
1523
1524 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1525 @Override
1526 public void onReceive(Context context, Intent intent) {
1527 String action = intent.getAction();
1528
1529 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1530 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1531 int stayAwakeConditions =
1532 Settings.System.getInt(mContext.getContentResolver(),
1533 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1534 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001535 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mAlarmManager.cancel(mIdleIntent);
1537 mDeviceIdle = false;
1538 mScreenOff = false;
1539 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001540 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 mScreenOff = true;
1542 /*
1543 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1544 * AND the "stay on while plugged in" setting doesn't match the
1545 * current power conditions (i.e, not plugged in, plugged in to USB,
1546 * or plugged in to AC).
1547 */
1548 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001549 if (!mWifiStateTracker.hasIpAddress()) {
1550 // do not keep Wifi awake when screen is off if Wifi is not fully active
1551 mDeviceIdle = true;
1552 updateWifiState();
1553 } else {
1554 long triggerTime = System.currentTimeMillis() + idleMillis;
1555 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1556 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 /* we can return now -- there's nothing to do until we get the idle intent back */
1560 return;
1561 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001562 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 mDeviceIdle = true;
1564 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1565 /*
1566 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1567 * AND we are transitioning from a state in which the device was supposed
1568 * to stay awake to a state in which it is not supposed to stay awake.
1569 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1570 * the already-set timer.
1571 */
1572 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001573 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1575 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1576 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001577 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1579 mPluggedType = pluggedType;
1580 return;
1581 }
1582 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001583 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1584 boolean isBluetoothPlaying =
1585 intent.getIntExtra(
1586 BluetoothA2dp.SINK_STATE,
1587 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1588 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 } else {
1590 return;
1591 }
1592
1593 updateWifiState();
1594 }
1595
1596 /**
1597 * Determines whether the Wi-Fi chipset should stay awake or be put to
1598 * sleep. Looks at the setting for the sleep policy and the current
1599 * conditions.
1600 *
1601 * @see #shouldDeviceStayAwake(int, int)
1602 */
1603 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1604 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1605 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1606
1607 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1608 // Never sleep
1609 return true;
1610 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1611 (pluggedType != 0)) {
1612 // Never sleep while plugged, and we're plugged
1613 return true;
1614 } else {
1615 // Default
1616 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1617 }
1618 }
1619
1620 /**
1621 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1622 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1623 * of {@code 0} isn't really a plugged type, but rather an indication that the
1624 * device isn't plugged in at all, there is no bit value corresponding to a
1625 * {@code pluggedType} value of {@code 0}. That is why we shift by
1626 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1627 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1628 * keep the device (and hence Wi-Fi) awake.
1629 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1630 * being made
1631 * @return {@code true} if {@code pluggedType} indicates that the device is
1632 * supposed to stay awake, {@code false} otherwise.
1633 */
1634 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1635 return (stayAwakeConditions & pluggedType) != 0;
1636 }
1637 };
1638
Dianne Hackborn617f8772009-03-31 15:04:46 -07001639 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 Message msg = Message.obtain(mWifiHandler,
1641 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001642 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 msg.sendToTarget();
1644 }
1645
1646 private void sendStartMessage(boolean scanOnlyMode) {
1647 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1648 }
1649
1650 private void updateWifiState() {
1651 boolean wifiEnabled = getPersistedWifiEnabled();
1652 boolean airplaneMode = isAirplaneModeOn();
1653 boolean lockHeld = mLocks.hasLocks();
1654 int strongestLockMode;
1655 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1656 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1657 if (mDeviceIdle && lockHeld) {
1658 strongestLockMode = mLocks.getStrongestLockMode();
1659 } else {
1660 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1661 }
1662
1663 synchronized (mWifiHandler) {
1664 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1665 return;
1666 }
1667 if (wifiShouldBeEnabled) {
1668 if (wifiShouldBeStarted) {
1669 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001670 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 sWakeLock.acquire();
1672 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1673 } else {
1674 int wakeLockTimeout =
1675 Settings.Secure.getInt(
1676 mContext.getContentResolver(),
1677 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1678 DEFAULT_WAKELOCK_TIMEOUT);
1679 /*
1680 * The following wakelock is held in order to ensure
1681 * that the connectivity manager has time to fail over
1682 * to the mobile data network. The connectivity manager
1683 * releases it once mobile data connectivity has been
1684 * established. If connectivity cannot be established,
1685 * the wakelock is released after wakeLockTimeout
1686 * milliseconds have elapsed.
1687 */
1688 sDriverStopWakeLock.acquire();
1689 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1690 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1691 }
1692 } else {
1693 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001694 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696 }
1697 }
1698
1699 private void registerForBroadcasts() {
1700 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1702 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1703 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1704 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001705 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 mContext.registerReceiver(mReceiver, intentFilter);
1707 }
1708
1709 private boolean isAirplaneSensitive() {
1710 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1711 Settings.System.AIRPLANE_MODE_RADIOS);
1712 return airplaneModeRadios == null
1713 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1714 }
1715
1716 /**
1717 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1718 * currently on.
1719 * @return {@code true} if airplane mode is on.
1720 */
1721 private boolean isAirplaneModeOn() {
1722 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1723 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1724 }
1725
1726 /**
1727 * Handler that allows posting to the WifiThread.
1728 */
1729 private class WifiHandler extends Handler {
1730 public WifiHandler(Looper looper) {
1731 super(looper);
1732 }
1733
1734 @Override
1735 public void handleMessage(Message msg) {
1736 switch (msg.what) {
1737
1738 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001739 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 sWakeLock.release();
1741 break;
1742
1743 case MESSAGE_START_WIFI:
1744 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1745 mWifiStateTracker.restart();
1746 sWakeLock.release();
1747 break;
1748
1749 case MESSAGE_DISABLE_WIFI:
1750 // a non-zero msg.arg1 value means the "enabled" setting
1751 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001752 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 sWakeLock.release();
1754 break;
1755
1756 case MESSAGE_STOP_WIFI:
1757 mWifiStateTracker.disconnectAndStop();
1758 // don't release wakelock
1759 break;
1760
1761 case MESSAGE_RELEASE_WAKELOCK:
1762 synchronized (sDriverStopWakeLock) {
1763 if (sDriverStopWakeLock.isHeld()) {
1764 sDriverStopWakeLock.release();
1765 }
1766 }
1767 break;
1768 }
1769 }
1770 }
1771
1772 @Override
1773 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1774 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1775 != PackageManager.PERMISSION_GRANTED) {
1776 pw.println("Permission Denial: can't dump WifiService from from pid="
1777 + Binder.getCallingPid()
1778 + ", uid=" + Binder.getCallingUid());
1779 return;
1780 }
1781 pw.println("Wi-Fi is " + stateName(mWifiState));
1782 pw.println("Stay-awake conditions: " +
1783 Settings.System.getInt(mContext.getContentResolver(),
1784 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1785 pw.println();
1786
1787 pw.println("Internal state:");
1788 pw.println(mWifiStateTracker);
1789 pw.println();
1790 pw.println("Latest scan results:");
1791 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1792 if (scanResults != null && scanResults.size() != 0) {
1793 pw.println(" BSSID Frequency RSSI Flags SSID");
1794 for (ScanResult r : scanResults) {
1795 pw.printf(" %17s %9d %5d %-16s %s%n",
1796 r.BSSID,
1797 r.frequency,
1798 r.level,
1799 r.capabilities,
1800 r.SSID == null ? "" : r.SSID);
1801 }
1802 }
1803 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001804 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1805 mScanLocksAcquired + " scan");
1806 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1807 mScanLocksReleased + " scan");
1808 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 pw.println("Locks held:");
1810 mLocks.dump(pw);
1811 }
1812
1813 private static String stateName(int wifiState) {
1814 switch (wifiState) {
1815 case WIFI_STATE_DISABLING:
1816 return "disabling";
1817 case WIFI_STATE_DISABLED:
1818 return "disabled";
1819 case WIFI_STATE_ENABLING:
1820 return "enabling";
1821 case WIFI_STATE_ENABLED:
1822 return "enabled";
1823 case WIFI_STATE_UNKNOWN:
1824 return "unknown state";
1825 default:
1826 return "[invalid state]";
1827 }
1828 }
1829
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001830 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001832 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834
1835 public void binderDied() {
1836 synchronized (mLocks) {
1837 releaseWifiLockLocked(mBinder);
1838 }
1839 }
1840
1841 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001842 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
1845
1846 private class LockList {
1847 private List<WifiLock> mList;
1848
1849 private LockList() {
1850 mList = new ArrayList<WifiLock>();
1851 }
1852
1853 private synchronized boolean hasLocks() {
1854 return !mList.isEmpty();
1855 }
1856
1857 private synchronized int getStrongestLockMode() {
1858 if (mList.isEmpty()) {
1859 return WifiManager.WIFI_MODE_FULL;
1860 }
1861 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001862 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 return WifiManager.WIFI_MODE_FULL;
1864 }
1865 }
1866 return WifiManager.WIFI_MODE_SCAN_ONLY;
1867 }
1868
1869 private void addLock(WifiLock lock) {
1870 if (findLockByBinder(lock.mBinder) < 0) {
1871 mList.add(lock);
1872 }
1873 }
1874
1875 private WifiLock removeLock(IBinder binder) {
1876 int index = findLockByBinder(binder);
1877 if (index >= 0) {
1878 return mList.remove(index);
1879 } else {
1880 return null;
1881 }
1882 }
1883
1884 private int findLockByBinder(IBinder binder) {
1885 int size = mList.size();
1886 for (int i = size - 1; i >= 0; i--)
1887 if (mList.get(i).mBinder == binder)
1888 return i;
1889 return -1;
1890 }
1891
1892 private void dump(PrintWriter pw) {
1893 for (WifiLock l : mList) {
1894 pw.print(" ");
1895 pw.println(l);
1896 }
1897 }
1898 }
1899
1900 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1901 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1902 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1903 return false;
1904 }
1905 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1906 synchronized (mLocks) {
1907 return acquireWifiLockLocked(wifiLock);
1908 }
1909 }
1910
1911 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1912 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001913
1914 int uid = Binder.getCallingUid();
1915 long ident = Binder.clearCallingIdentity();
1916 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001917 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001918 case WifiManager.WIFI_MODE_FULL:
1919 ++mFullLocksAcquired;
1920 mBatteryStats.noteFullWifiLockAcquired(uid);
1921 break;
1922 case WifiManager.WIFI_MODE_SCAN_ONLY:
1923 ++mScanLocksAcquired;
1924 mBatteryStats.noteScanWifiLockAcquired(uid);
1925 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001926 }
1927 } catch (RemoteException e) {
1928 } finally {
1929 Binder.restoreCallingIdentity(ident);
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 updateWifiState();
1933 return true;
1934 }
1935
1936 public boolean releaseWifiLock(IBinder lock) {
1937 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1938 synchronized (mLocks) {
1939 return releaseWifiLockLocked(lock);
1940 }
1941 }
1942
1943 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001944 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001945
1946 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001947 hadLock = (wifiLock != null);
1948
1949 if (hadLock) {
1950 int uid = Binder.getCallingUid();
1951 long ident = Binder.clearCallingIdentity();
1952 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001953 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001954 case WifiManager.WIFI_MODE_FULL:
1955 ++mFullLocksReleased;
1956 mBatteryStats.noteFullWifiLockReleased(uid);
1957 break;
1958 case WifiManager.WIFI_MODE_SCAN_ONLY:
1959 ++mScanLocksReleased;
1960 mBatteryStats.noteScanWifiLockReleased(uid);
1961 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001962 }
1963 } catch (RemoteException e) {
1964 } finally {
1965 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001966 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001967 }
1968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001970 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001972
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001973 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001974 implements IBinder.DeathRecipient {
1975 String mTag;
1976 int mMode;
1977 IBinder mBinder;
1978
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001979 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001980 super();
1981 mTag = tag;
1982 mMode = mode;
1983 mBinder = binder;
1984 try {
1985 mBinder.linkToDeath(this, 0);
1986 } catch (RemoteException e) {
1987 binderDied();
1988 }
1989 }
1990 }
1991
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001992 private class Multicaster extends DeathRecipient {
1993 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001994 super(Binder.getCallingUid(), tag, binder);
1995 }
1996
1997 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001998 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001999 synchronized (mMulticasters) {
2000 int i = mMulticasters.indexOf(this);
2001 if (i != -1) {
2002 removeMulticasterLocked(i, mMode);
2003 }
2004 }
2005 }
2006
2007 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002008 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002009 }
2010
2011 public int getUid() {
2012 return mMode;
2013 }
2014 }
2015
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002016 public void acquireMulticastLock(IBinder binder, String tag) {
2017 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002018
2019 synchronized (mMulticasters) {
2020 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002021 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002022 // Note that we could call stopPacketFiltering only when
2023 // our new size == 1 (first call), but this function won't
2024 // be called often and by making the stopPacket call each
2025 // time we're less fragile and self-healing.
2026 WifiNative.stopPacketFiltering();
2027 }
2028
2029 int uid = Binder.getCallingUid();
2030 Long ident = Binder.clearCallingIdentity();
2031 try {
2032 mBatteryStats.noteWifiMulticastEnabled(uid);
2033 } catch (RemoteException e) {
2034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
2037 }
2038
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002039 public void releaseMulticastLock() {
2040 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002041
2042 int uid = Binder.getCallingUid();
2043 synchronized (mMulticasters) {
2044 mMulticastDisabled++;
2045 int size = mMulticasters.size();
2046 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002047 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002048 if ((m != null) && (m.getUid() == uid)) {
2049 removeMulticasterLocked(i, uid);
2050 }
2051 }
2052 }
2053 }
2054
2055 private void removeMulticasterLocked(int i, int uid)
2056 {
2057 mMulticasters.remove(i);
2058 if (mMulticasters.size() == 0) {
2059 WifiNative.startPacketFiltering();
2060 }
2061
2062 Long ident = Binder.clearCallingIdentity();
2063 try {
2064 mBatteryStats.noteWifiMulticastDisabled(uid);
2065 } catch (RemoteException e) {
2066 } finally {
2067 Binder.restoreCallingIdentity(ident);
2068 }
2069 }
2070
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002071 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002072 enforceAccessPermission();
2073
2074 synchronized (mMulticasters) {
2075 return (mMulticasters.size() > 0);
2076 }
2077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078}