blob: 1528ba34efc72f5bbe4a3fa8b4d5194512dc2839 [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
1063 return netId;
1064 }
1065
1066 /*
1067 * For an update, if one of the setNetworkVariable operations fails,
1068 * we might want to roll back all the changes already made. But the
1069 * chances are that if anything is going to go wrong, it'll happen
1070 * the first time we try to set one of the variables.
1071 */
1072 if (newNetwork) {
1073 removeNetwork(netId);
1074 if (DBG) {
1075 Log.d(TAG,
1076 "Failed to set a network variable, removed network: "
1077 + netId);
1078 }
1079 }
1080 return -1;
1081 }
1082
1083 private static String makeString(BitSet set, String[] strings) {
1084 StringBuffer buf = new StringBuffer();
1085 int nextSetBit = -1;
1086
1087 /* Make sure all set bits are in [0, strings.length) to avoid
1088 * going out of bounds on strings. (Shouldn't happen, but...) */
1089 set = set.get(0, strings.length);
1090
1091 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1092 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1093 }
1094
1095 // remove trailing space
1096 if (set.cardinality() > 0) {
1097 buf.setLength(buf.length() - 1);
1098 }
1099
1100 return buf.toString();
1101 }
1102
1103 private static int lookupString(String string, String[] strings) {
1104 int size = strings.length;
1105
1106 string = string.replace('-', '_');
1107
1108 for (int i = 0; i < size; i++)
1109 if (string.equals(strings[i]))
1110 return i;
1111
1112 if (DBG) {
1113 // if we ever get here, we should probably add the
1114 // value to WifiConfiguration to reflect that it's
1115 // supported by the WPA supplicant
1116 Log.w(TAG, "Failed to look-up a string: " + string);
1117 }
1118
1119 return -1;
1120 }
1121
1122 /**
1123 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1124 * @param netId the integer that identifies the network configuration
1125 * to the supplicant
1126 * @return {@code true} if the operation succeeded
1127 */
1128 public boolean removeNetwork(int netId) {
1129 enforceChangePermission();
1130
1131 /*
1132 * If we have hidden networks, we may have to change the scan mode
1133 */
1134 removeNetworkIfHidden(netId);
1135
1136 return mWifiStateTracker.removeNetwork(netId);
1137 }
1138
1139 /**
1140 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1141 * @param netId the integer that identifies the network configuration
1142 * to the supplicant
1143 * @param disableOthers if true, disable all other networks.
1144 * @return {@code true} if the operation succeeded
1145 */
1146 public boolean enableNetwork(int netId, boolean disableOthers) {
1147 enforceChangePermission();
1148
1149 /*
1150 * If we have hidden networks, we may have to change the scan mode
1151 */
1152 synchronized(this) {
1153 if (disableOthers) {
1154 markAllHiddenNetworksButOneAsNotPresent(netId);
1155 }
1156 updateNetworkIfHidden(netId, true);
1157 }
1158
1159 synchronized (mWifiStateTracker) {
1160 return WifiNative.enableNetworkCommand(netId, disableOthers);
1161 }
1162 }
1163
1164 /**
1165 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1166 * @param netId the integer that identifies the network configuration
1167 * to the supplicant
1168 * @return {@code true} if the operation succeeded
1169 */
1170 public boolean disableNetwork(int netId) {
1171 enforceChangePermission();
1172
1173 /*
1174 * If we have hidden networks, we may have to change the scan mode
1175 */
1176 updateNetworkIfHidden(netId, false);
1177
1178 synchronized (mWifiStateTracker) {
1179 return WifiNative.disableNetworkCommand(netId);
1180 }
1181 }
1182
1183 /**
1184 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1185 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1186 */
1187 public WifiInfo getConnectionInfo() {
1188 enforceAccessPermission();
1189 /*
1190 * Make sure we have the latest information, by sending
1191 * a status request to the supplicant.
1192 */
1193 return mWifiStateTracker.requestConnectionInfo();
1194 }
1195
1196 /**
1197 * Return the results of the most recent access point scan, in the form of
1198 * a list of {@link ScanResult} objects.
1199 * @return the list of results
1200 */
1201 public List<ScanResult> getScanResults() {
1202 enforceAccessPermission();
1203 String reply;
1204 synchronized (mWifiStateTracker) {
1205 reply = WifiNative.scanResultsCommand();
1206 }
1207 if (reply == null) {
1208 return null;
1209 }
1210
1211 List<ScanResult> scanList = new ArrayList<ScanResult>();
1212
1213 int lineCount = 0;
1214
1215 int replyLen = reply.length();
1216 // Parse the result string, keeping in mind that the last line does
1217 // not end with a newline.
1218 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1219 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1220 ++lineCount;
1221 /*
1222 * Skip the first line, which is a header
1223 */
1224 if (lineCount == 1) {
1225 lineBeg = lineEnd + 1;
1226 continue;
1227 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001228 if (lineEnd > lineBeg) {
1229 String line = reply.substring(lineBeg, lineEnd);
1230 ScanResult scanResult = parseScanResult(line);
1231 if (scanResult != null) {
1232 scanList.add(scanResult);
1233 } else if (DBG) {
1234 Log.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 }
1237 lineBeg = lineEnd + 1;
1238 }
1239 }
1240 mWifiStateTracker.setScanResultsList(scanList);
1241 return scanList;
1242 }
1243
1244 /**
1245 * Parse the scan result line passed to us by wpa_supplicant (helper).
1246 * @param line the line to parse
1247 * @return the {@link ScanResult} object
1248 */
1249 private ScanResult parseScanResult(String line) {
1250 ScanResult scanResult = null;
1251 if (line != null) {
1252 /*
1253 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1254 * must synchronized here!
1255 */
1256 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001257 String[] result = scanResultPattern.split(line);
1258 if (3 <= result.length && result.length <= 5) {
1259 String bssid = result[0];
1260 // bssid | frequency | level | flags | ssid
1261 int frequency;
1262 int level;
1263 try {
1264 frequency = Integer.parseInt(result[1]);
1265 level = Integer.parseInt(result[2]);
1266 /* some implementations avoid negative values by adding 256
1267 * so we need to adjust for that here.
1268 */
1269 if (level > 0) level -= 256;
1270 } catch (NumberFormatException e) {
1271 frequency = 0;
1272 level = 0;
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001275 // bssid is the hash key
1276 scanResult = mScanResultCache.get(bssid);
1277 if (scanResult != null) {
1278 scanResult.level = level;
1279 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 /*
1281 * The formatting of the results returned by
1282 * wpa_supplicant is intended to make the fields
1283 * line up nicely when printed,
1284 * not to make them easy to parse. So we have to
1285 * apply some heuristics to figure out which field
1286 * is the SSID and which field is the flags.
1287 */
1288 String ssid;
1289 String flags;
1290 if (result.length == 4) {
1291 if (result[3].charAt(0) == '[') {
1292 flags = result[3];
1293 ssid = "";
1294 } else {
1295 flags = "";
1296 ssid = result[3];
1297 }
1298 } else if (result.length == 5) {
1299 flags = result[3];
1300 ssid = result[4];
1301 } else {
1302 // Here, we must have 3 fields: no flags and ssid
1303 // set
1304 flags = "";
1305 ssid = "";
1306 }
1307
1308 // Do not add scan results that have no SSID set
1309 if (0 < ssid.trim().length()) {
1310 scanResult =
1311 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001312 ssid, bssid, flags, level, frequency);
1313 mScanResultCache.put(bssid, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001316 } else {
1317 Log.w(TAG, "Misformatted scan result text with " +
1318 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320 }
1321 }
1322
1323 return scanResult;
1324 }
1325
1326 /**
1327 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1328 * and construct a {@code WifiConfiguration} that describes the encryption,
1329 * key management, and authenticaion capabilities of the access point.
1330 * @param flags the string returned by wpa_supplicant
1331 * @return the {@link WifiConfiguration} object, filled in
1332 */
1333 WifiConfiguration parseScanFlags(String flags) {
1334 WifiConfiguration config = new WifiConfiguration();
1335
1336 if (flags.length() == 0) {
1337 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1338 }
1339 // ... to be implemented
1340 return config;
1341 }
1342
1343 /**
1344 * Tell the supplicant to persist the current list of configured networks.
1345 * @return {@code true} if the operation succeeded
1346 */
1347 public boolean saveConfiguration() {
1348 boolean result;
1349 enforceChangePermission();
1350 synchronized (mWifiStateTracker) {
1351 result = WifiNative.saveConfigCommand();
1352 if (result && mNeedReconfig) {
1353 mNeedReconfig = false;
1354 result = WifiNative.reloadConfigCommand();
1355
1356 if (result) {
1357 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1358 mContext.sendBroadcast(intent);
1359 }
1360 }
1361 }
1362 return result;
1363 }
1364
1365 /**
1366 * Set the number of radio frequency channels that are allowed to be used
1367 * in the current regulatory domain. This method should be used only
1368 * if the correct number of channels cannot be determined automatically
1369 * for some reason. If the operation is successful, the new value is
1370 * persisted as a Secure setting.
1371 * @param numChannels the number of allowed channels. Must be greater than 0
1372 * and less than or equal to 16.
1373 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1374 * {@code numChannels} is outside the valid range.
1375 */
1376 public boolean setNumAllowedChannels(int numChannels) {
1377 enforceChangePermission();
1378 /*
1379 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1380 * but if Wi-Fi isn't currently enabled, that's not possible, and
1381 * we want to persist the setting anyway,so that it will take
1382 * effect when Wi-Fi does become enabled.
1383 */
1384 boolean found = false;
1385 for (int validChan : sValidRegulatoryChannelCounts) {
1386 if (validChan == numChannels) {
1387 found = true;
1388 break;
1389 }
1390 }
1391 if (!found) {
1392 return false;
1393 }
1394
1395 Settings.Secure.putInt(mContext.getContentResolver(),
1396 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1397 numChannels);
1398 mWifiStateTracker.setNumAllowedChannels(numChannels);
1399 return true;
1400 }
1401
1402 /**
1403 * Return the number of frequency channels that are allowed
1404 * to be used in the current regulatory domain.
1405 * @return the number of allowed channels, or {@code -1} if an error occurs
1406 */
1407 public int getNumAllowedChannels() {
1408 int numChannels;
1409
1410 enforceAccessPermission();
1411 synchronized (mWifiStateTracker) {
1412 /*
1413 * If we can't get the value from the driver (e.g., because
1414 * Wi-Fi is not currently enabled), get the value from
1415 * Settings.
1416 */
1417 numChannels = WifiNative.getNumAllowedChannelsCommand();
1418 if (numChannels < 0) {
1419 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1420 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1421 -1);
1422 }
1423 }
1424 return numChannels;
1425 }
1426
1427 /**
1428 * Return the list of valid values for the number of allowed radio channels
1429 * for various regulatory domains.
1430 * @return the list of channel counts
1431 */
1432 public int[] getValidChannelCounts() {
1433 enforceAccessPermission();
1434 return sValidRegulatoryChannelCounts;
1435 }
1436
1437 /**
1438 * Return the DHCP-assigned addresses from the last successful DHCP request,
1439 * if any.
1440 * @return the DHCP information
1441 */
1442 public DhcpInfo getDhcpInfo() {
1443 enforceAccessPermission();
1444 return mWifiStateTracker.getDhcpInfo();
1445 }
1446
1447 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1448 @Override
1449 public void onReceive(Context context, Intent intent) {
1450 String action = intent.getAction();
1451
1452 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1453 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1454 int stayAwakeConditions =
1455 Settings.System.getInt(mContext.getContentResolver(),
1456 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1457 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001458 Log.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 mAlarmManager.cancel(mIdleIntent);
1460 mDeviceIdle = false;
1461 mScreenOff = false;
1462 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001463 Log.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 mScreenOff = true;
1465 /*
1466 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1467 * AND the "stay on while plugged in" setting doesn't match the
1468 * current power conditions (i.e, not plugged in, plugged in to USB,
1469 * or plugged in to AC).
1470 */
1471 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001472 if (!mWifiStateTracker.hasIpAddress()) {
1473 // do not keep Wifi awake when screen is off if Wifi is not fully active
1474 mDeviceIdle = true;
1475 updateWifiState();
1476 } else {
1477 long triggerTime = System.currentTimeMillis() + idleMillis;
1478 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1479 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482 /* we can return now -- there's nothing to do until we get the idle intent back */
1483 return;
1484 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001485 Log.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 mDeviceIdle = true;
1487 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1488 /*
1489 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1490 * AND we are transitioning from a state in which the device was supposed
1491 * to stay awake to a state in which it is not supposed to stay awake.
1492 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1493 * the already-set timer.
1494 */
1495 int pluggedType = intent.getIntExtra("plugged", 0);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001496 Log.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1498 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1499 long triggerTime = System.currentTimeMillis() + idleMillis;
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001500 Log.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1502 mPluggedType = pluggedType;
1503 return;
1504 }
1505 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001506 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1507 boolean isBluetoothPlaying =
1508 intent.getIntExtra(
1509 BluetoothA2dp.SINK_STATE,
1510 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1511 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 } else {
1513 return;
1514 }
1515
1516 updateWifiState();
1517 }
1518
1519 /**
1520 * Determines whether the Wi-Fi chipset should stay awake or be put to
1521 * sleep. Looks at the setting for the sleep policy and the current
1522 * conditions.
1523 *
1524 * @see #shouldDeviceStayAwake(int, int)
1525 */
1526 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1527 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1528 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1529
1530 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1531 // Never sleep
1532 return true;
1533 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1534 (pluggedType != 0)) {
1535 // Never sleep while plugged, and we're plugged
1536 return true;
1537 } else {
1538 // Default
1539 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1540 }
1541 }
1542
1543 /**
1544 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1545 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1546 * of {@code 0} isn't really a plugged type, but rather an indication that the
1547 * device isn't plugged in at all, there is no bit value corresponding to a
1548 * {@code pluggedType} value of {@code 0}. That is why we shift by
1549 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1550 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1551 * keep the device (and hence Wi-Fi) awake.
1552 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1553 * being made
1554 * @return {@code true} if {@code pluggedType} indicates that the device is
1555 * supposed to stay awake, {@code false} otherwise.
1556 */
1557 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1558 return (stayAwakeConditions & pluggedType) != 0;
1559 }
1560 };
1561
Dianne Hackborn617f8772009-03-31 15:04:46 -07001562 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 Message msg = Message.obtain(mWifiHandler,
1564 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001565 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 msg.sendToTarget();
1567 }
1568
1569 private void sendStartMessage(boolean scanOnlyMode) {
1570 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1571 }
1572
1573 private void updateWifiState() {
1574 boolean wifiEnabled = getPersistedWifiEnabled();
1575 boolean airplaneMode = isAirplaneModeOn();
1576 boolean lockHeld = mLocks.hasLocks();
1577 int strongestLockMode;
1578 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1579 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1580 if (mDeviceIdle && lockHeld) {
1581 strongestLockMode = mLocks.getStrongestLockMode();
1582 } else {
1583 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1584 }
1585
1586 synchronized (mWifiHandler) {
1587 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1588 return;
1589 }
1590 if (wifiShouldBeEnabled) {
1591 if (wifiShouldBeStarted) {
1592 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001593 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 sWakeLock.acquire();
1595 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1596 } else {
1597 int wakeLockTimeout =
1598 Settings.Secure.getInt(
1599 mContext.getContentResolver(),
1600 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1601 DEFAULT_WAKELOCK_TIMEOUT);
1602 /*
1603 * The following wakelock is held in order to ensure
1604 * that the connectivity manager has time to fail over
1605 * to the mobile data network. The connectivity manager
1606 * releases it once mobile data connectivity has been
1607 * established. If connectivity cannot be established,
1608 * the wakelock is released after wakeLockTimeout
1609 * milliseconds have elapsed.
1610 */
1611 sDriverStopWakeLock.acquire();
1612 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1613 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1614 }
1615 } else {
1616 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001617 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619 }
1620 }
1621
1622 private void registerForBroadcasts() {
1623 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1625 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1626 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1627 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001628 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 mContext.registerReceiver(mReceiver, intentFilter);
1630 }
1631
1632 private boolean isAirplaneSensitive() {
1633 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1634 Settings.System.AIRPLANE_MODE_RADIOS);
1635 return airplaneModeRadios == null
1636 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1637 }
1638
1639 /**
1640 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1641 * currently on.
1642 * @return {@code true} if airplane mode is on.
1643 */
1644 private boolean isAirplaneModeOn() {
1645 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1646 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1647 }
1648
1649 /**
1650 * Handler that allows posting to the WifiThread.
1651 */
1652 private class WifiHandler extends Handler {
1653 public WifiHandler(Looper looper) {
1654 super(looper);
1655 }
1656
1657 @Override
1658 public void handleMessage(Message msg) {
1659 switch (msg.what) {
1660
1661 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001662 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 sWakeLock.release();
1664 break;
1665
1666 case MESSAGE_START_WIFI:
1667 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1668 mWifiStateTracker.restart();
1669 sWakeLock.release();
1670 break;
1671
1672 case MESSAGE_DISABLE_WIFI:
1673 // a non-zero msg.arg1 value means the "enabled" setting
1674 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001675 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 sWakeLock.release();
1677 break;
1678
1679 case MESSAGE_STOP_WIFI:
1680 mWifiStateTracker.disconnectAndStop();
1681 // don't release wakelock
1682 break;
1683
1684 case MESSAGE_RELEASE_WAKELOCK:
1685 synchronized (sDriverStopWakeLock) {
1686 if (sDriverStopWakeLock.isHeld()) {
1687 sDriverStopWakeLock.release();
1688 }
1689 }
1690 break;
1691 }
1692 }
1693 }
1694
1695 @Override
1696 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1697 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1698 != PackageManager.PERMISSION_GRANTED) {
1699 pw.println("Permission Denial: can't dump WifiService from from pid="
1700 + Binder.getCallingPid()
1701 + ", uid=" + Binder.getCallingUid());
1702 return;
1703 }
1704 pw.println("Wi-Fi is " + stateName(mWifiState));
1705 pw.println("Stay-awake conditions: " +
1706 Settings.System.getInt(mContext.getContentResolver(),
1707 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1708 pw.println();
1709
1710 pw.println("Internal state:");
1711 pw.println(mWifiStateTracker);
1712 pw.println();
1713 pw.println("Latest scan results:");
1714 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1715 if (scanResults != null && scanResults.size() != 0) {
1716 pw.println(" BSSID Frequency RSSI Flags SSID");
1717 for (ScanResult r : scanResults) {
1718 pw.printf(" %17s %9d %5d %-16s %s%n",
1719 r.BSSID,
1720 r.frequency,
1721 r.level,
1722 r.capabilities,
1723 r.SSID == null ? "" : r.SSID);
1724 }
1725 }
1726 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001727 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1728 mScanLocksAcquired + " scan");
1729 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1730 mScanLocksReleased + " scan");
1731 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 pw.println("Locks held:");
1733 mLocks.dump(pw);
1734 }
1735
1736 private static String stateName(int wifiState) {
1737 switch (wifiState) {
1738 case WIFI_STATE_DISABLING:
1739 return "disabling";
1740 case WIFI_STATE_DISABLED:
1741 return "disabled";
1742 case WIFI_STATE_ENABLING:
1743 return "enabling";
1744 case WIFI_STATE_ENABLED:
1745 return "enabled";
1746 case WIFI_STATE_UNKNOWN:
1747 return "unknown state";
1748 default:
1749 return "[invalid state]";
1750 }
1751 }
1752
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001753 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001755 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
1757
1758 public void binderDied() {
1759 synchronized (mLocks) {
1760 releaseWifiLockLocked(mBinder);
1761 }
1762 }
1763
1764 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001765 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 }
1768
1769 private class LockList {
1770 private List<WifiLock> mList;
1771
1772 private LockList() {
1773 mList = new ArrayList<WifiLock>();
1774 }
1775
1776 private synchronized boolean hasLocks() {
1777 return !mList.isEmpty();
1778 }
1779
1780 private synchronized int getStrongestLockMode() {
1781 if (mList.isEmpty()) {
1782 return WifiManager.WIFI_MODE_FULL;
1783 }
1784 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001785 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 return WifiManager.WIFI_MODE_FULL;
1787 }
1788 }
1789 return WifiManager.WIFI_MODE_SCAN_ONLY;
1790 }
1791
1792 private void addLock(WifiLock lock) {
1793 if (findLockByBinder(lock.mBinder) < 0) {
1794 mList.add(lock);
1795 }
1796 }
1797
1798 private WifiLock removeLock(IBinder binder) {
1799 int index = findLockByBinder(binder);
1800 if (index >= 0) {
1801 return mList.remove(index);
1802 } else {
1803 return null;
1804 }
1805 }
1806
1807 private int findLockByBinder(IBinder binder) {
1808 int size = mList.size();
1809 for (int i = size - 1; i >= 0; i--)
1810 if (mList.get(i).mBinder == binder)
1811 return i;
1812 return -1;
1813 }
1814
1815 private void dump(PrintWriter pw) {
1816 for (WifiLock l : mList) {
1817 pw.print(" ");
1818 pw.println(l);
1819 }
1820 }
1821 }
1822
1823 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1825 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1826 return false;
1827 }
1828 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1829 synchronized (mLocks) {
1830 return acquireWifiLockLocked(wifiLock);
1831 }
1832 }
1833
1834 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1835 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001836
1837 int uid = Binder.getCallingUid();
1838 long ident = Binder.clearCallingIdentity();
1839 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001840 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001841 case WifiManager.WIFI_MODE_FULL:
1842 ++mFullLocksAcquired;
1843 mBatteryStats.noteFullWifiLockAcquired(uid);
1844 break;
1845 case WifiManager.WIFI_MODE_SCAN_ONLY:
1846 ++mScanLocksAcquired;
1847 mBatteryStats.noteScanWifiLockAcquired(uid);
1848 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001849 }
1850 } catch (RemoteException e) {
1851 } finally {
1852 Binder.restoreCallingIdentity(ident);
1853 }
1854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 updateWifiState();
1856 return true;
1857 }
1858
1859 public boolean releaseWifiLock(IBinder lock) {
1860 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1861 synchronized (mLocks) {
1862 return releaseWifiLockLocked(lock);
1863 }
1864 }
1865
1866 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001867 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001868
1869 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001870 hadLock = (wifiLock != null);
1871
1872 if (hadLock) {
1873 int uid = Binder.getCallingUid();
1874 long ident = Binder.clearCallingIdentity();
1875 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001876 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001877 case WifiManager.WIFI_MODE_FULL:
1878 ++mFullLocksReleased;
1879 mBatteryStats.noteFullWifiLockReleased(uid);
1880 break;
1881 case WifiManager.WIFI_MODE_SCAN_ONLY:
1882 ++mScanLocksReleased;
1883 mBatteryStats.noteScanWifiLockReleased(uid);
1884 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001885 }
1886 } catch (RemoteException e) {
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001889 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001890 }
1891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001893 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001895
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001896 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001897 implements IBinder.DeathRecipient {
1898 String mTag;
1899 int mMode;
1900 IBinder mBinder;
1901
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001902 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001903 super();
1904 mTag = tag;
1905 mMode = mode;
1906 mBinder = binder;
1907 try {
1908 mBinder.linkToDeath(this, 0);
1909 } catch (RemoteException e) {
1910 binderDied();
1911 }
1912 }
1913 }
1914
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001915 private class Multicaster extends DeathRecipient {
1916 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001917 super(Binder.getCallingUid(), tag, binder);
1918 }
1919
1920 public void binderDied() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001921 Log.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001922 synchronized (mMulticasters) {
1923 int i = mMulticasters.indexOf(this);
1924 if (i != -1) {
1925 removeMulticasterLocked(i, mMode);
1926 }
1927 }
1928 }
1929
1930 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001931 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001932 }
1933
1934 public int getUid() {
1935 return mMode;
1936 }
1937 }
1938
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001939 public void acquireMulticastLock(IBinder binder, String tag) {
1940 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001941
1942 synchronized (mMulticasters) {
1943 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001944 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001945 // Note that we could call stopPacketFiltering only when
1946 // our new size == 1 (first call), but this function won't
1947 // be called often and by making the stopPacket call each
1948 // time we're less fragile and self-healing.
1949 WifiNative.stopPacketFiltering();
1950 }
1951
1952 int uid = Binder.getCallingUid();
1953 Long ident = Binder.clearCallingIdentity();
1954 try {
1955 mBatteryStats.noteWifiMulticastEnabled(uid);
1956 } catch (RemoteException e) {
1957 } finally {
1958 Binder.restoreCallingIdentity(ident);
1959 }
1960 }
1961
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001962 public void releaseMulticastLock() {
1963 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001964
1965 int uid = Binder.getCallingUid();
1966 synchronized (mMulticasters) {
1967 mMulticastDisabled++;
1968 int size = mMulticasters.size();
1969 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001970 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001971 if ((m != null) && (m.getUid() == uid)) {
1972 removeMulticasterLocked(i, uid);
1973 }
1974 }
1975 }
1976 }
1977
1978 private void removeMulticasterLocked(int i, int uid)
1979 {
1980 mMulticasters.remove(i);
1981 if (mMulticasters.size() == 0) {
1982 WifiNative.startPacketFiltering();
1983 }
1984
1985 Long ident = Binder.clearCallingIdentity();
1986 try {
1987 mBatteryStats.noteWifiMulticastDisabled(uid);
1988 } catch (RemoteException e) {
1989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 }
1993
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001994 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001995 enforceAccessPermission();
1996
1997 synchronized (mMulticasters) {
1998 return (mMulticasters.size() > 0);
1999 }
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001}