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