blob: af4d7e4d97247b6350386c1f85c5761d0c514314 [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
Irfan Sheriff5321aef2010-02-12 12:35:59 -080025import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
26import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
27import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
28import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
29import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.AlarmManager;
32import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070033import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080034import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.BroadcastReceiver;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.pm.PackageManager;
41import android.net.wifi.IWifiManager;
42import android.net.wifi.WifiInfo;
43import android.net.wifi.WifiManager;
44import android.net.wifi.WifiNative;
45import android.net.wifi.WifiStateTracker;
46import android.net.wifi.ScanResult;
47import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070048import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080049import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080050import android.net.ConnectivityManager;
51import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.NetworkStateTracker;
53import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040054import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
56import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080059import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
62import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070063import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070065import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.text.TextUtils;
69
70import java.util.ArrayList;
71import java.util.BitSet;
72import java.util.HashMap;
73import java.util.LinkedHashMap;
74import java.util.List;
75import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080076import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.regex.Pattern;
78import java.io.FileDescriptor;
79import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080080import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
The Android Open Source Project10592532009-03-18 17:39:46 -070082import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080083import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070084import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080085import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087/**
88 * WifiService handles remote WiFi operation requests by implementing
89 * the IWifiManager interface. It also creates a WifiMonitor to listen
90 * for Wifi-related events.
91 *
92 * @hide
93 */
94public class WifiService extends IWifiManager.Stub {
95 private static final String TAG = "WifiService";
96 private static final boolean DBG = false;
97 private static final Pattern scanResultPattern = Pattern.compile("\t+");
98 private final WifiStateTracker mWifiStateTracker;
Irfan Sheriffc2f54c22010-03-18 14:02:22 -070099 /* TODO: fetch a configurable interface */
100 private static final String SOFTAP_IFACE = "wl0.1";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 private Context mContext;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800103 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105 private AlarmManager mAlarmManager;
106 private PendingIntent mIdleIntent;
107 private static final int IDLE_REQUEST = 0;
108 private boolean mScreenOff;
109 private boolean mDeviceIdle;
110 private int mPluggedType;
111
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800112 private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
113
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700114 // true if the user enabled Wifi while in airplane mode
115 private boolean mAirplaneModeOverwridden;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700118 // some wifi lock statistics
Irfan Sheriff8c11e952010-08-12 20:26:23 -0700119 private int mFullHighPerfLocksAcquired;
120 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700121 private int mFullLocksAcquired;
122 private int mFullLocksReleased;
123 private int mScanLocksAcquired;
124 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700125
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700126 private final List<Multicaster> mMulticasters =
127 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700128 private int mMulticastEnabled;
129 private int mMulticastDisabled;
130
The Android Open Source Project10592532009-03-18 17:39:46 -0700131 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800132
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800133 private INetworkManagementService nwService;
134 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800135 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800136 private String[] mWifiRegexs;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800139 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
140 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 * the approximate point at which the battery drain caused by Wi-Fi
142 * being enabled but not active exceeds the battery drain caused by
143 * re-establishing a connection to the mobile data network.
144 */
145 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
146
147 private static final String WAKELOCK_TAG = "WifiService";
148
149 /**
150 * The maximum amount of time to hold the wake lock after a disconnect
151 * caused by stopping the driver. Establishing an EDGE connection has been
152 * observed to take about 5 seconds under normal circumstances. This
153 * provides a bit of extra margin.
154 * <p>
155 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
156 * This is the default value if a Settings.Secure value is not present.
157 */
158 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
159
160 // Wake lock used by driver-stop operation
161 private static PowerManager.WakeLock sDriverStopWakeLock;
162 // Wake lock used by other operations
163 private static PowerManager.WakeLock sWakeLock;
164
Irfan Sheriff59610c02010-03-30 11:00:41 -0700165 private static final int MESSAGE_ENABLE_WIFI = 0;
166 private static final int MESSAGE_DISABLE_WIFI = 1;
167 private static final int MESSAGE_STOP_WIFI = 2;
168 private static final int MESSAGE_START_WIFI = 3;
169 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
170 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800171 private static final int MESSAGE_START_ACCESS_POINT = 6;
172 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700173 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
176 private final WifiHandler mWifiHandler;
177
178 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 * Cache of scan results objects (size is somewhat arbitrary)
180 */
181 private static final int SCAN_RESULT_CACHE_SIZE = 80;
182 private final LinkedHashMap<String, ScanResult> mScanResultCache;
183
184 /*
185 * Character buffer used to parse scan results (optimization)
186 */
187 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 private boolean mNeedReconfig;
189
Dianne Hackborn617f8772009-03-31 15:04:46 -0700190 /*
191 * Last UID that asked to enable WIFI.
192 */
193 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800194
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700195 /*
196 * Last UID that asked to enable WIFI AP.
197 */
198 private int mLastApEnableUid = Process.myUid();
199
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 /**
202 * Number of allowed radio frequency channels in various regulatory domains.
203 * This list is sufficient for 802.11b/g networks (2.4GHz range).
204 */
205 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
206
207 private static final String ACTION_DEVICE_IDLE =
208 "com.android.server.WifiManager.action.DEVICE_IDLE";
209
210 WifiService(Context context, WifiStateTracker tracker) {
211 mContext = context;
212 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400213 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700214 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800215
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800216 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
217 nwService = INetworkManagementService.Stub.asInterface(b);
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 mScanResultCache = new LinkedHashMap<String, ScanResult>(
220 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
221 /*
222 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
223 * elements
224 */
225 public boolean removeEldestEntry(Map.Entry eldest) {
226 return SCAN_RESULT_CACHE_SIZE < this.size();
227 }
228 };
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 HandlerThread wifiThread = new HandlerThread("WifiService");
231 wifiThread.start();
232 mWifiHandler = new WifiHandler(wifiThread.getLooper());
233
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800234 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800235 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
237 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
238 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
239 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
240
241 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
242 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
243 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mContext.registerReceiver(
246 new BroadcastReceiver() {
247 @Override
248 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700249 // clear our flag indicating the user has overwridden airplane mode
250 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700251 // on airplane disable, restore Wifi if the saved state indicates so
252 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
253 persistWifiEnabled(true);
254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 updateWifiState();
256 }
257 },
258 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
259
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800260 mContext.registerReceiver(
261 new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264
265 ArrayList<String> available = intent.getStringArrayListExtra(
266 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
267 ArrayList<String> active = intent.getStringArrayListExtra(
268 ConnectivityManager.EXTRA_ACTIVE_TETHER);
269 updateTetherState(available, active);
270
271 }
272 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800273 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800274
Irfan Sheriff7b009782010-03-11 16:37:45 -0800275 /**
276 * Check if Wi-Fi needs to be enabled and start
277 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700278 *
279 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800280 */
281 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700282 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700283 boolean wifiEnabled = !isAirplaneModeOn()
284 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800285 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
286 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700287 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800288 }
289
290 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
291
292 boolean wifiTethered = false;
293 boolean wifiAvailable = false;
294
295 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
296 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
297
298 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
299 mWifiRegexs = mCm.getTetherableWifiRegexs();
300
301 for (String intf : available) {
302 for (String regex : mWifiRegexs) {
303 if (intf.matches(regex)) {
304
305 InterfaceConfiguration ifcg = null;
306 try {
307 ifcg = service.getInterfaceConfig(intf);
308 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700309 /* IP/netmask: 192.168.43.1/255.255.255.0 */
310 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800311 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
312 ifcg.interfaceFlags = "up";
313
314 service.setInterfaceConfig(intf, ifcg);
315 }
316 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800317 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700318 try {
319 nwService.stopAccessPoint();
320 } catch (Exception ee) {
321 Slog.e(TAG, "Could not stop AP, :" + ee);
322 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800323 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800324 return;
325 }
326
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800327 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800328 Slog.e(TAG, "Error tethering "+intf);
329 }
330 break;
331 }
332 }
333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 }
335
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700336 private boolean testAndClearWifiSavedState() {
337 final ContentResolver cr = mContext.getContentResolver();
338 int wifiSavedState = 0;
339 try {
340 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
341 if(wifiSavedState == 1)
342 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
343 } catch (Settings.SettingNotFoundException e) {
344 ;
345 }
346 return (wifiSavedState == 1);
347 }
348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 private boolean getPersistedWifiEnabled() {
350 final ContentResolver cr = mContext.getContentResolver();
351 try {
352 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
353 } catch (Settings.SettingNotFoundException e) {
354 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
355 return false;
356 }
357 }
358
359 private void persistWifiEnabled(boolean enabled) {
360 final ContentResolver cr = mContext.getContentResolver();
361 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
362 }
363
364 NetworkStateTracker getNetworkStateTracker() {
365 return mWifiStateTracker;
366 }
367
368 /**
369 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
370 * @return {@code true} if the operation succeeds
371 */
372 public boolean pingSupplicant() {
373 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800374
375 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
377
378 /**
379 * see {@link android.net.wifi.WifiManager#startScan()}
380 * @return {@code true} if the operation succeeds
381 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400382 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800384
385 switch (mWifiStateTracker.getSupplicantState()) {
386 case DISCONNECTED:
387 case INACTIVE:
388 case SCANNING:
389 case DORMANT:
390 break;
391 default:
392 mWifiStateTracker.setScanResultHandling(
393 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
394 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800396 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 }
398
399 /**
400 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
401 * @param enable {@code true} to enable, {@code false} to disable.
402 * @return {@code true} if the enable/disable operation was
403 * started or is already in the queue.
404 */
405 public boolean setWifiEnabled(boolean enable) {
406 enforceChangePermission();
407 if (mWifiHandler == null) return false;
408
409 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700410 // caller may not have WAKE_LOCK permission - it's not required here
411 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700413 Binder.restoreCallingIdentity(ident);
414
Dianne Hackborn617f8772009-03-31 15:04:46 -0700415 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700416 // set a flag if the user is enabling Wifi while in airplane mode
417 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700418 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420
421 return true;
422 }
423
424 /**
425 * Enables/disables Wi-Fi synchronously.
426 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
427 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700428 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 * @return {@code true} if the operation succeeds (or if the existing state
430 * is the same as the requested state)
431 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700432 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800434 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800436 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 return true;
438 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700439 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 return false;
441 }
442
Irfan Sheriffcd770372010-01-08 09:36:04 -0800443 /**
444 * Multiple calls to unregisterReceiver() cause exception and a system crash.
445 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
446 * disable wifi at the same time.
447 * Avoid doing a disable when the current Wifi state is UNKNOWN
448 * TODO: Handle driver load fail and supplicant lost as seperate states
449 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800450 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800451 return false;
452 }
453
Irfan Sherifff91444c2010-03-24 12:11:00 -0700454 /**
455 * Fail Wifi if AP is enabled
456 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
457 * WIFI_STATE_FAILED
458 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800459 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700460 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
461 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800462 }
463
Irfan Sherifff91444c2010-03-24 12:11:00 -0700464 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800467 if (!mWifiStateTracker.loadDriver()) {
468 Slog.e(TAG, "Failed to load Wi-Fi driver.");
469 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
470 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800472 if (!mWifiStateTracker.startSupplicant()) {
473 mWifiStateTracker.unloadDriver();
474 Slog.e(TAG, "Failed to start supplicant daemon.");
475 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
476 return false;
477 }
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 registerForBroadcasts();
480 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 } else {
483
484 mContext.unregisterReceiver(mReceiver);
485 // Remove notification (it will no-op if it isn't visible)
486 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
487
488 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800489
490 if (!mWifiStateTracker.stopSupplicant()) {
491 Slog.e(TAG, "Failed to stop supplicant daemon.");
492 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
493 failedToStopSupplicantOrUnloadDriver = true;
494 }
495
496 /**
497 * Reset connections and disable interface
498 * before we unload the driver
499 */
500 mWifiStateTracker.resetConnections(true);
501
502 if (!mWifiStateTracker.unloadDriver()) {
503 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
504 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700505 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 failedToStopSupplicantOrUnloadDriver = true;
507 }
508 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 if (failedToStopSupplicantOrUnloadDriver) {
511 return false;
512 }
513 }
514
515 // Success!
516
517 if (persist) {
518 persistWifiEnabled(enable);
519 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700520 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 return true;
522 }
523
Dianne Hackborn617f8772009-03-31 15:04:46 -0700524 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800525 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
The Android Open Source Project10592532009-03-18 17:39:46 -0700527 long ident = Binder.clearCallingIdentity();
528 try {
529 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700530 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700531 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700532 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700533 }
534 } catch (RemoteException e) {
535 } finally {
536 Binder.restoreCallingIdentity(ident);
537 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800540 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541
542 // Broadcast
543 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
544 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
545 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
546 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
547 mContext.sendStickyBroadcast(intent);
548 }
549
550 private void enforceAccessPermission() {
551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
552 "WifiService");
553 }
554
555 private void enforceChangePermission() {
556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
557 "WifiService");
558
559 }
560
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700561 private void enforceMulticastChangePermission() {
562 mContext.enforceCallingOrSelfPermission(
563 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
564 "WifiService");
565 }
566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 /**
568 * see {@link WifiManager#getWifiState()}
569 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
570 * {@link WifiManager#WIFI_STATE_DISABLING},
571 * {@link WifiManager#WIFI_STATE_ENABLED},
572 * {@link WifiManager#WIFI_STATE_ENABLING},
573 * {@link WifiManager#WIFI_STATE_UNKNOWN}
574 */
575 public int getWifiEnabledState() {
576 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800577 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579
580 /**
581 * see {@link android.net.wifi.WifiManager#disconnect()}
582 * @return {@code true} if the operation succeeds
583 */
584 public boolean disconnect() {
585 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800586
587 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
589
590 /**
591 * see {@link android.net.wifi.WifiManager#reconnect()}
592 * @return {@code true} if the operation succeeds
593 */
594 public boolean reconnect() {
595 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800596
597 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599
600 /**
601 * see {@link android.net.wifi.WifiManager#reassociate()}
602 * @return {@code true} if the operation succeeds
603 */
604 public boolean reassociate() {
605 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800606
607 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
609
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800610 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700611 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800612 * @param wifiConfig SSID, security and channel details as
613 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700614 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800615 * @return {@code true} if the start operation was
616 * started or is already in the queue.
617 */
618 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
619 enforceChangePermission();
620 if (mWifiHandler == null) return false;
621
622 synchronized (mWifiHandler) {
623
624 long ident = Binder.clearCallingIdentity();
625 sWakeLock.acquire();
626 Binder.restoreCallingIdentity(ident);
627
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700628 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800629 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
630 }
631
632 return true;
633 }
634
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800635 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700636 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800637 final ContentResolver cr = mContext.getContentResolver();
638 WifiConfiguration wifiConfig = new WifiConfiguration();
639 int authType;
640 try {
641 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
642 if (wifiConfig.SSID == null)
643 return null;
644 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
645 wifiConfig.allowedKeyManagement.set(authType);
646 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
647 return wifiConfig;
648 } catch (Settings.SettingNotFoundException e) {
649 Slog.e(TAG,"AP settings not found, returning");
650 return null;
651 }
652 }
653
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700654 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
655 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800656 final ContentResolver cr = mContext.getContentResolver();
657 boolean isWpa;
658 if (wifiConfig == null)
659 return;
660 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
661 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
662 Settings.Secure.putInt(cr,
663 Settings.Secure.WIFI_AP_SECURITY,
664 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
665 if (isWpa)
666 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
667 }
668
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800669 /**
670 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
671 * and soft access point configured as a single operation.
672 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800673 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800674 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800675 * @return {@code true} if the operation succeeds (or if the existing state
676 * is the same as the requested state)
677 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800678 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800679 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800680 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
681
682 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800683 /* Configuration changed on a running access point */
684 if(enable && (wifiConfig != null)) {
685 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700686 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
687 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700688 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800689 return true;
690 } catch(Exception e) {
691 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700692 try {
693 nwService.stopAccessPoint();
694 } catch (Exception ee) {
695 Slog.e(TAG, "Could not stop AP, :" + ee);
696 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800697 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
698 return false;
699 }
700 } else {
701 return true;
702 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800703 }
704
Irfan Sherifff91444c2010-03-24 12:11:00 -0700705 /**
706 * Fail AP if Wifi is enabled
707 */
708 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
709 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
710 return false;
711 }
712
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800713 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
714 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800715
716 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800717
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800718 /* Use default config if there is no existing config */
719 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
720 wifiConfig = new WifiConfiguration();
721 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
722 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
723 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800724
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800725 if (!mWifiStateTracker.loadDriver()) {
726 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800727 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800728 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800729 }
730
731 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700732 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
733 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800734 } catch(Exception e) {
735 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800736 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
737 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800738 }
739
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700740 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700741
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 } else {
743
744 try {
745 nwService.stopAccessPoint();
746 } catch(Exception e) {
747 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800748 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
749 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800750 }
751
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800752 if (!mWifiStateTracker.unloadDriver()) {
753 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800754 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800755 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800756 }
757 }
758
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800759 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800760 return true;
761 }
762
763 /**
764 * see {@link WifiManager#getWifiApState()}
765 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
766 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
767 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
768 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
769 * {@link WifiManager#WIFI_AP_STATE_FAILED}
770 */
771 public int getWifiApEnabledState() {
772 enforceAccessPermission();
773 return mWifiApState;
774 }
775
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800776 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800777 final int previousWifiApState = mWifiApState;
778
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800779 /**
780 * Unload the driver if going to a failed state
781 */
782 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
783 mWifiStateTracker.unloadDriver();
784 }
785
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800786 long ident = Binder.clearCallingIdentity();
787 try {
788 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
789 mBatteryStats.noteWifiOn(uid);
790 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
791 mBatteryStats.noteWifiOff(uid);
792 }
793 } catch (RemoteException e) {
794 } finally {
795 Binder.restoreCallingIdentity(ident);
796 }
797
798 // Update state
799 mWifiApState = wifiAPState;
800
801 // Broadcast
802 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
803 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
804 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
805 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
806 mContext.sendStickyBroadcast(intent);
807 }
808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 /**
810 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
811 * @return the list of configured networks
812 */
813 public List<WifiConfiguration> getConfiguredNetworks() {
814 enforceAccessPermission();
815 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /*
818 * We don't cache the list, because we want to allow
819 * for the possibility that the configuration file
820 * has been modified through some external means,
821 * such as the wpa_cli command line program.
822 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800823 listStr = mWifiStateTracker.listNetworks();
824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 List<WifiConfiguration> networks =
826 new ArrayList<WifiConfiguration>();
827 if (listStr == null)
828 return networks;
829
830 String[] lines = listStr.split("\n");
831 // Skip the first line, which is a header
832 for (int i = 1; i < lines.length; i++) {
833 String[] result = lines[i].split("\t");
834 // network-id | ssid | bssid | flags
835 WifiConfiguration config = new WifiConfiguration();
836 try {
837 config.networkId = Integer.parseInt(result[0]);
838 } catch(NumberFormatException e) {
839 continue;
840 }
841 if (result.length > 3) {
842 if (result[3].indexOf("[CURRENT]") != -1)
843 config.status = WifiConfiguration.Status.CURRENT;
844 else if (result[3].indexOf("[DISABLED]") != -1)
845 config.status = WifiConfiguration.Status.DISABLED;
846 else
847 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800848 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800851 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 networks.add(config);
853 }
854
855 return networks;
856 }
857
858 /**
859 * Read the variables from the supplicant daemon that are needed to
860 * fill in the WifiConfiguration object.
861 * <p/>
862 * The caller must hold the synchronization monitor.
863 * @param config the {@link WifiConfiguration} object to be filled in.
864 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800865 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866
867 int netId = config.networkId;
868 if (netId < 0)
869 return;
870
871 /*
872 * TODO: maybe should have a native method that takes an array of
873 * variable names and returns an array of values. But we'd still
874 * be doing a round trip to the supplicant daemon for each variable.
875 */
876 String value;
877
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800878 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800880 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } else {
882 config.SSID = null;
883 }
884
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800885 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 if (!TextUtils.isEmpty(value)) {
887 config.BSSID = value;
888 } else {
889 config.BSSID = null;
890 }
891
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800892 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 config.priority = -1;
894 if (!TextUtils.isEmpty(value)) {
895 try {
896 config.priority = Integer.parseInt(value);
897 } catch (NumberFormatException ignore) {
898 }
899 }
900
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800901 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 config.hiddenSSID = false;
903 if (!TextUtils.isEmpty(value)) {
904 try {
905 config.hiddenSSID = Integer.parseInt(value) != 0;
906 } catch (NumberFormatException ignore) {
907 }
908 }
909
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800910 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 config.wepTxKeyIndex = -1;
912 if (!TextUtils.isEmpty(value)) {
913 try {
914 config.wepTxKeyIndex = Integer.parseInt(value);
915 } catch (NumberFormatException ignore) {
916 }
917 }
918
919 /*
920 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
921 * just a "*" if the key is set, or the null string otherwise.
922 */
923 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800924 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 if (!TextUtils.isEmpty(value)) {
926 config.wepKeys[i] = value;
927 } else {
928 config.wepKeys[i] = null;
929 }
930 }
931
932 /*
933 * Get the private shared key. Note that the actual keys are not passed back,
934 * just a "*" if the key is set, or the null string otherwise.
935 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800936 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (!TextUtils.isEmpty(value)) {
938 config.preSharedKey = value;
939 } else {
940 config.preSharedKey = null;
941 }
942
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800943 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 WifiConfiguration.Protocol.varName);
945 if (!TextUtils.isEmpty(value)) {
946 String vals[] = value.split(" ");
947 for (String val : vals) {
948 int index =
949 lookupString(val, WifiConfiguration.Protocol.strings);
950 if (0 <= index) {
951 config.allowedProtocols.set(index);
952 }
953 }
954 }
955
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800956 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 WifiConfiguration.KeyMgmt.varName);
958 if (!TextUtils.isEmpty(value)) {
959 String vals[] = value.split(" ");
960 for (String val : vals) {
961 int index =
962 lookupString(val, WifiConfiguration.KeyMgmt.strings);
963 if (0 <= index) {
964 config.allowedKeyManagement.set(index);
965 }
966 }
967 }
968
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800969 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 WifiConfiguration.AuthAlgorithm.varName);
971 if (!TextUtils.isEmpty(value)) {
972 String vals[] = value.split(" ");
973 for (String val : vals) {
974 int index =
975 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
976 if (0 <= index) {
977 config.allowedAuthAlgorithms.set(index);
978 }
979 }
980 }
981
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800982 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 WifiConfiguration.PairwiseCipher.varName);
984 if (!TextUtils.isEmpty(value)) {
985 String vals[] = value.split(" ");
986 for (String val : vals) {
987 int index =
988 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
989 if (0 <= index) {
990 config.allowedPairwiseCiphers.set(index);
991 }
992 }
993 }
994
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800995 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 WifiConfiguration.GroupCipher.varName);
997 if (!TextUtils.isEmpty(value)) {
998 String vals[] = value.split(" ");
999 for (String val : vals) {
1000 int index =
1001 lookupString(val, WifiConfiguration.GroupCipher.strings);
1002 if (0 <= index) {
1003 config.allowedGroupCiphers.set(index);
1004 }
1005 }
1006 }
Chung-yih Wang43374762009-09-16 14:28:42 +08001007
1008 for (WifiConfiguration.EnterpriseField field :
1009 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001010 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +08001011 field.varName());
1012 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001013 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001014 field.setValue(value);
1015 }
1016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001019 private static String removeDoubleQuotes(String string) {
1020 if (string.length() <= 2) return "";
1021 return string.substring(1, string.length() - 1);
1022 }
1023
1024 private static String convertToQuotedString(String string) {
1025 return "\"" + string + "\"";
1026 }
1027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 /**
1029 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1030 * @return the supplicant-assigned identifier for the new or updated
1031 * network if the operation succeeds, or {@code -1} if it fails
1032 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001033 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /*
1037 * If the supplied networkId is -1, we create a new empty
1038 * network configuration. Otherwise, the networkId should
1039 * refer to an existing configuration.
1040 */
1041 int netId = config.networkId;
1042 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001043 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001045 synchronized (mWifiStateTracker) {
1046 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001047 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001048 if (netId < 0) {
1049 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001050 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001051 }
1052 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001054 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001056 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001059 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /*
1061 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001062 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * will fail, so we don't bother to make a separate check
1064 * for the validity of the ID up front.
1065 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001067 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001068 netId,
1069 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001070 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001072 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 break setVariables;
1075 }
1076
1077 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001078 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001079 netId,
1080 WifiConfiguration.bssidVarName,
1081 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001083 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 break setVariables;
1086 }
1087
1088 String allowedKeyManagementString =
1089 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1090 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001091 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001092 netId,
1093 WifiConfiguration.KeyMgmt.varName,
1094 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001096 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001097 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099 break setVariables;
1100 }
1101
1102 String allowedProtocolsString =
1103 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1104 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001105 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001106 netId,
1107 WifiConfiguration.Protocol.varName,
1108 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001110 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001111 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 break setVariables;
1114 }
1115
1116 String allowedAuthAlgorithmsString =
1117 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1118 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001119 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001120 netId,
1121 WifiConfiguration.AuthAlgorithm.varName,
1122 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001124 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001125 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 break setVariables;
1128 }
1129
1130 String allowedPairwiseCiphersString =
1131 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1132 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001133 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001134 netId,
1135 WifiConfiguration.PairwiseCipher.varName,
1136 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001138 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001139 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141 break setVariables;
1142 }
1143
1144 String allowedGroupCiphersString =
1145 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1146 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001147 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001148 netId,
1149 WifiConfiguration.GroupCipher.varName,
1150 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001152 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001153 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 break setVariables;
1156 }
1157
1158 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1159 // by preventing "*" as a key.
1160 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001161 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001162 netId,
1163 WifiConfiguration.pskVarName,
1164 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168 break setVariables;
1169 }
1170
1171 boolean hasSetKey = false;
1172 if (config.wepKeys != null) {
1173 for (int i = 0; i < config.wepKeys.length; i++) {
1174 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1175 // by preventing "*" as a key.
1176 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001177 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001178 netId,
1179 WifiConfiguration.wepKeyVarNames[i],
1180 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001182 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001183 "failed to set wep_key"+i+": " +
1184 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186 break setVariables;
1187 }
1188 hasSetKey = true;
1189 }
1190 }
1191 }
1192
1193 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001194 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001195 netId,
1196 WifiConfiguration.wepTxKeyIdxVarName,
1197 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001199 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001200 "failed to set wep_tx_keyidx: "+
1201 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203 break setVariables;
1204 }
1205 }
1206
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001207 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001208 netId,
1209 WifiConfiguration.priorityVarName,
1210 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001212 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001213 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215 break setVariables;
1216 }
1217
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001218 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001219 netId,
1220 WifiConfiguration.hiddenSSIDVarName,
1221 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001223 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001224 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 break setVariables;
1227 }
1228
Chung-yih Wang43374762009-09-16 14:28:42 +08001229 for (WifiConfiguration.EnterpriseField field
1230 : config.enterpriseFields) {
1231 String varName = field.varName();
1232 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001233 if (value != null) {
1234 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001235 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001236 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001237 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001238 netId,
1239 varName,
1240 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001241 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001242 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001243 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001244 }
1245 break setVariables;
1246 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001247 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001252 /*
1253 * For an update, if one of the setNetworkVariable operations fails,
1254 * we might want to roll back all the changes already made. But the
1255 * chances are that if anything is going to go wrong, it'll happen
1256 * the first time we try to set one of the variables.
1257 */
1258 if (newNetwork) {
1259 removeNetwork(netId);
1260 if (DBG) {
1261 Slog.d(TAG,
1262 "Failed to set a network variable, removed network: "
1263 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265 }
1266 return -1;
1267 }
1268
1269 private static String makeString(BitSet set, String[] strings) {
1270 StringBuffer buf = new StringBuffer();
1271 int nextSetBit = -1;
1272
1273 /* Make sure all set bits are in [0, strings.length) to avoid
1274 * going out of bounds on strings. (Shouldn't happen, but...) */
1275 set = set.get(0, strings.length);
1276
1277 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1278 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1279 }
1280
1281 // remove trailing space
1282 if (set.cardinality() > 0) {
1283 buf.setLength(buf.length() - 1);
1284 }
1285
1286 return buf.toString();
1287 }
1288
1289 private static int lookupString(String string, String[] strings) {
1290 int size = strings.length;
1291
1292 string = string.replace('-', '_');
1293
1294 for (int i = 0; i < size; i++)
1295 if (string.equals(strings[i]))
1296 return i;
1297
1298 if (DBG) {
1299 // if we ever get here, we should probably add the
1300 // value to WifiConfiguration to reflect that it's
1301 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001302 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304
1305 return -1;
1306 }
1307
1308 /**
1309 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1310 * @param netId the integer that identifies the network configuration
1311 * to the supplicant
1312 * @return {@code true} if the operation succeeded
1313 */
1314 public boolean removeNetwork(int netId) {
1315 enforceChangePermission();
1316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 return mWifiStateTracker.removeNetwork(netId);
1318 }
1319
1320 /**
1321 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1322 * @param netId the integer that identifies the network configuration
1323 * to the supplicant
1324 * @param disableOthers if true, disable all other networks.
1325 * @return {@code true} if the operation succeeded
1326 */
1327 public boolean enableNetwork(int netId, boolean disableOthers) {
1328 enforceChangePermission();
1329
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001330 String ifname = mWifiStateTracker.getInterfaceName();
1331 NetworkUtils.enableInterface(ifname);
1332 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1333 if (!result) {
1334 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001336 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
1339 /**
1340 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1341 * @param netId the integer that identifies the network configuration
1342 * to the supplicant
1343 * @return {@code true} if the operation succeeded
1344 */
1345 public boolean disableNetwork(int netId) {
1346 enforceChangePermission();
1347
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001348 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350
1351 /**
1352 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1353 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1354 */
1355 public WifiInfo getConnectionInfo() {
1356 enforceAccessPermission();
1357 /*
1358 * Make sure we have the latest information, by sending
1359 * a status request to the supplicant.
1360 */
1361 return mWifiStateTracker.requestConnectionInfo();
1362 }
1363
1364 /**
1365 * Return the results of the most recent access point scan, in the form of
1366 * a list of {@link ScanResult} objects.
1367 * @return the list of results
1368 */
1369 public List<ScanResult> getScanResults() {
1370 enforceAccessPermission();
1371 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001372
1373 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (reply == null) {
1375 return null;
1376 }
1377
1378 List<ScanResult> scanList = new ArrayList<ScanResult>();
1379
1380 int lineCount = 0;
1381
1382 int replyLen = reply.length();
1383 // Parse the result string, keeping in mind that the last line does
1384 // not end with a newline.
1385 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1386 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1387 ++lineCount;
1388 /*
1389 * Skip the first line, which is a header
1390 */
1391 if (lineCount == 1) {
1392 lineBeg = lineEnd + 1;
1393 continue;
1394 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001395 if (lineEnd > lineBeg) {
1396 String line = reply.substring(lineBeg, lineEnd);
1397 ScanResult scanResult = parseScanResult(line);
1398 if (scanResult != null) {
1399 scanList.add(scanResult);
1400 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403 }
1404 lineBeg = lineEnd + 1;
1405 }
1406 }
1407 mWifiStateTracker.setScanResultsList(scanList);
1408 return scanList;
1409 }
1410
1411 /**
1412 * Parse the scan result line passed to us by wpa_supplicant (helper).
1413 * @param line the line to parse
1414 * @return the {@link ScanResult} object
1415 */
1416 private ScanResult parseScanResult(String line) {
1417 ScanResult scanResult = null;
1418 if (line != null) {
1419 /*
1420 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1421 * must synchronized here!
1422 */
1423 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001424 String[] result = scanResultPattern.split(line);
1425 if (3 <= result.length && result.length <= 5) {
1426 String bssid = result[0];
1427 // bssid | frequency | level | flags | ssid
1428 int frequency;
1429 int level;
1430 try {
1431 frequency = Integer.parseInt(result[1]);
1432 level = Integer.parseInt(result[2]);
1433 /* some implementations avoid negative values by adding 256
1434 * so we need to adjust for that here.
1435 */
1436 if (level > 0) level -= 256;
1437 } catch (NumberFormatException e) {
1438 frequency = 0;
1439 level = 0;
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441
Mike Lockwood1a645052009-06-25 13:01:12 -04001442 /*
1443 * The formatting of the results returned by
1444 * wpa_supplicant is intended to make the fields
1445 * line up nicely when printed,
1446 * not to make them easy to parse. So we have to
1447 * apply some heuristics to figure out which field
1448 * is the SSID and which field is the flags.
1449 */
1450 String ssid;
1451 String flags;
1452 if (result.length == 4) {
1453 if (result[3].charAt(0) == '[') {
1454 flags = result[3];
1455 ssid = "";
1456 } else {
1457 flags = "";
1458 ssid = result[3];
1459 }
1460 } else if (result.length == 5) {
1461 flags = result[3];
1462 ssid = result[4];
1463 } else {
1464 // Here, we must have 3 fields: no flags and ssid
1465 // set
1466 flags = "";
1467 ssid = "";
1468 }
1469
Mike Lockwood00717e22009-08-17 10:09:36 -04001470 // bssid + ssid is the hash key
1471 String key = bssid + ssid;
1472 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001473 if (scanResult != null) {
1474 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001475 scanResult.SSID = ssid;
1476 scanResult.capabilities = flags;
1477 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001478 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 // Do not add scan results that have no SSID set
1480 if (0 < ssid.trim().length()) {
1481 scanResult =
1482 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001483 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001484 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001487 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001489 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491 }
1492 }
1493
1494 return scanResult;
1495 }
1496
1497 /**
1498 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1499 * and construct a {@code WifiConfiguration} that describes the encryption,
1500 * key management, and authenticaion capabilities of the access point.
1501 * @param flags the string returned by wpa_supplicant
1502 * @return the {@link WifiConfiguration} object, filled in
1503 */
1504 WifiConfiguration parseScanFlags(String flags) {
1505 WifiConfiguration config = new WifiConfiguration();
1506
1507 if (flags.length() == 0) {
1508 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1509 }
1510 // ... to be implemented
1511 return config;
1512 }
1513
1514 /**
1515 * Tell the supplicant to persist the current list of configured networks.
1516 * @return {@code true} if the operation succeeded
1517 */
1518 public boolean saveConfiguration() {
1519 boolean result;
1520 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001523 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 if (result && mNeedReconfig) {
1525 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001526 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527
1528 if (result) {
1529 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1530 mContext.sendBroadcast(intent);
1531 }
1532 }
1533 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001534 // Inform the backup manager about a data change
1535 IBackupManager ibm = IBackupManager.Stub.asInterface(
1536 ServiceManager.getService(Context.BACKUP_SERVICE));
1537 if (ibm != null) {
1538 try {
1539 ibm.dataChanged("com.android.providers.settings");
1540 } catch (Exception e) {
1541 // Try again later
1542 }
1543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 return result;
1545 }
1546
1547 /**
1548 * Set the number of radio frequency channels that are allowed to be used
1549 * in the current regulatory domain. This method should be used only
1550 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001551 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 * persisted as a Secure setting.
1553 * @param numChannels the number of allowed channels. Must be greater than 0
1554 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001555 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1557 * {@code numChannels} is outside the valid range.
1558 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001559 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001561 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 /*
1565 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1566 * but if Wi-Fi isn't currently enabled, that's not possible, and
1567 * we want to persist the setting anyway,so that it will take
1568 * effect when Wi-Fi does become enabled.
1569 */
1570 boolean found = false;
1571 for (int validChan : sValidRegulatoryChannelCounts) {
1572 if (validChan == numChannels) {
1573 found = true;
1574 break;
1575 }
1576 }
1577 if (!found) {
1578 return false;
1579 }
1580
Irfan Sheriff59610c02010-03-30 11:00:41 -07001581 if (mWifiHandler == null) return false;
1582
1583 Message.obtain(mWifiHandler,
1584 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1585
1586 return true;
1587 }
1588
1589 /**
1590 * sets the number of allowed radio frequency channels synchronously
1591 * @param numChannels the number of allowed channels. Must be greater than 0
1592 * and less than or equal to 16.
1593 * @param persist {@code true} if the setting should be remembered.
1594 * @return {@code true} if the operation succeeds, {@code false} otherwise
1595 */
1596 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001597 if (persist) {
1598 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001599 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1600 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001601 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001602 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
1605 /**
1606 * Return the number of frequency channels that are allowed
1607 * to be used in the current regulatory domain.
1608 * @return the number of allowed channels, or {@code -1} if an error occurs
1609 */
1610 public int getNumAllowedChannels() {
1611 int numChannels;
1612
1613 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001614
1615 /*
1616 * If we can't get the value from the driver (e.g., because
1617 * Wi-Fi is not currently enabled), get the value from
1618 * Settings.
1619 */
1620 numChannels = mWifiStateTracker.getNumAllowedChannels();
1621 if (numChannels < 0) {
1622 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1623 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1624 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
1626 return numChannels;
1627 }
1628
1629 /**
1630 * Return the list of valid values for the number of allowed radio channels
1631 * for various regulatory domains.
1632 * @return the list of channel counts
1633 */
1634 public int[] getValidChannelCounts() {
1635 enforceAccessPermission();
1636 return sValidRegulatoryChannelCounts;
1637 }
1638
1639 /**
1640 * Return the DHCP-assigned addresses from the last successful DHCP request,
1641 * if any.
1642 * @return the DHCP information
1643 */
1644 public DhcpInfo getDhcpInfo() {
1645 enforceAccessPermission();
1646 return mWifiStateTracker.getDhcpInfo();
1647 }
1648
1649 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1650 @Override
1651 public void onReceive(Context context, Intent intent) {
1652 String action = intent.getAction();
1653
Doug Zongker43866e02010-01-07 12:09:54 -08001654 long idleMillis =
1655 Settings.Secure.getLong(mContext.getContentResolver(),
1656 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001658 Settings.System.getInt(mContext.getContentResolver(),
1659 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 mAlarmManager.cancel(mIdleIntent);
1663 mDeviceIdle = false;
1664 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001665 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001667 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001669 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 /*
1671 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1672 * AND the "stay on while plugged in" setting doesn't match the
1673 * current power conditions (i.e, not plugged in, plugged in to USB,
1674 * or plugged in to AC).
1675 */
1676 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001677 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1678 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001679 // we used to go to sleep immediately, but this caused some race conditions
1680 // we don't have time to track down for this release. Delay instead, but not
1681 // as long as we would if connected (below)
1682 // TODO - fix the race conditions and switch back to the immediate turn-off
1683 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001685 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1686 // // do not keep Wifi awake when screen is off if Wifi is not associated
1687 // mDeviceIdle = true;
1688 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001689 } else {
1690 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001691 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001692 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 /* we can return now -- there's nothing to do until we get the idle intent back */
1696 return;
1697 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001698 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 mDeviceIdle = true;
1700 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1701 /*
1702 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1703 * AND we are transitioning from a state in which the device was supposed
1704 * to stay awake to a state in which it is not supposed to stay awake.
1705 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1706 * the already-set timer.
1707 */
1708 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001709 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1711 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1712 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001713 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1715 mPluggedType = pluggedType;
1716 return;
1717 }
1718 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001719 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001720 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1721 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1722 boolean isBluetoothPlaying = false;
1723 for (BluetoothDevice sink : sinks) {
1724 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1725 isBluetoothPlaying = true;
1726 }
1727 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001728 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 } else {
1731 return;
1732 }
1733
1734 updateWifiState();
1735 }
1736
1737 /**
1738 * Determines whether the Wi-Fi chipset should stay awake or be put to
1739 * sleep. Looks at the setting for the sleep policy and the current
1740 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001741 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 * @see #shouldDeviceStayAwake(int, int)
1743 */
1744 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1745 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1746 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1747
1748 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1749 // Never sleep
1750 return true;
1751 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1752 (pluggedType != 0)) {
1753 // Never sleep while plugged, and we're plugged
1754 return true;
1755 } else {
1756 // Default
1757 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1758 }
1759 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 /**
1762 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1763 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1764 * of {@code 0} isn't really a plugged type, but rather an indication that the
1765 * device isn't plugged in at all, there is no bit value corresponding to a
1766 * {@code pluggedType} value of {@code 0}. That is why we shift by
1767 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1768 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1769 * keep the device (and hence Wi-Fi) awake.
1770 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1771 * being made
1772 * @return {@code true} if {@code pluggedType} indicates that the device is
1773 * supposed to stay awake, {@code false} otherwise.
1774 */
1775 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1776 return (stayAwakeConditions & pluggedType) != 0;
1777 }
1778 };
1779
Dianne Hackborn617f8772009-03-31 15:04:46 -07001780 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 Message msg = Message.obtain(mWifiHandler,
1782 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001783 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 msg.sendToTarget();
1785 }
1786
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001787 private void sendStartMessage(int lockMode) {
1788 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, lockMode, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001791 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1792 Message.obtain(mWifiHandler,
1793 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001794 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001795 }
1796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001798 // send a message so it's all serialized
1799 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1800 }
1801
1802 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001804 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001806 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1808 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001809
1810 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001812 }
1813 /* If device is not idle, lockmode cannot be scan only */
1814 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1816 }
1817
1818 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001819 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 return;
1821 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001822
1823 /* Disable tethering when airplane mode is enabled */
1824 if (airplaneMode &&
1825 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1826 sWakeLock.acquire();
1827 sendAccessPointMessage(false, null, mLastApEnableUid);
1828 }
1829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 if (wifiShouldBeEnabled) {
1831 if (wifiShouldBeStarted) {
1832 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001833 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 sWakeLock.acquire();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001835 sendStartMessage(strongestLockMode);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001836 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 int wakeLockTimeout =
1838 Settings.Secure.getInt(
1839 mContext.getContentResolver(),
1840 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1841 DEFAULT_WAKELOCK_TIMEOUT);
1842 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001843 * We are assuming that ConnectivityService can make
1844 * a transition to cellular data within wakeLockTimeout time.
1845 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 */
1847 sDriverStopWakeLock.acquire();
1848 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1849 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1850 }
1851 } else {
1852 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001853 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
1855 }
1856 }
1857
1858 private void registerForBroadcasts() {
1859 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1861 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1862 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1863 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001864 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mContext.registerReceiver(mReceiver, intentFilter);
1866 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 private boolean isAirplaneSensitive() {
1869 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1870 Settings.System.AIRPLANE_MODE_RADIOS);
1871 return airplaneModeRadios == null
1872 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1873 }
1874
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001875 private boolean isAirplaneToggleable() {
1876 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1877 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1878 return toggleableRadios != null
1879 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1880 }
1881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 /**
1883 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1884 * currently on.
1885 * @return {@code true} if airplane mode is on.
1886 */
1887 private boolean isAirplaneModeOn() {
1888 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1889 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1890 }
1891
1892 /**
1893 * Handler that allows posting to the WifiThread.
1894 */
1895 private class WifiHandler extends Handler {
1896 public WifiHandler(Looper looper) {
1897 super(looper);
1898 }
1899
1900 @Override
1901 public void handleMessage(Message msg) {
1902 switch (msg.what) {
1903
1904 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001905 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001906 if (mWifiWatchdogService == null) {
1907 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 sWakeLock.release();
1910 break;
1911
1912 case MESSAGE_START_WIFI:
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001913 mWifiStateTracker.setScanOnlyMode(msg.arg1 == WifiManager.WIFI_MODE_SCAN_ONLY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 mWifiStateTracker.restart();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001915 mWifiStateTracker.setHighPerfMode(msg.arg1 ==
1916 WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 sWakeLock.release();
1918 break;
1919
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001920 case MESSAGE_UPDATE_STATE:
1921 doUpdateWifiState();
1922 break;
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 case MESSAGE_DISABLE_WIFI:
1925 // a non-zero msg.arg1 value means the "enabled" setting
1926 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001927 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001928 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 sWakeLock.release();
1930 break;
1931
1932 case MESSAGE_STOP_WIFI:
1933 mWifiStateTracker.disconnectAndStop();
1934 // don't release wakelock
1935 break;
1936
1937 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001938 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001940
1941 case MESSAGE_START_ACCESS_POINT:
1942 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001943 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001944 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001945 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001946 break;
1947
1948 case MESSAGE_STOP_ACCESS_POINT:
1949 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001950 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001951 (WifiConfiguration) msg.obj);
1952 sWakeLock.release();
1953 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001954
1955 case MESSAGE_SET_CHANNELS:
1956 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1957 break;
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
1960 }
1961 }
1962
1963 @Override
1964 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1965 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1966 != PackageManager.PERMISSION_GRANTED) {
1967 pw.println("Permission Denial: can't dump WifiService from from pid="
1968 + Binder.getCallingPid()
1969 + ", uid=" + Binder.getCallingUid());
1970 return;
1971 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001972 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 pw.println("Stay-awake conditions: " +
1974 Settings.System.getInt(mContext.getContentResolver(),
1975 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1976 pw.println();
1977
1978 pw.println("Internal state:");
1979 pw.println(mWifiStateTracker);
1980 pw.println();
1981 pw.println("Latest scan results:");
1982 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1983 if (scanResults != null && scanResults.size() != 0) {
1984 pw.println(" BSSID Frequency RSSI Flags SSID");
1985 for (ScanResult r : scanResults) {
1986 pw.printf(" %17s %9d %5d %-16s %s%n",
1987 r.BSSID,
1988 r.frequency,
1989 r.level,
1990 r.capabilities,
1991 r.SSID == null ? "" : r.SSID);
1992 }
1993 }
1994 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001995 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001996 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001997 mScanLocksAcquired + " scan");
1998 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001999 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002000 mScanLocksReleased + " scan");
2001 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 pw.println("Locks held:");
2003 mLocks.dump(pw);
2004 }
2005
2006 private static String stateName(int wifiState) {
2007 switch (wifiState) {
2008 case WIFI_STATE_DISABLING:
2009 return "disabling";
2010 case WIFI_STATE_DISABLED:
2011 return "disabled";
2012 case WIFI_STATE_ENABLING:
2013 return "enabling";
2014 case WIFI_STATE_ENABLED:
2015 return "enabled";
2016 case WIFI_STATE_UNKNOWN:
2017 return "unknown state";
2018 default:
2019 return "[invalid state]";
2020 }
2021 }
2022
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002023 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002025 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
2028 public void binderDied() {
2029 synchronized (mLocks) {
2030 releaseWifiLockLocked(mBinder);
2031 }
2032 }
2033
2034 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002035 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 }
2038
2039 private class LockList {
2040 private List<WifiLock> mList;
2041
2042 private LockList() {
2043 mList = new ArrayList<WifiLock>();
2044 }
2045
2046 private synchronized boolean hasLocks() {
2047 return !mList.isEmpty();
2048 }
2049
2050 private synchronized int getStrongestLockMode() {
2051 if (mList.isEmpty()) {
2052 return WifiManager.WIFI_MODE_FULL;
2053 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002054
2055 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
2056 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002058
2059 if (mFullLocksAcquired > mFullLocksReleased) {
2060 return WifiManager.WIFI_MODE_FULL;
2061 }
2062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 return WifiManager.WIFI_MODE_SCAN_ONLY;
2064 }
2065
2066 private void addLock(WifiLock lock) {
2067 if (findLockByBinder(lock.mBinder) < 0) {
2068 mList.add(lock);
2069 }
2070 }
2071
2072 private WifiLock removeLock(IBinder binder) {
2073 int index = findLockByBinder(binder);
2074 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002075 WifiLock ret = mList.remove(index);
2076 ret.unlinkDeathRecipient();
2077 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 } else {
2079 return null;
2080 }
2081 }
2082
2083 private int findLockByBinder(IBinder binder) {
2084 int size = mList.size();
2085 for (int i = size - 1; i >= 0; i--)
2086 if (mList.get(i).mBinder == binder)
2087 return i;
2088 return -1;
2089 }
2090
2091 private void dump(PrintWriter pw) {
2092 for (WifiLock l : mList) {
2093 pw.print(" ");
2094 pw.println(l);
2095 }
2096 }
2097 }
2098
2099 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002101 if (lockMode != WifiManager.WIFI_MODE_FULL &&
2102 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
2103 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
2104 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
2105 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 return false;
2107 }
2108 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2109 synchronized (mLocks) {
2110 return acquireWifiLockLocked(wifiLock);
2111 }
2112 }
2113
2114 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002115 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002118
The Android Open Source Project10592532009-03-18 17:39:46 -07002119 int uid = Binder.getCallingUid();
2120 long ident = Binder.clearCallingIdentity();
2121 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002122 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002123 case WifiManager.WIFI_MODE_FULL:
2124 ++mFullLocksAcquired;
2125 mBatteryStats.noteFullWifiLockAcquired(uid);
2126 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002127 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2128 ++mFullHighPerfLocksAcquired;
2129 /* Treat high power as a full lock for battery stats */
2130 mBatteryStats.noteFullWifiLockAcquired(uid);
2131 break;
2132
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002133 case WifiManager.WIFI_MODE_SCAN_ONLY:
2134 ++mScanLocksAcquired;
2135 mBatteryStats.noteScanWifiLockAcquired(uid);
2136 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002137 }
2138 } catch (RemoteException e) {
2139 } finally {
2140 Binder.restoreCallingIdentity(ident);
2141 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 updateWifiState();
2144 return true;
2145 }
2146
2147 public boolean releaseWifiLock(IBinder lock) {
2148 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2149 synchronized (mLocks) {
2150 return releaseWifiLockLocked(lock);
2151 }
2152 }
2153
2154 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002155 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002156
The Android Open Source Project10592532009-03-18 17:39:46 -07002157 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002158
Joe Onorato8a9b2202010-02-26 18:56:32 -08002159 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002160
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002161 hadLock = (wifiLock != null);
2162
2163 if (hadLock) {
2164 int uid = Binder.getCallingUid();
2165 long ident = Binder.clearCallingIdentity();
2166 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002167 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002168 case WifiManager.WIFI_MODE_FULL:
2169 ++mFullLocksReleased;
2170 mBatteryStats.noteFullWifiLockReleased(uid);
2171 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002172 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2173 ++mFullHighPerfLocksReleased;
2174 mBatteryStats.noteFullWifiLockReleased(uid);
2175 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002176 case WifiManager.WIFI_MODE_SCAN_ONLY:
2177 ++mScanLocksReleased;
2178 mBatteryStats.noteScanWifiLockReleased(uid);
2179 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002180 }
2181 } catch (RemoteException e) {
2182 } finally {
2183 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002184 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002185 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002186 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002188 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002190
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002191 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002192 implements IBinder.DeathRecipient {
2193 String mTag;
2194 int mMode;
2195 IBinder mBinder;
2196
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002197 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002198 super();
2199 mTag = tag;
2200 mMode = mode;
2201 mBinder = binder;
2202 try {
2203 mBinder.linkToDeath(this, 0);
2204 } catch (RemoteException e) {
2205 binderDied();
2206 }
2207 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002208
2209 void unlinkDeathRecipient() {
2210 mBinder.unlinkToDeath(this, 0);
2211 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002212 }
2213
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002214 private class Multicaster extends DeathRecipient {
2215 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002216 super(Binder.getCallingUid(), tag, binder);
2217 }
2218
2219 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002220 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002221 synchronized (mMulticasters) {
2222 int i = mMulticasters.indexOf(this);
2223 if (i != -1) {
2224 removeMulticasterLocked(i, mMode);
2225 }
2226 }
2227 }
2228
2229 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002230 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002231 }
2232
2233 public int getUid() {
2234 return mMode;
2235 }
2236 }
2237
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002238 public void initializeMulticastFiltering() {
2239 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002240
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002241 synchronized (mMulticasters) {
2242 // if anybody had requested filters be off, leave off
2243 if (mMulticasters.size() != 0) {
2244 return;
2245 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002246 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002247 }
2248 }
2249 }
2250
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002251 public void acquireMulticastLock(IBinder binder, String tag) {
2252 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002253
2254 synchronized (mMulticasters) {
2255 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002256 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002257 // Note that we could call stopPacketFiltering only when
2258 // our new size == 1 (first call), but this function won't
2259 // be called often and by making the stopPacket call each
2260 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002261 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002262 }
2263
2264 int uid = Binder.getCallingUid();
2265 Long ident = Binder.clearCallingIdentity();
2266 try {
2267 mBatteryStats.noteWifiMulticastEnabled(uid);
2268 } catch (RemoteException e) {
2269 } finally {
2270 Binder.restoreCallingIdentity(ident);
2271 }
2272 }
2273
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002274 public void releaseMulticastLock() {
2275 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002276
2277 int uid = Binder.getCallingUid();
2278 synchronized (mMulticasters) {
2279 mMulticastDisabled++;
2280 int size = mMulticasters.size();
2281 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002282 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002283 if ((m != null) && (m.getUid() == uid)) {
2284 removeMulticasterLocked(i, uid);
2285 }
2286 }
2287 }
2288 }
2289
2290 private void removeMulticasterLocked(int i, int uid)
2291 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002292 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002293
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002294 if (removed != null) {
2295 removed.unlinkDeathRecipient();
2296 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002297 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002298 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002299 }
2300
2301 Long ident = Binder.clearCallingIdentity();
2302 try {
2303 mBatteryStats.noteWifiMulticastDisabled(uid);
2304 } catch (RemoteException e) {
2305 } finally {
2306 Binder.restoreCallingIdentity(ident);
2307 }
2308 }
2309
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002310 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002311 enforceAccessPermission();
2312
2313 synchronized (mMulticasters) {
2314 return (mMulticasters.size() > 0);
2315 }
2316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317}