blob: e4d762349ca4c4ce90f251cee0b5af39bddd39aa [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
119 private int mFullLocksAcquired;
120 private int mFullLocksReleased;
121 private int mScanLocksAcquired;
122 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700123
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700124 private final List<Multicaster> mMulticasters =
125 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700126 private int mMulticastEnabled;
127 private int mMulticastDisabled;
128
The Android Open Source Project10592532009-03-18 17:39:46 -0700129 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800130
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800131 private INetworkManagementService nwService;
132 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800133 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800134 private String[] mWifiRegexs;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800137 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
138 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 * the approximate point at which the battery drain caused by Wi-Fi
140 * being enabled but not active exceeds the battery drain caused by
141 * re-establishing a connection to the mobile data network.
142 */
143 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
144
145 private static final String WAKELOCK_TAG = "WifiService";
146
147 /**
148 * The maximum amount of time to hold the wake lock after a disconnect
149 * caused by stopping the driver. Establishing an EDGE connection has been
150 * observed to take about 5 seconds under normal circumstances. This
151 * provides a bit of extra margin.
152 * <p>
153 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
154 * This is the default value if a Settings.Secure value is not present.
155 */
156 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
157
158 // Wake lock used by driver-stop operation
159 private static PowerManager.WakeLock sDriverStopWakeLock;
160 // Wake lock used by other operations
161 private static PowerManager.WakeLock sWakeLock;
162
163 private static final int MESSAGE_ENABLE_WIFI = 0;
164 private static final int MESSAGE_DISABLE_WIFI = 1;
165 private static final int MESSAGE_STOP_WIFI = 2;
166 private static final int MESSAGE_START_WIFI = 3;
167 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -0700168 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800169 private static final int MESSAGE_START_ACCESS_POINT = 6;
170 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173 private final WifiHandler mWifiHandler;
174
175 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 * Cache of scan results objects (size is somewhat arbitrary)
177 */
178 private static final int SCAN_RESULT_CACHE_SIZE = 80;
179 private final LinkedHashMap<String, ScanResult> mScanResultCache;
180
181 /*
182 * Character buffer used to parse scan results (optimization)
183 */
184 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private boolean mNeedReconfig;
186
Dianne Hackborn617f8772009-03-31 15:04:46 -0700187 /*
188 * Last UID that asked to enable WIFI.
189 */
190 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 /**
193 * Number of allowed radio frequency channels in various regulatory domains.
194 * This list is sufficient for 802.11b/g networks (2.4GHz range).
195 */
196 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
197
198 private static final String ACTION_DEVICE_IDLE =
199 "com.android.server.WifiManager.action.DEVICE_IDLE";
200
201 WifiService(Context context, WifiStateTracker tracker) {
202 mContext = context;
203 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400204 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700205 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800206
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800207 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
208 nwService = INetworkManagementService.Stub.asInterface(b);
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 mScanResultCache = new LinkedHashMap<String, ScanResult>(
211 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
212 /*
213 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
214 * elements
215 */
216 public boolean removeEldestEntry(Map.Entry eldest) {
217 return SCAN_RESULT_CACHE_SIZE < this.size();
218 }
219 };
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 HandlerThread wifiThread = new HandlerThread("WifiService");
222 wifiThread.start();
223 mWifiHandler = new WifiHandler(wifiThread.getLooper());
224
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800225 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800226 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
228 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
229 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
230 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
231
232 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
233 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
234 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 mContext.registerReceiver(
237 new BroadcastReceiver() {
238 @Override
239 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700240 // clear our flag indicating the user has overwridden airplane mode
241 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 updateWifiState();
243 }
244 },
245 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
246
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800247 mContext.registerReceiver(
248 new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context, Intent intent) {
251
252 ArrayList<String> available = intent.getStringArrayListExtra(
253 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
254 ArrayList<String> active = intent.getStringArrayListExtra(
255 ConnectivityManager.EXTRA_ACTIVE_TETHER);
256 updateTetherState(available, active);
257
258 }
259 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800260 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800261
Irfan Sheriff7b009782010-03-11 16:37:45 -0800262 /**
263 * Check if Wi-Fi needs to be enabled and start
264 * if needed
265 */
266 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700267 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
268 boolean wifiEnabled = getPersistedWifiEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800269 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
270 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700271 setWifiEnabledBlocking(wifiEnabled, true, Process.myUid());
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800272 }
273
274 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
275
276 boolean wifiTethered = false;
277 boolean wifiAvailable = false;
278
279 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
280 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
281
282 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
283 mWifiRegexs = mCm.getTetherableWifiRegexs();
284
285 for (String intf : available) {
286 for (String regex : mWifiRegexs) {
287 if (intf.matches(regex)) {
288
289 InterfaceConfiguration ifcg = null;
290 try {
291 ifcg = service.getInterfaceConfig(intf);
292 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700293 /* IP/netmask: 192.168.43.1/255.255.255.0 */
294 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800295 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
296 ifcg.interfaceFlags = "up";
297
298 service.setInterfaceConfig(intf, ifcg);
299 }
300 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800301 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700302 try {
303 nwService.stopAccessPoint();
304 } catch (Exception ee) {
305 Slog.e(TAG, "Could not stop AP, :" + ee);
306 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800307 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800308 return;
309 }
310
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800311 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800312 Slog.e(TAG, "Error tethering "+intf);
313 }
314 break;
315 }
316 }
317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700320 private boolean testAndClearWifiSavedState() {
321 final ContentResolver cr = mContext.getContentResolver();
322 int wifiSavedState = 0;
323 try {
324 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
325 if(wifiSavedState == 1)
326 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
327 } catch (Settings.SettingNotFoundException e) {
328 ;
329 }
330 return (wifiSavedState == 1);
331 }
332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 private boolean getPersistedWifiEnabled() {
334 final ContentResolver cr = mContext.getContentResolver();
335 try {
336 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
337 } catch (Settings.SettingNotFoundException e) {
338 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
339 return false;
340 }
341 }
342
343 private void persistWifiEnabled(boolean enabled) {
344 final ContentResolver cr = mContext.getContentResolver();
345 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
346 }
347
348 NetworkStateTracker getNetworkStateTracker() {
349 return mWifiStateTracker;
350 }
351
352 /**
353 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
354 * @return {@code true} if the operation succeeds
355 */
356 public boolean pingSupplicant() {
357 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800358
359 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361
362 /**
363 * see {@link android.net.wifi.WifiManager#startScan()}
364 * @return {@code true} if the operation succeeds
365 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400366 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800368
369 switch (mWifiStateTracker.getSupplicantState()) {
370 case DISCONNECTED:
371 case INACTIVE:
372 case SCANNING:
373 case DORMANT:
374 break;
375 default:
376 mWifiStateTracker.setScanResultHandling(
377 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
378 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800380 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
382
383 /**
384 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
385 * @param enable {@code true} to enable, {@code false} to disable.
386 * @return {@code true} if the enable/disable operation was
387 * started or is already in the queue.
388 */
389 public boolean setWifiEnabled(boolean enable) {
390 enforceChangePermission();
391 if (mWifiHandler == null) return false;
392
393 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700394 // caller may not have WAKE_LOCK permission - it's not required here
395 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700397 Binder.restoreCallingIdentity(ident);
398
Dianne Hackborn617f8772009-03-31 15:04:46 -0700399 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700400 // set a flag if the user is enabling Wifi while in airplane mode
401 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700402 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
404
405 return true;
406 }
407
408 /**
409 * Enables/disables Wi-Fi synchronously.
410 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
411 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700412 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 * @return {@code true} if the operation succeeds (or if the existing state
414 * is the same as the requested state)
415 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700416 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800418 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800420 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 return true;
422 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700423 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 return false;
425 }
426
Irfan Sheriffcd770372010-01-08 09:36:04 -0800427 /**
428 * Multiple calls to unregisterReceiver() cause exception and a system crash.
429 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
430 * disable wifi at the same time.
431 * Avoid doing a disable when the current Wifi state is UNKNOWN
432 * TODO: Handle driver load fail and supplicant lost as seperate states
433 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800434 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800435 return false;
436 }
437
Irfan Sherifff91444c2010-03-24 12:11:00 -0700438 /**
439 * Fail Wifi if AP is enabled
440 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
441 * WIFI_STATE_FAILED
442 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800443 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700444 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
445 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800446 }
447
Irfan Sherifff91444c2010-03-24 12:11:00 -0700448 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800451 if (!mWifiStateTracker.loadDriver()) {
452 Slog.e(TAG, "Failed to load Wi-Fi driver.");
453 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
454 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800456 if (!mWifiStateTracker.startSupplicant()) {
457 mWifiStateTracker.unloadDriver();
458 Slog.e(TAG, "Failed to start supplicant daemon.");
459 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
460 return false;
461 }
462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 registerForBroadcasts();
464 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 } else {
467
468 mContext.unregisterReceiver(mReceiver);
469 // Remove notification (it will no-op if it isn't visible)
470 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
471
472 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800473
474 if (!mWifiStateTracker.stopSupplicant()) {
475 Slog.e(TAG, "Failed to stop supplicant daemon.");
476 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
477 failedToStopSupplicantOrUnloadDriver = true;
478 }
479
480 /**
481 * Reset connections and disable interface
482 * before we unload the driver
483 */
484 mWifiStateTracker.resetConnections(true);
485
486 if (!mWifiStateTracker.unloadDriver()) {
487 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
488 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700489 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 failedToStopSupplicantOrUnloadDriver = true;
491 }
492 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 if (failedToStopSupplicantOrUnloadDriver) {
495 return false;
496 }
497 }
498
499 // Success!
500
501 if (persist) {
502 persistWifiEnabled(enable);
503 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700504 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 return true;
506 }
507
Dianne Hackborn617f8772009-03-31 15:04:46 -0700508 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800509 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510
The Android Open Source Project10592532009-03-18 17:39:46 -0700511 long ident = Binder.clearCallingIdentity();
512 try {
513 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700514 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700515 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700516 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700517 }
518 } catch (RemoteException e) {
519 } finally {
520 Binder.restoreCallingIdentity(ident);
521 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800524 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525
526 // Broadcast
527 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
528 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
529 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
530 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
531 mContext.sendStickyBroadcast(intent);
532 }
533
534 private void enforceAccessPermission() {
535 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
536 "WifiService");
537 }
538
539 private void enforceChangePermission() {
540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
541 "WifiService");
542
543 }
544
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700545 private void enforceMulticastChangePermission() {
546 mContext.enforceCallingOrSelfPermission(
547 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
548 "WifiService");
549 }
550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 /**
552 * see {@link WifiManager#getWifiState()}
553 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
554 * {@link WifiManager#WIFI_STATE_DISABLING},
555 * {@link WifiManager#WIFI_STATE_ENABLED},
556 * {@link WifiManager#WIFI_STATE_ENABLING},
557 * {@link WifiManager#WIFI_STATE_UNKNOWN}
558 */
559 public int getWifiEnabledState() {
560 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800561 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
563
564 /**
565 * see {@link android.net.wifi.WifiManager#disconnect()}
566 * @return {@code true} if the operation succeeds
567 */
568 public boolean disconnect() {
569 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800570
571 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573
574 /**
575 * see {@link android.net.wifi.WifiManager#reconnect()}
576 * @return {@code true} if the operation succeeds
577 */
578 public boolean reconnect() {
579 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800580
581 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
584 /**
585 * see {@link android.net.wifi.WifiManager#reassociate()}
586 * @return {@code true} if the operation succeeds
587 */
588 public boolean reassociate() {
589 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800590
591 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800594 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700595 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800596 * @param wifiConfig SSID, security and channel details as
597 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700598 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800599 * @return {@code true} if the start operation was
600 * started or is already in the queue.
601 */
602 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
603 enforceChangePermission();
604 if (mWifiHandler == null) return false;
605
606 synchronized (mWifiHandler) {
607
608 long ident = Binder.clearCallingIdentity();
609 sWakeLock.acquire();
610 Binder.restoreCallingIdentity(ident);
611
612 mLastEnableUid = Binder.getCallingUid();
613
614 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
615 }
616
617 return true;
618 }
619
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800620 public WifiConfiguration getWifiApConfiguration() {
621 final ContentResolver cr = mContext.getContentResolver();
622 WifiConfiguration wifiConfig = new WifiConfiguration();
623 int authType;
624 try {
625 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
626 if (wifiConfig.SSID == null)
627 return null;
628 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
629 wifiConfig.allowedKeyManagement.set(authType);
630 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
631 return wifiConfig;
632 } catch (Settings.SettingNotFoundException e) {
633 Slog.e(TAG,"AP settings not found, returning");
634 return null;
635 }
636 }
637
638 private void persistApConfiguration(WifiConfiguration wifiConfig) {
639 final ContentResolver cr = mContext.getContentResolver();
640 boolean isWpa;
641 if (wifiConfig == null)
642 return;
643 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
644 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
645 Settings.Secure.putInt(cr,
646 Settings.Secure.WIFI_AP_SECURITY,
647 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
648 if (isWpa)
649 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
650 }
651
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800652 /**
653 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
654 * and soft access point configured as a single operation.
655 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800656 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800657 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800658 * @return {@code true} if the operation succeeds (or if the existing state
659 * is the same as the requested state)
660 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800661 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800662 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800663 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
664
665 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800666 /* Configuration changed on a running access point */
667 if(enable && (wifiConfig != null)) {
668 try {
669 persistApConfiguration(wifiConfig);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700670 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
671 SOFTAP_IFACE);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800672 return true;
673 } catch(Exception e) {
674 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700675 try {
676 nwService.stopAccessPoint();
677 } catch (Exception ee) {
678 Slog.e(TAG, "Could not stop AP, :" + ee);
679 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800680 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
681 return false;
682 }
683 } else {
684 return true;
685 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800686 }
687
Irfan Sherifff91444c2010-03-24 12:11:00 -0700688 /**
689 * Fail AP if Wifi is enabled
690 */
691 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
692 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
693 return false;
694 }
695
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800696 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
697 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800698
699 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800700
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800701 /* Use default config if there is no existing config */
702 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
703 wifiConfig = new WifiConfiguration();
704 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
705 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
706 }
707 persistApConfiguration(wifiConfig);
708
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800709 if (!mWifiStateTracker.loadDriver()) {
710 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800711 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800712 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800713 }
714
715 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700716 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
717 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800718 } catch(Exception e) {
719 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800720 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
721 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800722 }
723
724 } else {
725
726 try {
727 nwService.stopAccessPoint();
728 } catch(Exception e) {
729 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800730 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
731 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800732 }
733
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800734 if (!mWifiStateTracker.unloadDriver()) {
735 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800736 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800737 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800738 }
739 }
740
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800741 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 return true;
743 }
744
745 /**
746 * see {@link WifiManager#getWifiApState()}
747 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
748 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
749 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
750 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
751 * {@link WifiManager#WIFI_AP_STATE_FAILED}
752 */
753 public int getWifiApEnabledState() {
754 enforceAccessPermission();
755 return mWifiApState;
756 }
757
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800758 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800759 final int previousWifiApState = mWifiApState;
760
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800761 /**
762 * Unload the driver if going to a failed state
763 */
764 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
765 mWifiStateTracker.unloadDriver();
766 }
767
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800768 long ident = Binder.clearCallingIdentity();
769 try {
770 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
771 mBatteryStats.noteWifiOn(uid);
772 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
773 mBatteryStats.noteWifiOff(uid);
774 }
775 } catch (RemoteException e) {
776 } finally {
777 Binder.restoreCallingIdentity(ident);
778 }
779
780 // Update state
781 mWifiApState = wifiAPState;
782
783 // Broadcast
784 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
785 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
786 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
787 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
788 mContext.sendStickyBroadcast(intent);
789 }
790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /**
792 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
793 * @return the list of configured networks
794 */
795 public List<WifiConfiguration> getConfiguredNetworks() {
796 enforceAccessPermission();
797 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /*
800 * We don't cache the list, because we want to allow
801 * for the possibility that the configuration file
802 * has been modified through some external means,
803 * such as the wpa_cli command line program.
804 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800805 listStr = mWifiStateTracker.listNetworks();
806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 List<WifiConfiguration> networks =
808 new ArrayList<WifiConfiguration>();
809 if (listStr == null)
810 return networks;
811
812 String[] lines = listStr.split("\n");
813 // Skip the first line, which is a header
814 for (int i = 1; i < lines.length; i++) {
815 String[] result = lines[i].split("\t");
816 // network-id | ssid | bssid | flags
817 WifiConfiguration config = new WifiConfiguration();
818 try {
819 config.networkId = Integer.parseInt(result[0]);
820 } catch(NumberFormatException e) {
821 continue;
822 }
823 if (result.length > 3) {
824 if (result[3].indexOf("[CURRENT]") != -1)
825 config.status = WifiConfiguration.Status.CURRENT;
826 else if (result[3].indexOf("[DISABLED]") != -1)
827 config.status = WifiConfiguration.Status.DISABLED;
828 else
829 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800830 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800833 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 networks.add(config);
835 }
836
837 return networks;
838 }
839
840 /**
841 * Read the variables from the supplicant daemon that are needed to
842 * fill in the WifiConfiguration object.
843 * <p/>
844 * The caller must hold the synchronization monitor.
845 * @param config the {@link WifiConfiguration} object to be filled in.
846 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800847 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848
849 int netId = config.networkId;
850 if (netId < 0)
851 return;
852
853 /*
854 * TODO: maybe should have a native method that takes an array of
855 * variable names and returns an array of values. But we'd still
856 * be doing a round trip to the supplicant daemon for each variable.
857 */
858 String value;
859
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800860 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800862 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 } else {
864 config.SSID = null;
865 }
866
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800867 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 if (!TextUtils.isEmpty(value)) {
869 config.BSSID = value;
870 } else {
871 config.BSSID = null;
872 }
873
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800874 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 config.priority = -1;
876 if (!TextUtils.isEmpty(value)) {
877 try {
878 config.priority = Integer.parseInt(value);
879 } catch (NumberFormatException ignore) {
880 }
881 }
882
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800883 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 config.hiddenSSID = false;
885 if (!TextUtils.isEmpty(value)) {
886 try {
887 config.hiddenSSID = Integer.parseInt(value) != 0;
888 } catch (NumberFormatException ignore) {
889 }
890 }
891
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800892 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 config.wepTxKeyIndex = -1;
894 if (!TextUtils.isEmpty(value)) {
895 try {
896 config.wepTxKeyIndex = Integer.parseInt(value);
897 } catch (NumberFormatException ignore) {
898 }
899 }
900
901 /*
902 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
903 * just a "*" if the key is set, or the null string otherwise.
904 */
905 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800906 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 if (!TextUtils.isEmpty(value)) {
908 config.wepKeys[i] = value;
909 } else {
910 config.wepKeys[i] = null;
911 }
912 }
913
914 /*
915 * Get the private shared key. Note that the actual keys are not passed back,
916 * just a "*" if the key is set, or the null string otherwise.
917 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800918 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (!TextUtils.isEmpty(value)) {
920 config.preSharedKey = value;
921 } else {
922 config.preSharedKey = null;
923 }
924
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800925 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 WifiConfiguration.Protocol.varName);
927 if (!TextUtils.isEmpty(value)) {
928 String vals[] = value.split(" ");
929 for (String val : vals) {
930 int index =
931 lookupString(val, WifiConfiguration.Protocol.strings);
932 if (0 <= index) {
933 config.allowedProtocols.set(index);
934 }
935 }
936 }
937
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800938 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 WifiConfiguration.KeyMgmt.varName);
940 if (!TextUtils.isEmpty(value)) {
941 String vals[] = value.split(" ");
942 for (String val : vals) {
943 int index =
944 lookupString(val, WifiConfiguration.KeyMgmt.strings);
945 if (0 <= index) {
946 config.allowedKeyManagement.set(index);
947 }
948 }
949 }
950
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800951 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 WifiConfiguration.AuthAlgorithm.varName);
953 if (!TextUtils.isEmpty(value)) {
954 String vals[] = value.split(" ");
955 for (String val : vals) {
956 int index =
957 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
958 if (0 <= index) {
959 config.allowedAuthAlgorithms.set(index);
960 }
961 }
962 }
963
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800964 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 WifiConfiguration.PairwiseCipher.varName);
966 if (!TextUtils.isEmpty(value)) {
967 String vals[] = value.split(" ");
968 for (String val : vals) {
969 int index =
970 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
971 if (0 <= index) {
972 config.allowedPairwiseCiphers.set(index);
973 }
974 }
975 }
976
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800977 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 WifiConfiguration.GroupCipher.varName);
979 if (!TextUtils.isEmpty(value)) {
980 String vals[] = value.split(" ");
981 for (String val : vals) {
982 int index =
983 lookupString(val, WifiConfiguration.GroupCipher.strings);
984 if (0 <= index) {
985 config.allowedGroupCiphers.set(index);
986 }
987 }
988 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800989
990 for (WifiConfiguration.EnterpriseField field :
991 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800992 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800993 field.varName());
994 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800995 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800996 field.setValue(value);
997 }
998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001001 private static String removeDoubleQuotes(String string) {
1002 if (string.length() <= 2) return "";
1003 return string.substring(1, string.length() - 1);
1004 }
1005
1006 private static String convertToQuotedString(String string) {
1007 return "\"" + string + "\"";
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1012 * @return the supplicant-assigned identifier for the new or updated
1013 * network if the operation succeeds, or {@code -1} if it fails
1014 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001015 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 /*
1019 * If the supplied networkId is -1, we create a new empty
1020 * network configuration. Otherwise, the networkId should
1021 * refer to an existing configuration.
1022 */
1023 int netId = config.networkId;
1024 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001025 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001027 synchronized (mWifiStateTracker) {
1028 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001029 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001030 if (netId < 0) {
1031 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001032 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001033 }
1034 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001036 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001038 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001041 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 /*
1043 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001044 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 * will fail, so we don't bother to make a separate check
1046 * for the validity of the ID up front.
1047 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001049 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001050 netId,
1051 WifiConfiguration.ssidVarName,
1052 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001054 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056 break setVariables;
1057 }
1058
1059 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001060 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001061 netId,
1062 WifiConfiguration.bssidVarName,
1063 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001065 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067 break setVariables;
1068 }
1069
1070 String allowedKeyManagementString =
1071 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1072 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001073 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001074 netId,
1075 WifiConfiguration.KeyMgmt.varName,
1076 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001078 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001079 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081 break setVariables;
1082 }
1083
1084 String allowedProtocolsString =
1085 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1086 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001087 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001088 netId,
1089 WifiConfiguration.Protocol.varName,
1090 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001092 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001093 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 }
1095 break setVariables;
1096 }
1097
1098 String allowedAuthAlgorithmsString =
1099 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1100 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001101 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001102 netId,
1103 WifiConfiguration.AuthAlgorithm.varName,
1104 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001106 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001107 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109 break setVariables;
1110 }
1111
1112 String allowedPairwiseCiphersString =
1113 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1114 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001115 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001116 netId,
1117 WifiConfiguration.PairwiseCipher.varName,
1118 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001120 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001121 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123 break setVariables;
1124 }
1125
1126 String allowedGroupCiphersString =
1127 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1128 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001129 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001130 netId,
1131 WifiConfiguration.GroupCipher.varName,
1132 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001134 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001135 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137 break setVariables;
1138 }
1139
1140 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1141 // by preventing "*" as a key.
1142 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001143 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001144 netId,
1145 WifiConfiguration.pskVarName,
1146 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001148 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 break setVariables;
1151 }
1152
1153 boolean hasSetKey = false;
1154 if (config.wepKeys != null) {
1155 for (int i = 0; i < config.wepKeys.length; i++) {
1156 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1157 // by preventing "*" as a key.
1158 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001159 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001160 netId,
1161 WifiConfiguration.wepKeyVarNames[i],
1162 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001164 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001165 "failed to set wep_key"+i+": " +
1166 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168 break setVariables;
1169 }
1170 hasSetKey = true;
1171 }
1172 }
1173 }
1174
1175 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001176 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001177 netId,
1178 WifiConfiguration.wepTxKeyIdxVarName,
1179 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001181 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001182 "failed to set wep_tx_keyidx: "+
1183 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185 break setVariables;
1186 }
1187 }
1188
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001189 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001190 netId,
1191 WifiConfiguration.priorityVarName,
1192 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001194 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001195 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 break setVariables;
1198 }
1199
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001200 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001201 netId,
1202 WifiConfiguration.hiddenSSIDVarName,
1203 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001205 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001206 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
1208 break setVariables;
1209 }
1210
Chung-yih Wang43374762009-09-16 14:28:42 +08001211 for (WifiConfiguration.EnterpriseField field
1212 : config.enterpriseFields) {
1213 String varName = field.varName();
1214 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001215 if (value != null) {
1216 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001217 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001218 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001219 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001220 netId,
1221 varName,
1222 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001223 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001225 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001226 }
1227 break setVariables;
1228 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001229 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001234 /*
1235 * For an update, if one of the setNetworkVariable operations fails,
1236 * we might want to roll back all the changes already made. But the
1237 * chances are that if anything is going to go wrong, it'll happen
1238 * the first time we try to set one of the variables.
1239 */
1240 if (newNetwork) {
1241 removeNetwork(netId);
1242 if (DBG) {
1243 Slog.d(TAG,
1244 "Failed to set a network variable, removed network: "
1245 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247 }
1248 return -1;
1249 }
1250
1251 private static String makeString(BitSet set, String[] strings) {
1252 StringBuffer buf = new StringBuffer();
1253 int nextSetBit = -1;
1254
1255 /* Make sure all set bits are in [0, strings.length) to avoid
1256 * going out of bounds on strings. (Shouldn't happen, but...) */
1257 set = set.get(0, strings.length);
1258
1259 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1260 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1261 }
1262
1263 // remove trailing space
1264 if (set.cardinality() > 0) {
1265 buf.setLength(buf.length() - 1);
1266 }
1267
1268 return buf.toString();
1269 }
1270
1271 private static int lookupString(String string, String[] strings) {
1272 int size = strings.length;
1273
1274 string = string.replace('-', '_');
1275
1276 for (int i = 0; i < size; i++)
1277 if (string.equals(strings[i]))
1278 return i;
1279
1280 if (DBG) {
1281 // if we ever get here, we should probably add the
1282 // value to WifiConfiguration to reflect that it's
1283 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001284 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
1287 return -1;
1288 }
1289
1290 /**
1291 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1292 * @param netId the integer that identifies the network configuration
1293 * to the supplicant
1294 * @return {@code true} if the operation succeeded
1295 */
1296 public boolean removeNetwork(int netId) {
1297 enforceChangePermission();
1298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 return mWifiStateTracker.removeNetwork(netId);
1300 }
1301
1302 /**
1303 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1304 * @param netId the integer that identifies the network configuration
1305 * to the supplicant
1306 * @param disableOthers if true, disable all other networks.
1307 * @return {@code true} if the operation succeeded
1308 */
1309 public boolean enableNetwork(int netId, boolean disableOthers) {
1310 enforceChangePermission();
1311
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001312 String ifname = mWifiStateTracker.getInterfaceName();
1313 NetworkUtils.enableInterface(ifname);
1314 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1315 if (!result) {
1316 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001318 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
1321 /**
1322 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1323 * @param netId the integer that identifies the network configuration
1324 * to the supplicant
1325 * @return {@code true} if the operation succeeded
1326 */
1327 public boolean disableNetwork(int netId) {
1328 enforceChangePermission();
1329
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001330 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 /**
1334 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1335 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1336 */
1337 public WifiInfo getConnectionInfo() {
1338 enforceAccessPermission();
1339 /*
1340 * Make sure we have the latest information, by sending
1341 * a status request to the supplicant.
1342 */
1343 return mWifiStateTracker.requestConnectionInfo();
1344 }
1345
1346 /**
1347 * Return the results of the most recent access point scan, in the form of
1348 * a list of {@link ScanResult} objects.
1349 * @return the list of results
1350 */
1351 public List<ScanResult> getScanResults() {
1352 enforceAccessPermission();
1353 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001354
1355 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 if (reply == null) {
1357 return null;
1358 }
1359
1360 List<ScanResult> scanList = new ArrayList<ScanResult>();
1361
1362 int lineCount = 0;
1363
1364 int replyLen = reply.length();
1365 // Parse the result string, keeping in mind that the last line does
1366 // not end with a newline.
1367 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1368 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1369 ++lineCount;
1370 /*
1371 * Skip the first line, which is a header
1372 */
1373 if (lineCount == 1) {
1374 lineBeg = lineEnd + 1;
1375 continue;
1376 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001377 if (lineEnd > lineBeg) {
1378 String line = reply.substring(lineBeg, lineEnd);
1379 ScanResult scanResult = parseScanResult(line);
1380 if (scanResult != null) {
1381 scanList.add(scanResult);
1382 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001383 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385 }
1386 lineBeg = lineEnd + 1;
1387 }
1388 }
1389 mWifiStateTracker.setScanResultsList(scanList);
1390 return scanList;
1391 }
1392
1393 /**
1394 * Parse the scan result line passed to us by wpa_supplicant (helper).
1395 * @param line the line to parse
1396 * @return the {@link ScanResult} object
1397 */
1398 private ScanResult parseScanResult(String line) {
1399 ScanResult scanResult = null;
1400 if (line != null) {
1401 /*
1402 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1403 * must synchronized here!
1404 */
1405 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001406 String[] result = scanResultPattern.split(line);
1407 if (3 <= result.length && result.length <= 5) {
1408 String bssid = result[0];
1409 // bssid | frequency | level | flags | ssid
1410 int frequency;
1411 int level;
1412 try {
1413 frequency = Integer.parseInt(result[1]);
1414 level = Integer.parseInt(result[2]);
1415 /* some implementations avoid negative values by adding 256
1416 * so we need to adjust for that here.
1417 */
1418 if (level > 0) level -= 256;
1419 } catch (NumberFormatException e) {
1420 frequency = 0;
1421 level = 0;
1422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Mike Lockwood1a645052009-06-25 13:01:12 -04001424 /*
1425 * The formatting of the results returned by
1426 * wpa_supplicant is intended to make the fields
1427 * line up nicely when printed,
1428 * not to make them easy to parse. So we have to
1429 * apply some heuristics to figure out which field
1430 * is the SSID and which field is the flags.
1431 */
1432 String ssid;
1433 String flags;
1434 if (result.length == 4) {
1435 if (result[3].charAt(0) == '[') {
1436 flags = result[3];
1437 ssid = "";
1438 } else {
1439 flags = "";
1440 ssid = result[3];
1441 }
1442 } else if (result.length == 5) {
1443 flags = result[3];
1444 ssid = result[4];
1445 } else {
1446 // Here, we must have 3 fields: no flags and ssid
1447 // set
1448 flags = "";
1449 ssid = "";
1450 }
1451
Mike Lockwood00717e22009-08-17 10:09:36 -04001452 // bssid + ssid is the hash key
1453 String key = bssid + ssid;
1454 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001455 if (scanResult != null) {
1456 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001457 scanResult.SSID = ssid;
1458 scanResult.capabilities = flags;
1459 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001460 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 // Do not add scan results that have no SSID set
1462 if (0 < ssid.trim().length()) {
1463 scanResult =
1464 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001465 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001466 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001469 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001470 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001471 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
1473 }
1474 }
1475
1476 return scanResult;
1477 }
1478
1479 /**
1480 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1481 * and construct a {@code WifiConfiguration} that describes the encryption,
1482 * key management, and authenticaion capabilities of the access point.
1483 * @param flags the string returned by wpa_supplicant
1484 * @return the {@link WifiConfiguration} object, filled in
1485 */
1486 WifiConfiguration parseScanFlags(String flags) {
1487 WifiConfiguration config = new WifiConfiguration();
1488
1489 if (flags.length() == 0) {
1490 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1491 }
1492 // ... to be implemented
1493 return config;
1494 }
1495
1496 /**
1497 * Tell the supplicant to persist the current list of configured networks.
1498 * @return {@code true} if the operation succeeded
1499 */
1500 public boolean saveConfiguration() {
1501 boolean result;
1502 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001505 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 if (result && mNeedReconfig) {
1507 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001508 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509
1510 if (result) {
1511 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1512 mContext.sendBroadcast(intent);
1513 }
1514 }
1515 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001516 // Inform the backup manager about a data change
1517 IBackupManager ibm = IBackupManager.Stub.asInterface(
1518 ServiceManager.getService(Context.BACKUP_SERVICE));
1519 if (ibm != null) {
1520 try {
1521 ibm.dataChanged("com.android.providers.settings");
1522 } catch (Exception e) {
1523 // Try again later
1524 }
1525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 return result;
1527 }
1528
1529 /**
1530 * Set the number of radio frequency channels that are allowed to be used
1531 * in the current regulatory domain. This method should be used only
1532 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001533 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 * persisted as a Secure setting.
1535 * @param numChannels the number of allowed channels. Must be greater than 0
1536 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001537 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1539 * {@code numChannels} is outside the valid range.
1540 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001541 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001542 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001543 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 enforceChangePermission();
1545 /*
1546 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1547 * but if Wi-Fi isn't currently enabled, that's not possible, and
1548 * we want to persist the setting anyway,so that it will take
1549 * effect when Wi-Fi does become enabled.
1550 */
1551 boolean found = false;
1552 for (int validChan : sValidRegulatoryChannelCounts) {
1553 if (validChan == numChannels) {
1554 found = true;
1555 break;
1556 }
1557 }
1558 if (!found) {
1559 return false;
1560 }
1561
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001562 if (persist) {
1563 Settings.Secure.putInt(mContext.getContentResolver(),
1564 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1565 numChannels);
1566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 mWifiStateTracker.setNumAllowedChannels(numChannels);
1568 return true;
1569 }
1570
1571 /**
1572 * Return the number of frequency channels that are allowed
1573 * to be used in the current regulatory domain.
1574 * @return the number of allowed channels, or {@code -1} if an error occurs
1575 */
1576 public int getNumAllowedChannels() {
1577 int numChannels;
1578
1579 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001580
1581 /*
1582 * If we can't get the value from the driver (e.g., because
1583 * Wi-Fi is not currently enabled), get the value from
1584 * Settings.
1585 */
1586 numChannels = mWifiStateTracker.getNumAllowedChannels();
1587 if (numChannels < 0) {
1588 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1589 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1590 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592 return numChannels;
1593 }
1594
1595 /**
1596 * Return the list of valid values for the number of allowed radio channels
1597 * for various regulatory domains.
1598 * @return the list of channel counts
1599 */
1600 public int[] getValidChannelCounts() {
1601 enforceAccessPermission();
1602 return sValidRegulatoryChannelCounts;
1603 }
1604
1605 /**
1606 * Return the DHCP-assigned addresses from the last successful DHCP request,
1607 * if any.
1608 * @return the DHCP information
1609 */
1610 public DhcpInfo getDhcpInfo() {
1611 enforceAccessPermission();
1612 return mWifiStateTracker.getDhcpInfo();
1613 }
1614
1615 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1616 @Override
1617 public void onReceive(Context context, Intent intent) {
1618 String action = intent.getAction();
1619
Doug Zongker43866e02010-01-07 12:09:54 -08001620 long idleMillis =
1621 Settings.Secure.getLong(mContext.getContentResolver(),
1622 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001624 Settings.System.getInt(mContext.getContentResolver(),
1625 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001627 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 mAlarmManager.cancel(mIdleIntent);
1629 mDeviceIdle = false;
1630 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001631 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001633 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001635 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 /*
1637 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1638 * AND the "stay on while plugged in" setting doesn't match the
1639 * current power conditions (i.e, not plugged in, plugged in to USB,
1640 * or plugged in to AC).
1641 */
1642 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001643 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1644 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001645 // we used to go to sleep immediately, but this caused some race conditions
1646 // we don't have time to track down for this release. Delay instead, but not
1647 // as long as we would if connected (below)
1648 // TODO - fix the race conditions and switch back to the immediate turn-off
1649 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001651 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1652 // // do not keep Wifi awake when screen is off if Wifi is not associated
1653 // mDeviceIdle = true;
1654 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001655 } else {
1656 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001657 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001658 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 /* we can return now -- there's nothing to do until we get the idle intent back */
1662 return;
1663 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001664 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 mDeviceIdle = true;
1666 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1667 /*
1668 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1669 * AND we are transitioning from a state in which the device was supposed
1670 * to stay awake to a state in which it is not supposed to stay awake.
1671 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1672 * the already-set timer.
1673 */
1674 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1677 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1678 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001679 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1681 mPluggedType = pluggedType;
1682 return;
1683 }
1684 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001685 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001686 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1687 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1688 boolean isBluetoothPlaying = false;
1689 for (BluetoothDevice sink : sinks) {
1690 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1691 isBluetoothPlaying = true;
1692 }
1693 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001694 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 } else {
1697 return;
1698 }
1699
1700 updateWifiState();
1701 }
1702
1703 /**
1704 * Determines whether the Wi-Fi chipset should stay awake or be put to
1705 * sleep. Looks at the setting for the sleep policy and the current
1706 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001707 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 * @see #shouldDeviceStayAwake(int, int)
1709 */
1710 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1711 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1712 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1713
1714 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1715 // Never sleep
1716 return true;
1717 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1718 (pluggedType != 0)) {
1719 // Never sleep while plugged, and we're plugged
1720 return true;
1721 } else {
1722 // Default
1723 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1724 }
1725 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 /**
1728 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1729 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1730 * of {@code 0} isn't really a plugged type, but rather an indication that the
1731 * device isn't plugged in at all, there is no bit value corresponding to a
1732 * {@code pluggedType} value of {@code 0}. That is why we shift by
1733 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1734 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1735 * keep the device (and hence Wi-Fi) awake.
1736 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1737 * being made
1738 * @return {@code true} if {@code pluggedType} indicates that the device is
1739 * supposed to stay awake, {@code false} otherwise.
1740 */
1741 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1742 return (stayAwakeConditions & pluggedType) != 0;
1743 }
1744 };
1745
Dianne Hackborn617f8772009-03-31 15:04:46 -07001746 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 Message msg = Message.obtain(mWifiHandler,
1748 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001749 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 msg.sendToTarget();
1751 }
1752
1753 private void sendStartMessage(boolean scanOnlyMode) {
1754 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1755 }
1756
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001757 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1758 Message.obtain(mWifiHandler,
1759 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001760 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001761 }
1762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001764 // send a message so it's all serialized
1765 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1766 }
1767
1768 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001770 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 boolean lockHeld = mLocks.hasLocks();
1772 int strongestLockMode;
1773 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1774 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1775 if (mDeviceIdle && lockHeld) {
1776 strongestLockMode = mLocks.getStrongestLockMode();
1777 } else {
1778 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1779 }
1780
1781 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001782 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 return;
1784 }
1785 if (wifiShouldBeEnabled) {
1786 if (wifiShouldBeStarted) {
1787 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001788 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 sWakeLock.acquire();
1790 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001791 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 int wakeLockTimeout =
1793 Settings.Secure.getInt(
1794 mContext.getContentResolver(),
1795 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1796 DEFAULT_WAKELOCK_TIMEOUT);
1797 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001798 * We are assuming that ConnectivityService can make
1799 * a transition to cellular data within wakeLockTimeout time.
1800 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 */
1802 sDriverStopWakeLock.acquire();
1803 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1804 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1805 }
1806 } else {
1807 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001808 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811 }
1812
1813 private void registerForBroadcasts() {
1814 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1816 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1817 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1818 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001819 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 mContext.registerReceiver(mReceiver, intentFilter);
1821 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 private boolean isAirplaneSensitive() {
1824 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1825 Settings.System.AIRPLANE_MODE_RADIOS);
1826 return airplaneModeRadios == null
1827 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1828 }
1829
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001830 private boolean isAirplaneToggleable() {
1831 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1832 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1833 return toggleableRadios != null
1834 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1835 }
1836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 /**
1838 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1839 * currently on.
1840 * @return {@code true} if airplane mode is on.
1841 */
1842 private boolean isAirplaneModeOn() {
1843 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1844 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1845 }
1846
1847 /**
1848 * Handler that allows posting to the WifiThread.
1849 */
1850 private class WifiHandler extends Handler {
1851 public WifiHandler(Looper looper) {
1852 super(looper);
1853 }
1854
1855 @Override
1856 public void handleMessage(Message msg) {
1857 switch (msg.what) {
1858
1859 case MESSAGE_ENABLE_WIFI:
Irfan Sheriff7b009782010-03-11 16:37:45 -08001860 if (mWifiWatchdogService == null) {
1861 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1862 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001863 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 sWakeLock.release();
1865 break;
1866
1867 case MESSAGE_START_WIFI:
1868 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1869 mWifiStateTracker.restart();
1870 sWakeLock.release();
1871 break;
1872
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001873 case MESSAGE_UPDATE_STATE:
1874 doUpdateWifiState();
1875 break;
1876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 case MESSAGE_DISABLE_WIFI:
1878 // a non-zero msg.arg1 value means the "enabled" setting
1879 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001880 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001881 if (mWifiWatchdogService != null) {
1882 mWifiWatchdogService.quit();
1883 mWifiWatchdogService = null;
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 sWakeLock.release();
1886 break;
1887
1888 case MESSAGE_STOP_WIFI:
1889 mWifiStateTracker.disconnectAndStop();
1890 // don't release wakelock
1891 break;
1892
1893 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001894 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001896
1897 case MESSAGE_START_ACCESS_POINT:
1898 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001899 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001900 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001901 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001902 break;
1903
1904 case MESSAGE_STOP_ACCESS_POINT:
1905 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001906 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001907 (WifiConfiguration) msg.obj);
1908 sWakeLock.release();
1909 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911 }
1912 }
1913
1914 @Override
1915 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1916 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1917 != PackageManager.PERMISSION_GRANTED) {
1918 pw.println("Permission Denial: can't dump WifiService from from pid="
1919 + Binder.getCallingPid()
1920 + ", uid=" + Binder.getCallingUid());
1921 return;
1922 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001923 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 pw.println("Stay-awake conditions: " +
1925 Settings.System.getInt(mContext.getContentResolver(),
1926 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1927 pw.println();
1928
1929 pw.println("Internal state:");
1930 pw.println(mWifiStateTracker);
1931 pw.println();
1932 pw.println("Latest scan results:");
1933 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1934 if (scanResults != null && scanResults.size() != 0) {
1935 pw.println(" BSSID Frequency RSSI Flags SSID");
1936 for (ScanResult r : scanResults) {
1937 pw.printf(" %17s %9d %5d %-16s %s%n",
1938 r.BSSID,
1939 r.frequency,
1940 r.level,
1941 r.capabilities,
1942 r.SSID == null ? "" : r.SSID);
1943 }
1944 }
1945 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001946 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1947 mScanLocksAcquired + " scan");
1948 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1949 mScanLocksReleased + " scan");
1950 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 pw.println("Locks held:");
1952 mLocks.dump(pw);
1953 }
1954
1955 private static String stateName(int wifiState) {
1956 switch (wifiState) {
1957 case WIFI_STATE_DISABLING:
1958 return "disabling";
1959 case WIFI_STATE_DISABLED:
1960 return "disabled";
1961 case WIFI_STATE_ENABLING:
1962 return "enabling";
1963 case WIFI_STATE_ENABLED:
1964 return "enabled";
1965 case WIFI_STATE_UNKNOWN:
1966 return "unknown state";
1967 default:
1968 return "[invalid state]";
1969 }
1970 }
1971
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001972 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001974 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976
1977 public void binderDied() {
1978 synchronized (mLocks) {
1979 releaseWifiLockLocked(mBinder);
1980 }
1981 }
1982
1983 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001984 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 }
1987
1988 private class LockList {
1989 private List<WifiLock> mList;
1990
1991 private LockList() {
1992 mList = new ArrayList<WifiLock>();
1993 }
1994
1995 private synchronized boolean hasLocks() {
1996 return !mList.isEmpty();
1997 }
1998
1999 private synchronized int getStrongestLockMode() {
2000 if (mList.isEmpty()) {
2001 return WifiManager.WIFI_MODE_FULL;
2002 }
2003 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002004 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 return WifiManager.WIFI_MODE_FULL;
2006 }
2007 }
2008 return WifiManager.WIFI_MODE_SCAN_ONLY;
2009 }
2010
2011 private void addLock(WifiLock lock) {
2012 if (findLockByBinder(lock.mBinder) < 0) {
2013 mList.add(lock);
2014 }
2015 }
2016
2017 private WifiLock removeLock(IBinder binder) {
2018 int index = findLockByBinder(binder);
2019 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002020 WifiLock ret = mList.remove(index);
2021 ret.unlinkDeathRecipient();
2022 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 } else {
2024 return null;
2025 }
2026 }
2027
2028 private int findLockByBinder(IBinder binder) {
2029 int size = mList.size();
2030 for (int i = size - 1; i >= 0; i--)
2031 if (mList.get(i).mBinder == binder)
2032 return i;
2033 return -1;
2034 }
2035
2036 private void dump(PrintWriter pw) {
2037 for (WifiLock l : mList) {
2038 pw.print(" ");
2039 pw.println(l);
2040 }
2041 }
2042 }
2043
2044 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2046 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
2047 return false;
2048 }
2049 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2050 synchronized (mLocks) {
2051 return acquireWifiLockLocked(wifiLock);
2052 }
2053 }
2054
2055 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002056 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002059
The Android Open Source Project10592532009-03-18 17:39:46 -07002060 int uid = Binder.getCallingUid();
2061 long ident = Binder.clearCallingIdentity();
2062 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002063 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002064 case WifiManager.WIFI_MODE_FULL:
2065 ++mFullLocksAcquired;
2066 mBatteryStats.noteFullWifiLockAcquired(uid);
2067 break;
2068 case WifiManager.WIFI_MODE_SCAN_ONLY:
2069 ++mScanLocksAcquired;
2070 mBatteryStats.noteScanWifiLockAcquired(uid);
2071 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002072 }
2073 } catch (RemoteException e) {
2074 } finally {
2075 Binder.restoreCallingIdentity(ident);
2076 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 updateWifiState();
2079 return true;
2080 }
2081
2082 public boolean releaseWifiLock(IBinder lock) {
2083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2084 synchronized (mLocks) {
2085 return releaseWifiLockLocked(lock);
2086 }
2087 }
2088
2089 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002090 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002091
The Android Open Source Project10592532009-03-18 17:39:46 -07002092 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002093
Joe Onorato8a9b2202010-02-26 18:56:32 -08002094 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002095
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002096 hadLock = (wifiLock != null);
2097
2098 if (hadLock) {
2099 int uid = Binder.getCallingUid();
2100 long ident = Binder.clearCallingIdentity();
2101 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002102 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002103 case WifiManager.WIFI_MODE_FULL:
2104 ++mFullLocksReleased;
2105 mBatteryStats.noteFullWifiLockReleased(uid);
2106 break;
2107 case WifiManager.WIFI_MODE_SCAN_ONLY:
2108 ++mScanLocksReleased;
2109 mBatteryStats.noteScanWifiLockReleased(uid);
2110 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002111 }
2112 } catch (RemoteException e) {
2113 } finally {
2114 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002115 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002116 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002117 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002119 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002121
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002122 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002123 implements IBinder.DeathRecipient {
2124 String mTag;
2125 int mMode;
2126 IBinder mBinder;
2127
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002128 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002129 super();
2130 mTag = tag;
2131 mMode = mode;
2132 mBinder = binder;
2133 try {
2134 mBinder.linkToDeath(this, 0);
2135 } catch (RemoteException e) {
2136 binderDied();
2137 }
2138 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002139
2140 void unlinkDeathRecipient() {
2141 mBinder.unlinkToDeath(this, 0);
2142 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002143 }
2144
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002145 private class Multicaster extends DeathRecipient {
2146 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002147 super(Binder.getCallingUid(), tag, binder);
2148 }
2149
2150 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002151 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002152 synchronized (mMulticasters) {
2153 int i = mMulticasters.indexOf(this);
2154 if (i != -1) {
2155 removeMulticasterLocked(i, mMode);
2156 }
2157 }
2158 }
2159
2160 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002161 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002162 }
2163
2164 public int getUid() {
2165 return mMode;
2166 }
2167 }
2168
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002169 public void initializeMulticastFiltering() {
2170 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002171
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002172 synchronized (mMulticasters) {
2173 // if anybody had requested filters be off, leave off
2174 if (mMulticasters.size() != 0) {
2175 return;
2176 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002177 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002178 }
2179 }
2180 }
2181
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002182 public void acquireMulticastLock(IBinder binder, String tag) {
2183 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002184
2185 synchronized (mMulticasters) {
2186 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002187 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002188 // Note that we could call stopPacketFiltering only when
2189 // our new size == 1 (first call), but this function won't
2190 // be called often and by making the stopPacket call each
2191 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002192 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002193 }
2194
2195 int uid = Binder.getCallingUid();
2196 Long ident = Binder.clearCallingIdentity();
2197 try {
2198 mBatteryStats.noteWifiMulticastEnabled(uid);
2199 } catch (RemoteException e) {
2200 } finally {
2201 Binder.restoreCallingIdentity(ident);
2202 }
2203 }
2204
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002205 public void releaseMulticastLock() {
2206 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002207
2208 int uid = Binder.getCallingUid();
2209 synchronized (mMulticasters) {
2210 mMulticastDisabled++;
2211 int size = mMulticasters.size();
2212 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002213 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002214 if ((m != null) && (m.getUid() == uid)) {
2215 removeMulticasterLocked(i, uid);
2216 }
2217 }
2218 }
2219 }
2220
2221 private void removeMulticasterLocked(int i, int uid)
2222 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002223 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002224
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002225 if (removed != null) {
2226 removed.unlinkDeathRecipient();
2227 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002228 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002229 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002230 }
2231
2232 Long ident = Binder.clearCallingIdentity();
2233 try {
2234 mBatteryStats.noteWifiMulticastDisabled(uid);
2235 } catch (RemoteException e) {
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
2239 }
2240
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002241 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002242 enforceAccessPermission();
2243
2244 synchronized (mMulticasters) {
2245 return (mMulticasters.size() > 0);
2246 }
2247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248}