blob: 35baaa702e0abf575765e97fb8526ab6e2474593 [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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 // Wake lock used by other operations
148 private static PowerManager.WakeLock sWakeLock;
149
Irfan Sheriff59610c02010-03-30 11:00:41 -0700150 private static final int MESSAGE_ENABLE_WIFI = 0;
151 private static final int MESSAGE_DISABLE_WIFI = 1;
152 private static final int MESSAGE_STOP_WIFI = 2;
153 private static final int MESSAGE_START_WIFI = 3;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700154 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800155 private static final int MESSAGE_START_ACCESS_POINT = 6;
156 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700157 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
160 private final WifiHandler mWifiHandler;
161
162 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 * Cache of scan results objects (size is somewhat arbitrary)
164 */
165 private static final int SCAN_RESULT_CACHE_SIZE = 80;
166 private final LinkedHashMap<String, ScanResult> mScanResultCache;
167
168 /*
169 * Character buffer used to parse scan results (optimization)
170 */
171 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private boolean mNeedReconfig;
173
Dianne Hackborn617f8772009-03-31 15:04:46 -0700174 /*
175 * Last UID that asked to enable WIFI.
176 */
177 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800178
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700179 /*
180 * Last UID that asked to enable WIFI AP.
181 */
182 private int mLastApEnableUid = Process.myUid();
183
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 /**
186 * Number of allowed radio frequency channels in various regulatory domains.
187 * This list is sufficient for 802.11b/g networks (2.4GHz range).
188 */
189 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
190
191 private static final String ACTION_DEVICE_IDLE =
192 "com.android.server.WifiManager.action.DEVICE_IDLE";
193
194 WifiService(Context context, WifiStateTracker tracker) {
195 mContext = context;
196 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400197 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700198 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800199
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800200 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
201 nwService = INetworkManagementService.Stub.asInterface(b);
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 mScanResultCache = new LinkedHashMap<String, ScanResult>(
204 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
205 /*
206 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
207 * elements
208 */
209 public boolean removeEldestEntry(Map.Entry eldest) {
210 return SCAN_RESULT_CACHE_SIZE < this.size();
211 }
212 };
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 HandlerThread wifiThread = new HandlerThread("WifiService");
215 wifiThread.start();
216 mWifiHandler = new WifiHandler(wifiThread.getLooper());
217
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800218 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800219 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
221 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
222 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
223 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
224
225 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
226 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 mContext.registerReceiver(
229 new BroadcastReceiver() {
230 @Override
231 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700232 // clear our flag indicating the user has overwridden airplane mode
233 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700234 // on airplane disable, restore Wifi if the saved state indicates so
235 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
236 persistWifiEnabled(true);
237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 updateWifiState();
239 }
240 },
241 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
242
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800243 mContext.registerReceiver(
244 new BroadcastReceiver() {
245 @Override
246 public void onReceive(Context context, Intent intent) {
247
248 ArrayList<String> available = intent.getStringArrayListExtra(
249 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
250 ArrayList<String> active = intent.getStringArrayListExtra(
251 ConnectivityManager.EXTRA_ACTIVE_TETHER);
252 updateTetherState(available, active);
253
254 }
255 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800256 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800257
Irfan Sheriff7b009782010-03-11 16:37:45 -0800258 /**
259 * Check if Wi-Fi needs to be enabled and start
260 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700261 *
262 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800263 */
264 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700265 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700266 boolean wifiEnabled = !isAirplaneModeOn()
267 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800268 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
269 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700270 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800271 }
272
273 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
274
275 boolean wifiTethered = false;
276 boolean wifiAvailable = false;
277
278 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
279 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
280
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700281 if (mCm == null) {
282 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
283 }
284
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800285 mWifiRegexs = mCm.getTetherableWifiRegexs();
286
287 for (String intf : available) {
288 for (String regex : mWifiRegexs) {
289 if (intf.matches(regex)) {
290
291 InterfaceConfiguration ifcg = null;
292 try {
293 ifcg = service.getInterfaceConfig(intf);
294 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700295 /* IP/netmask: 192.168.43.1/255.255.255.0 */
296 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800297 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
298 ifcg.interfaceFlags = "up";
299
300 service.setInterfaceConfig(intf, ifcg);
301 }
302 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800303 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700304 try {
305 nwService.stopAccessPoint();
306 } catch (Exception ee) {
307 Slog.e(TAG, "Could not stop AP, :" + ee);
308 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800309 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800310 return;
311 }
312
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800313 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800314 Slog.e(TAG, "Error tethering "+intf);
315 }
316 break;
317 }
318 }
319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 }
321
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700322 private boolean testAndClearWifiSavedState() {
323 final ContentResolver cr = mContext.getContentResolver();
324 int wifiSavedState = 0;
325 try {
326 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
327 if(wifiSavedState == 1)
328 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
329 } catch (Settings.SettingNotFoundException e) {
330 ;
331 }
332 return (wifiSavedState == 1);
333 }
334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 private boolean getPersistedWifiEnabled() {
336 final ContentResolver cr = mContext.getContentResolver();
337 try {
338 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
339 } catch (Settings.SettingNotFoundException e) {
340 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
341 return false;
342 }
343 }
344
345 private void persistWifiEnabled(boolean enabled) {
346 final ContentResolver cr = mContext.getContentResolver();
347 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
348 }
349
350 NetworkStateTracker getNetworkStateTracker() {
351 return mWifiStateTracker;
352 }
353
354 /**
355 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
356 * @return {@code true} if the operation succeeds
357 */
358 public boolean pingSupplicant() {
359 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800360
361 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
363
364 /**
365 * see {@link android.net.wifi.WifiManager#startScan()}
366 * @return {@code true} if the operation succeeds
367 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400368 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800370
371 switch (mWifiStateTracker.getSupplicantState()) {
372 case DISCONNECTED:
373 case INACTIVE:
374 case SCANNING:
375 case DORMANT:
376 break;
377 default:
378 mWifiStateTracker.setScanResultHandling(
379 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
380 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800382 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 }
384
385 /**
386 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
387 * @param enable {@code true} to enable, {@code false} to disable.
388 * @return {@code true} if the enable/disable operation was
389 * started or is already in the queue.
390 */
391 public boolean setWifiEnabled(boolean enable) {
392 enforceChangePermission();
393 if (mWifiHandler == null) return false;
394
395 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700396 // caller may not have WAKE_LOCK permission - it's not required here
397 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700399 Binder.restoreCallingIdentity(ident);
400
Dianne Hackborn617f8772009-03-31 15:04:46 -0700401 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700402 // set a flag if the user is enabling Wifi while in airplane mode
403 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700404 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
407 return true;
408 }
409
410 /**
411 * Enables/disables Wi-Fi synchronously.
412 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
413 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700414 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 * @return {@code true} if the operation succeeds (or if the existing state
416 * is the same as the requested state)
417 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700418 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800420 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800422 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 return true;
424 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700425 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 return false;
427 }
428
Irfan Sheriffcd770372010-01-08 09:36:04 -0800429 /**
430 * Multiple calls to unregisterReceiver() cause exception and a system crash.
431 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
432 * disable wifi at the same time.
433 * Avoid doing a disable when the current Wifi state is UNKNOWN
434 * TODO: Handle driver load fail and supplicant lost as seperate states
435 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800436 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800437 return false;
438 }
439
Irfan Sherifff91444c2010-03-24 12:11:00 -0700440 /**
441 * Fail Wifi if AP is enabled
442 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
443 * WIFI_STATE_FAILED
444 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800445 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700446 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
447 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800448 }
449
Irfan Sherifff91444c2010-03-24 12:11:00 -0700450 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800453 if (!mWifiStateTracker.loadDriver()) {
454 Slog.e(TAG, "Failed to load Wi-Fi driver.");
455 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
456 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800458 if (!mWifiStateTracker.startSupplicant()) {
459 mWifiStateTracker.unloadDriver();
460 Slog.e(TAG, "Failed to start supplicant daemon.");
461 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
462 return false;
463 }
464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 registerForBroadcasts();
466 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 } else {
469
470 mContext.unregisterReceiver(mReceiver);
471 // Remove notification (it will no-op if it isn't visible)
472 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
473
474 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800475
476 if (!mWifiStateTracker.stopSupplicant()) {
477 Slog.e(TAG, "Failed to stop supplicant daemon.");
478 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
479 failedToStopSupplicantOrUnloadDriver = true;
480 }
481
482 /**
483 * Reset connections and disable interface
484 * before we unload the driver
485 */
486 mWifiStateTracker.resetConnections(true);
487
488 if (!mWifiStateTracker.unloadDriver()) {
489 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
490 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700491 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 failedToStopSupplicantOrUnloadDriver = true;
493 }
494 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 if (failedToStopSupplicantOrUnloadDriver) {
497 return false;
498 }
499 }
500
501 // Success!
502
503 if (persist) {
504 persistWifiEnabled(enable);
505 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700506 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 return true;
508 }
509
Dianne Hackborn617f8772009-03-31 15:04:46 -0700510 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800511 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512
The Android Open Source Project10592532009-03-18 17:39:46 -0700513 long ident = Binder.clearCallingIdentity();
514 try {
515 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700516 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700517 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700518 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700519 }
520 } catch (RemoteException e) {
521 } finally {
522 Binder.restoreCallingIdentity(ident);
523 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800526 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
528 // Broadcast
529 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
531 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
532 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
533 mContext.sendStickyBroadcast(intent);
534 }
535
536 private void enforceAccessPermission() {
537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
538 "WifiService");
539 }
540
541 private void enforceChangePermission() {
542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
543 "WifiService");
544
545 }
546
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700547 private void enforceMulticastChangePermission() {
548 mContext.enforceCallingOrSelfPermission(
549 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
550 "WifiService");
551 }
552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 /**
554 * see {@link WifiManager#getWifiState()}
555 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
556 * {@link WifiManager#WIFI_STATE_DISABLING},
557 * {@link WifiManager#WIFI_STATE_ENABLED},
558 * {@link WifiManager#WIFI_STATE_ENABLING},
559 * {@link WifiManager#WIFI_STATE_UNKNOWN}
560 */
561 public int getWifiEnabledState() {
562 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800563 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 }
565
566 /**
567 * see {@link android.net.wifi.WifiManager#disconnect()}
568 * @return {@code true} if the operation succeeds
569 */
570 public boolean disconnect() {
571 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800572
573 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 }
575
576 /**
577 * see {@link android.net.wifi.WifiManager#reconnect()}
578 * @return {@code true} if the operation succeeds
579 */
580 public boolean reconnect() {
581 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800582
583 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585
586 /**
587 * see {@link android.net.wifi.WifiManager#reassociate()}
588 * @return {@code true} if the operation succeeds
589 */
590 public boolean reassociate() {
591 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800592
593 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
595
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800596 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700597 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800598 * @param wifiConfig SSID, security and channel details as
599 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700600 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800601 * @return {@code true} if the start operation was
602 * started or is already in the queue.
603 */
604 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
605 enforceChangePermission();
606 if (mWifiHandler == null) return false;
607
608 synchronized (mWifiHandler) {
609
610 long ident = Binder.clearCallingIdentity();
611 sWakeLock.acquire();
612 Binder.restoreCallingIdentity(ident);
613
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700614 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800615 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
616 }
617
618 return true;
619 }
620
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800621 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700622 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800623 final ContentResolver cr = mContext.getContentResolver();
624 WifiConfiguration wifiConfig = new WifiConfiguration();
625 int authType;
626 try {
627 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
628 if (wifiConfig.SSID == null)
629 return null;
630 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
631 wifiConfig.allowedKeyManagement.set(authType);
632 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
633 return wifiConfig;
634 } catch (Settings.SettingNotFoundException e) {
635 Slog.e(TAG,"AP settings not found, returning");
636 return null;
637 }
638 }
639
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700640 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
641 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800642 final ContentResolver cr = mContext.getContentResolver();
643 boolean isWpa;
644 if (wifiConfig == null)
645 return;
646 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
647 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
648 Settings.Secure.putInt(cr,
649 Settings.Secure.WIFI_AP_SECURITY,
650 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
651 if (isWpa)
652 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
653 }
654
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800655 /**
656 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
657 * and soft access point configured as a single operation.
658 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800659 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800660 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800661 * @return {@code true} if the operation succeeds (or if the existing state
662 * is the same as the requested state)
663 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800664 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800665 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800666 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
667
668 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800669 /* Configuration changed on a running access point */
670 if(enable && (wifiConfig != null)) {
671 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700672 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
673 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700674 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800675 return true;
676 } catch(Exception e) {
677 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700678 try {
679 nwService.stopAccessPoint();
680 } catch (Exception ee) {
681 Slog.e(TAG, "Could not stop AP, :" + ee);
682 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800683 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
684 return false;
685 }
686 } else {
687 return true;
688 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800689 }
690
Irfan Sherifff91444c2010-03-24 12:11:00 -0700691 /**
692 * Fail AP if Wifi is enabled
693 */
694 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
695 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
696 return false;
697 }
698
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800699 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
700 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800701
702 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800703
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800704 /* Use default config if there is no existing config */
705 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
706 wifiConfig = new WifiConfiguration();
707 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
708 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
709 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800710
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800711 if (!mWifiStateTracker.loadDriver()) {
712 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800713 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800714 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800715 }
716
717 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700718 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
719 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800720 } catch(Exception e) {
721 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800722 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
723 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800724 }
725
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700726 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700727
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800728 } else {
729
730 try {
731 nwService.stopAccessPoint();
732 } catch(Exception e) {
733 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800734 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
735 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800736 }
737
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800738 if (!mWifiStateTracker.unloadDriver()) {
739 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800740 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800741 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 }
743 }
744
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800745 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800746 return true;
747 }
748
749 /**
750 * see {@link WifiManager#getWifiApState()}
751 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
752 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
753 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
754 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
755 * {@link WifiManager#WIFI_AP_STATE_FAILED}
756 */
757 public int getWifiApEnabledState() {
758 enforceAccessPermission();
759 return mWifiApState;
760 }
761
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800762 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800763 final int previousWifiApState = mWifiApState;
764
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800765 /**
766 * Unload the driver if going to a failed state
767 */
768 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
769 mWifiStateTracker.unloadDriver();
770 }
771
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800772 long ident = Binder.clearCallingIdentity();
773 try {
774 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
775 mBatteryStats.noteWifiOn(uid);
776 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
777 mBatteryStats.noteWifiOff(uid);
778 }
779 } catch (RemoteException e) {
780 } finally {
781 Binder.restoreCallingIdentity(ident);
782 }
783
784 // Update state
785 mWifiApState = wifiAPState;
786
787 // Broadcast
788 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
789 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
790 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
791 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
792 mContext.sendStickyBroadcast(intent);
793 }
794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 /**
796 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
797 * @return the list of configured networks
798 */
799 public List<WifiConfiguration> getConfiguredNetworks() {
800 enforceAccessPermission();
801 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 /*
804 * We don't cache the list, because we want to allow
805 * for the possibility that the configuration file
806 * has been modified through some external means,
807 * such as the wpa_cli command line program.
808 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800809 listStr = mWifiStateTracker.listNetworks();
810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 List<WifiConfiguration> networks =
812 new ArrayList<WifiConfiguration>();
813 if (listStr == null)
814 return networks;
815
816 String[] lines = listStr.split("\n");
817 // Skip the first line, which is a header
818 for (int i = 1; i < lines.length; i++) {
819 String[] result = lines[i].split("\t");
820 // network-id | ssid | bssid | flags
821 WifiConfiguration config = new WifiConfiguration();
822 try {
823 config.networkId = Integer.parseInt(result[0]);
824 } catch(NumberFormatException e) {
825 continue;
826 }
827 if (result.length > 3) {
828 if (result[3].indexOf("[CURRENT]") != -1)
829 config.status = WifiConfiguration.Status.CURRENT;
830 else if (result[3].indexOf("[DISABLED]") != -1)
831 config.status = WifiConfiguration.Status.DISABLED;
832 else
833 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800834 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800837 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 networks.add(config);
839 }
840
841 return networks;
842 }
843
844 /**
845 * Read the variables from the supplicant daemon that are needed to
846 * fill in the WifiConfiguration object.
847 * <p/>
848 * The caller must hold the synchronization monitor.
849 * @param config the {@link WifiConfiguration} object to be filled in.
850 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800851 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852
853 int netId = config.networkId;
854 if (netId < 0)
855 return;
856
857 /*
858 * TODO: maybe should have a native method that takes an array of
859 * variable names and returns an array of values. But we'd still
860 * be doing a round trip to the supplicant daemon for each variable.
861 */
862 String value;
863
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800864 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800866 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 } else {
868 config.SSID = null;
869 }
870
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800871 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 if (!TextUtils.isEmpty(value)) {
873 config.BSSID = value;
874 } else {
875 config.BSSID = null;
876 }
877
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800878 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 config.priority = -1;
880 if (!TextUtils.isEmpty(value)) {
881 try {
882 config.priority = Integer.parseInt(value);
883 } catch (NumberFormatException ignore) {
884 }
885 }
886
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800887 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 config.hiddenSSID = false;
889 if (!TextUtils.isEmpty(value)) {
890 try {
891 config.hiddenSSID = Integer.parseInt(value) != 0;
892 } catch (NumberFormatException ignore) {
893 }
894 }
895
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800896 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 config.wepTxKeyIndex = -1;
898 if (!TextUtils.isEmpty(value)) {
899 try {
900 config.wepTxKeyIndex = Integer.parseInt(value);
901 } catch (NumberFormatException ignore) {
902 }
903 }
904
905 /*
906 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
907 * just a "*" if the key is set, or the null string otherwise.
908 */
909 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800910 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 if (!TextUtils.isEmpty(value)) {
912 config.wepKeys[i] = value;
913 } else {
914 config.wepKeys[i] = null;
915 }
916 }
917
918 /*
919 * Get the private shared key. Note that the actual keys are not passed back,
920 * just a "*" if the key is set, or the null string otherwise.
921 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800922 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 if (!TextUtils.isEmpty(value)) {
924 config.preSharedKey = value;
925 } else {
926 config.preSharedKey = null;
927 }
928
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800929 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 WifiConfiguration.Protocol.varName);
931 if (!TextUtils.isEmpty(value)) {
932 String vals[] = value.split(" ");
933 for (String val : vals) {
934 int index =
935 lookupString(val, WifiConfiguration.Protocol.strings);
936 if (0 <= index) {
937 config.allowedProtocols.set(index);
938 }
939 }
940 }
941
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800942 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 WifiConfiguration.KeyMgmt.varName);
944 if (!TextUtils.isEmpty(value)) {
945 String vals[] = value.split(" ");
946 for (String val : vals) {
947 int index =
948 lookupString(val, WifiConfiguration.KeyMgmt.strings);
949 if (0 <= index) {
950 config.allowedKeyManagement.set(index);
951 }
952 }
953 }
954
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800955 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 WifiConfiguration.AuthAlgorithm.varName);
957 if (!TextUtils.isEmpty(value)) {
958 String vals[] = value.split(" ");
959 for (String val : vals) {
960 int index =
961 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
962 if (0 <= index) {
963 config.allowedAuthAlgorithms.set(index);
964 }
965 }
966 }
967
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800968 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 WifiConfiguration.PairwiseCipher.varName);
970 if (!TextUtils.isEmpty(value)) {
971 String vals[] = value.split(" ");
972 for (String val : vals) {
973 int index =
974 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
975 if (0 <= index) {
976 config.allowedPairwiseCiphers.set(index);
977 }
978 }
979 }
980
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800981 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 WifiConfiguration.GroupCipher.varName);
983 if (!TextUtils.isEmpty(value)) {
984 String vals[] = value.split(" ");
985 for (String val : vals) {
986 int index =
987 lookupString(val, WifiConfiguration.GroupCipher.strings);
988 if (0 <= index) {
989 config.allowedGroupCiphers.set(index);
990 }
991 }
992 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800993
994 for (WifiConfiguration.EnterpriseField field :
995 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800996 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800997 field.varName());
998 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800999 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001000 field.setValue(value);
1001 }
1002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001005 private static String removeDoubleQuotes(String string) {
1006 if (string.length() <= 2) return "";
1007 return string.substring(1, string.length() - 1);
1008 }
1009
1010 private static String convertToQuotedString(String string) {
1011 return "\"" + string + "\"";
1012 }
1013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 /**
1015 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1016 * @return the supplicant-assigned identifier for the new or updated
1017 * network if the operation succeeds, or {@code -1} if it fails
1018 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001019 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 /*
1023 * If the supplied networkId is -1, we create a new empty
1024 * network configuration. Otherwise, the networkId should
1025 * refer to an existing configuration.
1026 */
1027 int netId = config.networkId;
1028 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001029 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001031 synchronized (mWifiStateTracker) {
1032 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001033 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001034 if (netId < 0) {
1035 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001036 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001037 }
1038 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001040 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001042 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001045 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 /*
1047 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001048 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 * will fail, so we don't bother to make a separate check
1050 * for the validity of the ID up front.
1051 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001053 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001054 netId,
1055 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001056 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001058 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 break setVariables;
1061 }
1062
1063 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001064 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001065 netId,
1066 WifiConfiguration.bssidVarName,
1067 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001069 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
1071 break setVariables;
1072 }
1073
1074 String allowedKeyManagementString =
1075 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1076 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001077 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001078 netId,
1079 WifiConfiguration.KeyMgmt.varName,
1080 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001082 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001083 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 break setVariables;
1086 }
1087
1088 String allowedProtocolsString =
1089 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1090 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001091 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001092 netId,
1093 WifiConfiguration.Protocol.varName,
1094 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001096 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001097 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099 break setVariables;
1100 }
1101
1102 String allowedAuthAlgorithmsString =
1103 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1104 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001105 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001106 netId,
1107 WifiConfiguration.AuthAlgorithm.varName,
1108 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001110 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001111 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 break setVariables;
1114 }
1115
1116 String allowedPairwiseCiphersString =
1117 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1118 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001119 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001120 netId,
1121 WifiConfiguration.PairwiseCipher.varName,
1122 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001124 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001125 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 break setVariables;
1128 }
1129
1130 String allowedGroupCiphersString =
1131 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1132 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001133 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001134 netId,
1135 WifiConfiguration.GroupCipher.varName,
1136 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001138 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001139 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141 break setVariables;
1142 }
1143
1144 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1145 // by preventing "*" as a key.
1146 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001147 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001148 netId,
1149 WifiConfiguration.pskVarName,
1150 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001152 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154 break setVariables;
1155 }
1156
1157 boolean hasSetKey = false;
1158 if (config.wepKeys != null) {
1159 for (int i = 0; i < config.wepKeys.length; i++) {
1160 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1161 // by preventing "*" as a key.
1162 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001163 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001164 netId,
1165 WifiConfiguration.wepKeyVarNames[i],
1166 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001168 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001169 "failed to set wep_key"+i+": " +
1170 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172 break setVariables;
1173 }
1174 hasSetKey = true;
1175 }
1176 }
1177 }
1178
1179 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001180 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001181 netId,
1182 WifiConfiguration.wepTxKeyIdxVarName,
1183 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001185 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001186 "failed to set wep_tx_keyidx: "+
1187 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189 break setVariables;
1190 }
1191 }
1192
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001193 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001194 netId,
1195 WifiConfiguration.priorityVarName,
1196 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001198 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001199 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201 break setVariables;
1202 }
1203
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001204 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001205 netId,
1206 WifiConfiguration.hiddenSSIDVarName,
1207 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001209 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001210 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212 break setVariables;
1213 }
1214
Chung-yih Wang43374762009-09-16 14:28:42 +08001215 for (WifiConfiguration.EnterpriseField field
1216 : config.enterpriseFields) {
1217 String varName = field.varName();
1218 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001219 if (value != null) {
1220 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001221 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001222 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001223 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001224 netId,
1225 varName,
1226 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001227 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001228 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001229 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001230 }
1231 break setVariables;
1232 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001233 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001238 /*
1239 * For an update, if one of the setNetworkVariable operations fails,
1240 * we might want to roll back all the changes already made. But the
1241 * chances are that if anything is going to go wrong, it'll happen
1242 * the first time we try to set one of the variables.
1243 */
1244 if (newNetwork) {
1245 removeNetwork(netId);
1246 if (DBG) {
1247 Slog.d(TAG,
1248 "Failed to set a network variable, removed network: "
1249 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
1251 }
1252 return -1;
1253 }
1254
1255 private static String makeString(BitSet set, String[] strings) {
1256 StringBuffer buf = new StringBuffer();
1257 int nextSetBit = -1;
1258
1259 /* Make sure all set bits are in [0, strings.length) to avoid
1260 * going out of bounds on strings. (Shouldn't happen, but...) */
1261 set = set.get(0, strings.length);
1262
1263 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1264 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1265 }
1266
1267 // remove trailing space
1268 if (set.cardinality() > 0) {
1269 buf.setLength(buf.length() - 1);
1270 }
1271
1272 return buf.toString();
1273 }
1274
1275 private static int lookupString(String string, String[] strings) {
1276 int size = strings.length;
1277
1278 string = string.replace('-', '_');
1279
1280 for (int i = 0; i < size; i++)
1281 if (string.equals(strings[i]))
1282 return i;
1283
1284 if (DBG) {
1285 // if we ever get here, we should probably add the
1286 // value to WifiConfiguration to reflect that it's
1287 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001288 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
1290
1291 return -1;
1292 }
1293
1294 /**
1295 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1296 * @param netId the integer that identifies the network configuration
1297 * to the supplicant
1298 * @return {@code true} if the operation succeeded
1299 */
1300 public boolean removeNetwork(int netId) {
1301 enforceChangePermission();
1302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 return mWifiStateTracker.removeNetwork(netId);
1304 }
1305
1306 /**
1307 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1308 * @param netId the integer that identifies the network configuration
1309 * to the supplicant
1310 * @param disableOthers if true, disable all other networks.
1311 * @return {@code true} if the operation succeeded
1312 */
1313 public boolean enableNetwork(int netId, boolean disableOthers) {
1314 enforceChangePermission();
1315
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001316 String ifname = mWifiStateTracker.getInterfaceName();
1317 NetworkUtils.enableInterface(ifname);
1318 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1319 if (!result) {
1320 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001322 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
1325 /**
1326 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1327 * @param netId the integer that identifies the network configuration
1328 * to the supplicant
1329 * @return {@code true} if the operation succeeded
1330 */
1331 public boolean disableNetwork(int netId) {
1332 enforceChangePermission();
1333
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001334 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336
1337 /**
1338 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1339 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1340 */
1341 public WifiInfo getConnectionInfo() {
1342 enforceAccessPermission();
1343 /*
1344 * Make sure we have the latest information, by sending
1345 * a status request to the supplicant.
1346 */
1347 return mWifiStateTracker.requestConnectionInfo();
1348 }
1349
1350 /**
1351 * Return the results of the most recent access point scan, in the form of
1352 * a list of {@link ScanResult} objects.
1353 * @return the list of results
1354 */
1355 public List<ScanResult> getScanResults() {
1356 enforceAccessPermission();
1357 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001358
1359 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 if (reply == null) {
1361 return null;
1362 }
1363
1364 List<ScanResult> scanList = new ArrayList<ScanResult>();
1365
1366 int lineCount = 0;
1367
1368 int replyLen = reply.length();
1369 // Parse the result string, keeping in mind that the last line does
1370 // not end with a newline.
1371 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1372 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1373 ++lineCount;
1374 /*
1375 * Skip the first line, which is a header
1376 */
1377 if (lineCount == 1) {
1378 lineBeg = lineEnd + 1;
1379 continue;
1380 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001381 if (lineEnd > lineBeg) {
1382 String line = reply.substring(lineBeg, lineEnd);
1383 ScanResult scanResult = parseScanResult(line);
1384 if (scanResult != null) {
1385 scanList.add(scanResult);
1386 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001387 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389 }
1390 lineBeg = lineEnd + 1;
1391 }
1392 }
1393 mWifiStateTracker.setScanResultsList(scanList);
1394 return scanList;
1395 }
1396
1397 /**
1398 * Parse the scan result line passed to us by wpa_supplicant (helper).
1399 * @param line the line to parse
1400 * @return the {@link ScanResult} object
1401 */
1402 private ScanResult parseScanResult(String line) {
1403 ScanResult scanResult = null;
1404 if (line != null) {
1405 /*
1406 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1407 * must synchronized here!
1408 */
1409 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001410 String[] result = scanResultPattern.split(line);
1411 if (3 <= result.length && result.length <= 5) {
1412 String bssid = result[0];
1413 // bssid | frequency | level | flags | ssid
1414 int frequency;
1415 int level;
1416 try {
1417 frequency = Integer.parseInt(result[1]);
1418 level = Integer.parseInt(result[2]);
1419 /* some implementations avoid negative values by adding 256
1420 * so we need to adjust for that here.
1421 */
1422 if (level > 0) level -= 256;
1423 } catch (NumberFormatException e) {
1424 frequency = 0;
1425 level = 0;
1426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
Mike Lockwood1a645052009-06-25 13:01:12 -04001428 /*
1429 * The formatting of the results returned by
1430 * wpa_supplicant is intended to make the fields
1431 * line up nicely when printed,
1432 * not to make them easy to parse. So we have to
1433 * apply some heuristics to figure out which field
1434 * is the SSID and which field is the flags.
1435 */
1436 String ssid;
1437 String flags;
1438 if (result.length == 4) {
1439 if (result[3].charAt(0) == '[') {
1440 flags = result[3];
1441 ssid = "";
1442 } else {
1443 flags = "";
1444 ssid = result[3];
1445 }
1446 } else if (result.length == 5) {
1447 flags = result[3];
1448 ssid = result[4];
1449 } else {
1450 // Here, we must have 3 fields: no flags and ssid
1451 // set
1452 flags = "";
1453 ssid = "";
1454 }
1455
Mike Lockwood00717e22009-08-17 10:09:36 -04001456 // bssid + ssid is the hash key
1457 String key = bssid + ssid;
1458 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001459 if (scanResult != null) {
1460 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001461 scanResult.SSID = ssid;
1462 scanResult.capabilities = flags;
1463 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001464 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 // Do not add scan results that have no SSID set
1466 if (0 < ssid.trim().length()) {
1467 scanResult =
1468 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001469 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001470 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001473 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001474 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001475 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477 }
1478 }
1479
1480 return scanResult;
1481 }
1482
1483 /**
1484 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1485 * and construct a {@code WifiConfiguration} that describes the encryption,
1486 * key management, and authenticaion capabilities of the access point.
1487 * @param flags the string returned by wpa_supplicant
1488 * @return the {@link WifiConfiguration} object, filled in
1489 */
1490 WifiConfiguration parseScanFlags(String flags) {
1491 WifiConfiguration config = new WifiConfiguration();
1492
1493 if (flags.length() == 0) {
1494 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1495 }
1496 // ... to be implemented
1497 return config;
1498 }
1499
1500 /**
1501 * Tell the supplicant to persist the current list of configured networks.
1502 * @return {@code true} if the operation succeeded
1503 */
1504 public boolean saveConfiguration() {
1505 boolean result;
1506 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001509 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if (result && mNeedReconfig) {
1511 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001512 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513
1514 if (result) {
1515 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1516 mContext.sendBroadcast(intent);
1517 }
1518 }
1519 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001520 // Inform the backup manager about a data change
1521 IBackupManager ibm = IBackupManager.Stub.asInterface(
1522 ServiceManager.getService(Context.BACKUP_SERVICE));
1523 if (ibm != null) {
1524 try {
1525 ibm.dataChanged("com.android.providers.settings");
1526 } catch (Exception e) {
1527 // Try again later
1528 }
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 return result;
1531 }
1532
1533 /**
1534 * Set the number of radio frequency channels that are allowed to be used
1535 * in the current regulatory domain. This method should be used only
1536 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001537 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 * persisted as a Secure setting.
1539 * @param numChannels the number of allowed channels. Must be greater than 0
1540 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001541 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1543 * {@code numChannels} is outside the valid range.
1544 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001545 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001547 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 /*
1551 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1552 * but if Wi-Fi isn't currently enabled, that's not possible, and
1553 * we want to persist the setting anyway,so that it will take
1554 * effect when Wi-Fi does become enabled.
1555 */
1556 boolean found = false;
1557 for (int validChan : sValidRegulatoryChannelCounts) {
1558 if (validChan == numChannels) {
1559 found = true;
1560 break;
1561 }
1562 }
1563 if (!found) {
1564 return false;
1565 }
1566
Irfan Sheriff59610c02010-03-30 11:00:41 -07001567 if (mWifiHandler == null) return false;
1568
1569 Message.obtain(mWifiHandler,
1570 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1571
1572 return true;
1573 }
1574
1575 /**
1576 * sets the number of allowed radio frequency channels synchronously
1577 * @param numChannels the number of allowed channels. Must be greater than 0
1578 * and less than or equal to 16.
1579 * @param persist {@code true} if the setting should be remembered.
1580 * @return {@code true} if the operation succeeds, {@code false} otherwise
1581 */
1582 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001583 if (persist) {
1584 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001585 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1586 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001587 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001588 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 /**
1592 * Return the number of frequency channels that are allowed
1593 * to be used in the current regulatory domain.
1594 * @return the number of allowed channels, or {@code -1} if an error occurs
1595 */
1596 public int getNumAllowedChannels() {
1597 int numChannels;
1598
1599 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001600
1601 /*
1602 * If we can't get the value from the driver (e.g., because
1603 * Wi-Fi is not currently enabled), get the value from
1604 * Settings.
1605 */
1606 numChannels = mWifiStateTracker.getNumAllowedChannels();
1607 if (numChannels < 0) {
1608 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1609 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1610 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 return numChannels;
1613 }
1614
1615 /**
1616 * Return the list of valid values for the number of allowed radio channels
1617 * for various regulatory domains.
1618 * @return the list of channel counts
1619 */
1620 public int[] getValidChannelCounts() {
1621 enforceAccessPermission();
1622 return sValidRegulatoryChannelCounts;
1623 }
1624
1625 /**
1626 * Return the DHCP-assigned addresses from the last successful DHCP request,
1627 * if any.
1628 * @return the DHCP information
1629 */
1630 public DhcpInfo getDhcpInfo() {
1631 enforceAccessPermission();
1632 return mWifiStateTracker.getDhcpInfo();
1633 }
1634
1635 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1636 @Override
1637 public void onReceive(Context context, Intent intent) {
1638 String action = intent.getAction();
1639
Doug Zongker43866e02010-01-07 12:09:54 -08001640 long idleMillis =
1641 Settings.Secure.getLong(mContext.getContentResolver(),
1642 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001644 Settings.System.getInt(mContext.getContentResolver(),
1645 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 mAlarmManager.cancel(mIdleIntent);
1649 mDeviceIdle = false;
1650 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001651 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001653 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001655 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 /*
1657 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1658 * AND the "stay on while plugged in" setting doesn't match the
1659 * current power conditions (i.e, not plugged in, plugged in to USB,
1660 * or plugged in to AC).
1661 */
1662 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001663 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1664 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001665 // we used to go to sleep immediately, but this caused some race conditions
1666 // we don't have time to track down for this release. Delay instead, but not
1667 // as long as we would if connected (below)
1668 // TODO - fix the race conditions and switch back to the immediate turn-off
1669 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001670 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001671 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1672 // // do not keep Wifi awake when screen is off if Wifi is not associated
1673 // mDeviceIdle = true;
1674 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001675 } else {
1676 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001677 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001678 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681 /* we can return now -- there's nothing to do until we get the idle intent back */
1682 return;
1683 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mDeviceIdle = true;
1686 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1687 /*
1688 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1689 * AND we are transitioning from a state in which the device was supposed
1690 * to stay awake to a state in which it is not supposed to stay awake.
1691 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1692 * the already-set timer.
1693 */
1694 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001695 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1697 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1698 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001699 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1701 mPluggedType = pluggedType;
1702 return;
1703 }
1704 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001705 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001706 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1707 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1708 boolean isBluetoothPlaying = false;
1709 for (BluetoothDevice sink : sinks) {
1710 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1711 isBluetoothPlaying = true;
1712 }
1713 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001714 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 } else {
1717 return;
1718 }
1719
1720 updateWifiState();
1721 }
1722
1723 /**
1724 * Determines whether the Wi-Fi chipset should stay awake or be put to
1725 * sleep. Looks at the setting for the sleep policy and the current
1726 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001727 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 * @see #shouldDeviceStayAwake(int, int)
1729 */
1730 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1731 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1732 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1733
1734 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1735 // Never sleep
1736 return true;
1737 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1738 (pluggedType != 0)) {
1739 // Never sleep while plugged, and we're plugged
1740 return true;
1741 } else {
1742 // Default
1743 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1744 }
1745 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 /**
1748 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1749 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1750 * of {@code 0} isn't really a plugged type, but rather an indication that the
1751 * device isn't plugged in at all, there is no bit value corresponding to a
1752 * {@code pluggedType} value of {@code 0}. That is why we shift by
1753 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1754 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1755 * keep the device (and hence Wi-Fi) awake.
1756 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1757 * being made
1758 * @return {@code true} if {@code pluggedType} indicates that the device is
1759 * supposed to stay awake, {@code false} otherwise.
1760 */
1761 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1762 return (stayAwakeConditions & pluggedType) != 0;
1763 }
1764 };
1765
Dianne Hackborn617f8772009-03-31 15:04:46 -07001766 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 Message msg = Message.obtain(mWifiHandler,
1768 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001769 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 msg.sendToTarget();
1771 }
1772
1773 private void sendStartMessage(boolean scanOnlyMode) {
1774 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1775 }
1776
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001777 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1778 Message.obtain(mWifiHandler,
1779 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001780 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001784 // send a message so it's all serialized
1785 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1786 }
1787
1788 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001790 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 boolean lockHeld = mLocks.hasLocks();
1792 int strongestLockMode;
1793 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1794 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1795 if (mDeviceIdle && lockHeld) {
1796 strongestLockMode = mLocks.getStrongestLockMode();
1797 } else {
1798 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1799 }
1800
1801 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001802 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 return;
1804 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001805
1806 /* Disable tethering when airplane mode is enabled */
1807 if (airplaneMode &&
1808 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1809 sWakeLock.acquire();
1810 sendAccessPointMessage(false, null, mLastApEnableUid);
1811 }
1812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (wifiShouldBeEnabled) {
1814 if (wifiShouldBeStarted) {
1815 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001816 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 sWakeLock.acquire();
1818 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001819 } else if (!mWifiStateTracker.isDriverStopped()) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001820 if (mCm == null) {
1821 mCm = (ConnectivityManager)mContext.
1822 getSystemService(Context.CONNECTIVITY_SERVICE);
1823 }
1824 mCm.requestNetworkTransitionWakelock(TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 } else {
1828 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001829 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831 }
1832 }
1833
1834 private void registerForBroadcasts() {
1835 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1837 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1838 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1839 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001840 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 mContext.registerReceiver(mReceiver, intentFilter);
1842 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 private boolean isAirplaneSensitive() {
1845 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1846 Settings.System.AIRPLANE_MODE_RADIOS);
1847 return airplaneModeRadios == null
1848 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1849 }
1850
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001851 private boolean isAirplaneToggleable() {
1852 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1853 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1854 return toggleableRadios != null
1855 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1856 }
1857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 /**
1859 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1860 * currently on.
1861 * @return {@code true} if airplane mode is on.
1862 */
1863 private boolean isAirplaneModeOn() {
1864 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1865 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1866 }
1867
1868 /**
1869 * Handler that allows posting to the WifiThread.
1870 */
1871 private class WifiHandler extends Handler {
1872 public WifiHandler(Looper looper) {
1873 super(looper);
1874 }
1875
1876 @Override
1877 public void handleMessage(Message msg) {
1878 switch (msg.what) {
1879
1880 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001881 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001882 if (mWifiWatchdogService == null) {
1883 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 sWakeLock.release();
1886 break;
1887
1888 case MESSAGE_START_WIFI:
1889 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1890 mWifiStateTracker.restart();
1891 sWakeLock.release();
1892 break;
1893
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001894 case MESSAGE_UPDATE_STATE:
1895 doUpdateWifiState();
1896 break;
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 case MESSAGE_DISABLE_WIFI:
1899 // a non-zero msg.arg1 value means the "enabled" setting
1900 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001901 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001902 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 sWakeLock.release();
1904 break;
1905
1906 case MESSAGE_STOP_WIFI:
1907 mWifiStateTracker.disconnectAndStop();
1908 // don't release wakelock
1909 break;
1910
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001911 case MESSAGE_START_ACCESS_POINT:
1912 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001913 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001914 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001915 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001916 break;
1917
1918 case MESSAGE_STOP_ACCESS_POINT:
1919 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001920 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001921 (WifiConfiguration) msg.obj);
1922 sWakeLock.release();
1923 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001924
1925 case MESSAGE_SET_CHANNELS:
1926 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1927 break;
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930 }
1931 }
1932
1933 @Override
1934 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1935 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1936 != PackageManager.PERMISSION_GRANTED) {
1937 pw.println("Permission Denial: can't dump WifiService from from pid="
1938 + Binder.getCallingPid()
1939 + ", uid=" + Binder.getCallingUid());
1940 return;
1941 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001942 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 pw.println("Stay-awake conditions: " +
1944 Settings.System.getInt(mContext.getContentResolver(),
1945 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1946 pw.println();
1947
1948 pw.println("Internal state:");
1949 pw.println(mWifiStateTracker);
1950 pw.println();
1951 pw.println("Latest scan results:");
1952 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1953 if (scanResults != null && scanResults.size() != 0) {
1954 pw.println(" BSSID Frequency RSSI Flags SSID");
1955 for (ScanResult r : scanResults) {
1956 pw.printf(" %17s %9d %5d %-16s %s%n",
1957 r.BSSID,
1958 r.frequency,
1959 r.level,
1960 r.capabilities,
1961 r.SSID == null ? "" : r.SSID);
1962 }
1963 }
1964 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001965 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1966 mScanLocksAcquired + " scan");
1967 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1968 mScanLocksReleased + " scan");
1969 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 pw.println("Locks held:");
1971 mLocks.dump(pw);
1972 }
1973
1974 private static String stateName(int wifiState) {
1975 switch (wifiState) {
1976 case WIFI_STATE_DISABLING:
1977 return "disabling";
1978 case WIFI_STATE_DISABLED:
1979 return "disabled";
1980 case WIFI_STATE_ENABLING:
1981 return "enabling";
1982 case WIFI_STATE_ENABLED:
1983 return "enabled";
1984 case WIFI_STATE_UNKNOWN:
1985 return "unknown state";
1986 default:
1987 return "[invalid state]";
1988 }
1989 }
1990
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001991 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001993 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
1996 public void binderDied() {
1997 synchronized (mLocks) {
1998 releaseWifiLockLocked(mBinder);
1999 }
2000 }
2001
2002 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002003 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005 }
2006
2007 private class LockList {
2008 private List<WifiLock> mList;
2009
2010 private LockList() {
2011 mList = new ArrayList<WifiLock>();
2012 }
2013
2014 private synchronized boolean hasLocks() {
2015 return !mList.isEmpty();
2016 }
2017
2018 private synchronized int getStrongestLockMode() {
2019 if (mList.isEmpty()) {
2020 return WifiManager.WIFI_MODE_FULL;
2021 }
2022 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002023 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 return WifiManager.WIFI_MODE_FULL;
2025 }
2026 }
2027 return WifiManager.WIFI_MODE_SCAN_ONLY;
2028 }
2029
2030 private void addLock(WifiLock lock) {
2031 if (findLockByBinder(lock.mBinder) < 0) {
2032 mList.add(lock);
2033 }
2034 }
2035
2036 private WifiLock removeLock(IBinder binder) {
2037 int index = findLockByBinder(binder);
2038 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002039 WifiLock ret = mList.remove(index);
2040 ret.unlinkDeathRecipient();
2041 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 } else {
2043 return null;
2044 }
2045 }
2046
2047 private int findLockByBinder(IBinder binder) {
2048 int size = mList.size();
2049 for (int i = size - 1; i >= 0; i--)
2050 if (mList.get(i).mBinder == binder)
2051 return i;
2052 return -1;
2053 }
2054
2055 private void dump(PrintWriter pw) {
2056 for (WifiLock l : mList) {
2057 pw.print(" ");
2058 pw.println(l);
2059 }
2060 }
2061 }
2062
2063 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2064 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2065 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
2066 return false;
2067 }
2068 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2069 synchronized (mLocks) {
2070 return acquireWifiLockLocked(wifiLock);
2071 }
2072 }
2073
2074 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002075 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002078
The Android Open Source Project10592532009-03-18 17:39:46 -07002079 int uid = Binder.getCallingUid();
2080 long ident = Binder.clearCallingIdentity();
2081 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002082 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002083 case WifiManager.WIFI_MODE_FULL:
2084 ++mFullLocksAcquired;
2085 mBatteryStats.noteFullWifiLockAcquired(uid);
2086 break;
2087 case WifiManager.WIFI_MODE_SCAN_ONLY:
2088 ++mScanLocksAcquired;
2089 mBatteryStats.noteScanWifiLockAcquired(uid);
2090 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002091 }
2092 } catch (RemoteException e) {
2093 } finally {
2094 Binder.restoreCallingIdentity(ident);
2095 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 updateWifiState();
2098 return true;
2099 }
2100
2101 public boolean releaseWifiLock(IBinder lock) {
2102 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2103 synchronized (mLocks) {
2104 return releaseWifiLockLocked(lock);
2105 }
2106 }
2107
2108 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002109 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002110
The Android Open Source Project10592532009-03-18 17:39:46 -07002111 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002112
Joe Onorato8a9b2202010-02-26 18:56:32 -08002113 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002114
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002115 hadLock = (wifiLock != null);
2116
2117 if (hadLock) {
2118 int uid = Binder.getCallingUid();
2119 long ident = Binder.clearCallingIdentity();
2120 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002121 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002122 case WifiManager.WIFI_MODE_FULL:
2123 ++mFullLocksReleased;
2124 mBatteryStats.noteFullWifiLockReleased(uid);
2125 break;
2126 case WifiManager.WIFI_MODE_SCAN_ONLY:
2127 ++mScanLocksReleased;
2128 mBatteryStats.noteScanWifiLockReleased(uid);
2129 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002130 }
2131 } catch (RemoteException e) {
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002134 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002135 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002136 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002138 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002140
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002141 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002142 implements IBinder.DeathRecipient {
2143 String mTag;
2144 int mMode;
2145 IBinder mBinder;
2146
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002147 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002148 super();
2149 mTag = tag;
2150 mMode = mode;
2151 mBinder = binder;
2152 try {
2153 mBinder.linkToDeath(this, 0);
2154 } catch (RemoteException e) {
2155 binderDied();
2156 }
2157 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002158
2159 void unlinkDeathRecipient() {
2160 mBinder.unlinkToDeath(this, 0);
2161 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002162 }
2163
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002164 private class Multicaster extends DeathRecipient {
2165 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002166 super(Binder.getCallingUid(), tag, binder);
2167 }
2168
2169 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002170 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002171 synchronized (mMulticasters) {
2172 int i = mMulticasters.indexOf(this);
2173 if (i != -1) {
2174 removeMulticasterLocked(i, mMode);
2175 }
2176 }
2177 }
2178
2179 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002180 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002181 }
2182
2183 public int getUid() {
2184 return mMode;
2185 }
2186 }
2187
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002188 public void initializeMulticastFiltering() {
2189 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002190
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002191 synchronized (mMulticasters) {
2192 // if anybody had requested filters be off, leave off
2193 if (mMulticasters.size() != 0) {
2194 return;
2195 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002196 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002197 }
2198 }
2199 }
2200
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002201 public void acquireMulticastLock(IBinder binder, String tag) {
2202 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002203
2204 synchronized (mMulticasters) {
2205 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002206 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002207 // Note that we could call stopPacketFiltering only when
2208 // our new size == 1 (first call), but this function won't
2209 // be called often and by making the stopPacket call each
2210 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002211 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002212 }
2213
2214 int uid = Binder.getCallingUid();
2215 Long ident = Binder.clearCallingIdentity();
2216 try {
2217 mBatteryStats.noteWifiMulticastEnabled(uid);
2218 } catch (RemoteException e) {
2219 } finally {
2220 Binder.restoreCallingIdentity(ident);
2221 }
2222 }
2223
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002224 public void releaseMulticastLock() {
2225 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002226
2227 int uid = Binder.getCallingUid();
2228 synchronized (mMulticasters) {
2229 mMulticastDisabled++;
2230 int size = mMulticasters.size();
2231 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002232 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002233 if ((m != null) && (m.getUid() == uid)) {
2234 removeMulticasterLocked(i, uid);
2235 }
2236 }
2237 }
2238 }
2239
2240 private void removeMulticasterLocked(int i, int uid)
2241 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002242 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002243
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002244 if (removed != null) {
2245 removed.unlinkDeathRecipient();
2246 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002247 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002248 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002249 }
2250
2251 Long ident = Binder.clearCallingIdentity();
2252 try {
2253 mBatteryStats.noteWifiMulticastDisabled(uid);
2254 } catch (RemoteException e) {
2255 } finally {
2256 Binder.restoreCallingIdentity(ident);
2257 }
2258 }
2259
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002260 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002261 enforceAccessPermission();
2262
2263 synchronized (mMulticasters) {
2264 return (mMulticasters.size() > 0);
2265 }
2266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267}