blob: 6d9888b24526c70f99955287aae7b3d90a7da243 [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() {
622 final ContentResolver cr = mContext.getContentResolver();
623 WifiConfiguration wifiConfig = new WifiConfiguration();
624 int authType;
625 try {
626 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
627 if (wifiConfig.SSID == null)
628 return null;
629 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
630 wifiConfig.allowedKeyManagement.set(authType);
631 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
632 return wifiConfig;
633 } catch (Settings.SettingNotFoundException e) {
634 Slog.e(TAG,"AP settings not found, returning");
635 return null;
636 }
637 }
638
639 private void persistApConfiguration(WifiConfiguration wifiConfig) {
640 final ContentResolver cr = mContext.getContentResolver();
641 boolean isWpa;
642 if (wifiConfig == null)
643 return;
644 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
645 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
646 Settings.Secure.putInt(cr,
647 Settings.Secure.WIFI_AP_SECURITY,
648 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
649 if (isWpa)
650 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
651 }
652
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800653 /**
654 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
655 * and soft access point configured as a single operation.
656 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800657 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800658 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800659 * @return {@code true} if the operation succeeds (or if the existing state
660 * is the same as the requested state)
661 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800662 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800663 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800664 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
665
666 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800667 /* Configuration changed on a running access point */
668 if(enable && (wifiConfig != null)) {
669 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700670 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
671 SOFTAP_IFACE);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700672 persistApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800673 return true;
674 } catch(Exception e) {
675 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700676 try {
677 nwService.stopAccessPoint();
678 } catch (Exception ee) {
679 Slog.e(TAG, "Could not stop AP, :" + ee);
680 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800681 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
682 return false;
683 }
684 } else {
685 return true;
686 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800687 }
688
Irfan Sherifff91444c2010-03-24 12:11:00 -0700689 /**
690 * Fail AP if Wifi is enabled
691 */
692 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
693 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
694 return false;
695 }
696
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800697 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
698 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800699
700 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800701
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800702 /* Use default config if there is no existing config */
703 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
704 wifiConfig = new WifiConfiguration();
705 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
706 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
707 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800708
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800709 if (!mWifiStateTracker.loadDriver()) {
710 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800711 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800712 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800713 }
714
715 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700716 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
717 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800718 } catch(Exception e) {
719 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800720 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
721 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800722 }
723
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700724 persistApConfiguration(wifiConfig);
725
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800726 } else {
727
728 try {
729 nwService.stopAccessPoint();
730 } catch(Exception e) {
731 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800732 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
733 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800734 }
735
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800736 if (!mWifiStateTracker.unloadDriver()) {
737 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800738 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800739 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800740 }
741 }
742
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800743 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800744 return true;
745 }
746
747 /**
748 * see {@link WifiManager#getWifiApState()}
749 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
750 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
751 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
752 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
753 * {@link WifiManager#WIFI_AP_STATE_FAILED}
754 */
755 public int getWifiApEnabledState() {
756 enforceAccessPermission();
757 return mWifiApState;
758 }
759
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800760 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800761 final int previousWifiApState = mWifiApState;
762
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800763 /**
764 * Unload the driver if going to a failed state
765 */
766 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
767 mWifiStateTracker.unloadDriver();
768 }
769
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800770 long ident = Binder.clearCallingIdentity();
771 try {
772 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
773 mBatteryStats.noteWifiOn(uid);
774 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
775 mBatteryStats.noteWifiOff(uid);
776 }
777 } catch (RemoteException e) {
778 } finally {
779 Binder.restoreCallingIdentity(ident);
780 }
781
782 // Update state
783 mWifiApState = wifiAPState;
784
785 // Broadcast
786 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
787 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
788 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
789 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
790 mContext.sendStickyBroadcast(intent);
791 }
792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 /**
794 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
795 * @return the list of configured networks
796 */
797 public List<WifiConfiguration> getConfiguredNetworks() {
798 enforceAccessPermission();
799 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 /*
802 * We don't cache the list, because we want to allow
803 * for the possibility that the configuration file
804 * has been modified through some external means,
805 * such as the wpa_cli command line program.
806 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800807 listStr = mWifiStateTracker.listNetworks();
808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 List<WifiConfiguration> networks =
810 new ArrayList<WifiConfiguration>();
811 if (listStr == null)
812 return networks;
813
814 String[] lines = listStr.split("\n");
815 // Skip the first line, which is a header
816 for (int i = 1; i < lines.length; i++) {
817 String[] result = lines[i].split("\t");
818 // network-id | ssid | bssid | flags
819 WifiConfiguration config = new WifiConfiguration();
820 try {
821 config.networkId = Integer.parseInt(result[0]);
822 } catch(NumberFormatException e) {
823 continue;
824 }
825 if (result.length > 3) {
826 if (result[3].indexOf("[CURRENT]") != -1)
827 config.status = WifiConfiguration.Status.CURRENT;
828 else if (result[3].indexOf("[DISABLED]") != -1)
829 config.status = WifiConfiguration.Status.DISABLED;
830 else
831 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800832 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800835 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 networks.add(config);
837 }
838
839 return networks;
840 }
841
842 /**
843 * Read the variables from the supplicant daemon that are needed to
844 * fill in the WifiConfiguration object.
845 * <p/>
846 * The caller must hold the synchronization monitor.
847 * @param config the {@link WifiConfiguration} object to be filled in.
848 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800849 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
851 int netId = config.networkId;
852 if (netId < 0)
853 return;
854
855 /*
856 * TODO: maybe should have a native method that takes an array of
857 * variable names and returns an array of values. But we'd still
858 * be doing a round trip to the supplicant daemon for each variable.
859 */
860 String value;
861
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800862 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800864 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } else {
866 config.SSID = null;
867 }
868
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800869 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 if (!TextUtils.isEmpty(value)) {
871 config.BSSID = value;
872 } else {
873 config.BSSID = null;
874 }
875
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800876 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 config.priority = -1;
878 if (!TextUtils.isEmpty(value)) {
879 try {
880 config.priority = Integer.parseInt(value);
881 } catch (NumberFormatException ignore) {
882 }
883 }
884
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800885 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 config.hiddenSSID = false;
887 if (!TextUtils.isEmpty(value)) {
888 try {
889 config.hiddenSSID = Integer.parseInt(value) != 0;
890 } catch (NumberFormatException ignore) {
891 }
892 }
893
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800894 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 config.wepTxKeyIndex = -1;
896 if (!TextUtils.isEmpty(value)) {
897 try {
898 config.wepTxKeyIndex = Integer.parseInt(value);
899 } catch (NumberFormatException ignore) {
900 }
901 }
902
903 /*
904 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
905 * just a "*" if the key is set, or the null string otherwise.
906 */
907 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800908 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 if (!TextUtils.isEmpty(value)) {
910 config.wepKeys[i] = value;
911 } else {
912 config.wepKeys[i] = null;
913 }
914 }
915
916 /*
917 * Get the private shared key. Note that the actual keys are not passed back,
918 * just a "*" if the key is set, or the null string otherwise.
919 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800920 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (!TextUtils.isEmpty(value)) {
922 config.preSharedKey = value;
923 } else {
924 config.preSharedKey = null;
925 }
926
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800927 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 WifiConfiguration.Protocol.varName);
929 if (!TextUtils.isEmpty(value)) {
930 String vals[] = value.split(" ");
931 for (String val : vals) {
932 int index =
933 lookupString(val, WifiConfiguration.Protocol.strings);
934 if (0 <= index) {
935 config.allowedProtocols.set(index);
936 }
937 }
938 }
939
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800940 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 WifiConfiguration.KeyMgmt.varName);
942 if (!TextUtils.isEmpty(value)) {
943 String vals[] = value.split(" ");
944 for (String val : vals) {
945 int index =
946 lookupString(val, WifiConfiguration.KeyMgmt.strings);
947 if (0 <= index) {
948 config.allowedKeyManagement.set(index);
949 }
950 }
951 }
952
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800953 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 WifiConfiguration.AuthAlgorithm.varName);
955 if (!TextUtils.isEmpty(value)) {
956 String vals[] = value.split(" ");
957 for (String val : vals) {
958 int index =
959 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
960 if (0 <= index) {
961 config.allowedAuthAlgorithms.set(index);
962 }
963 }
964 }
965
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800966 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 WifiConfiguration.PairwiseCipher.varName);
968 if (!TextUtils.isEmpty(value)) {
969 String vals[] = value.split(" ");
970 for (String val : vals) {
971 int index =
972 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
973 if (0 <= index) {
974 config.allowedPairwiseCiphers.set(index);
975 }
976 }
977 }
978
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800979 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 WifiConfiguration.GroupCipher.varName);
981 if (!TextUtils.isEmpty(value)) {
982 String vals[] = value.split(" ");
983 for (String val : vals) {
984 int index =
985 lookupString(val, WifiConfiguration.GroupCipher.strings);
986 if (0 <= index) {
987 config.allowedGroupCiphers.set(index);
988 }
989 }
990 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800991
992 for (WifiConfiguration.EnterpriseField field :
993 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800994 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800995 field.varName());
996 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800997 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800998 field.setValue(value);
999 }
1000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001003 private static String removeDoubleQuotes(String string) {
1004 if (string.length() <= 2) return "";
1005 return string.substring(1, string.length() - 1);
1006 }
1007
1008 private static String convertToQuotedString(String string) {
1009 return "\"" + string + "\"";
1010 }
1011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 /**
1013 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1014 * @return the supplicant-assigned identifier for the new or updated
1015 * network if the operation succeeds, or {@code -1} if it fails
1016 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001017 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 /*
1021 * If the supplied networkId is -1, we create a new empty
1022 * network configuration. Otherwise, the networkId should
1023 * refer to an existing configuration.
1024 */
1025 int netId = config.networkId;
1026 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001027 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001029 synchronized (mWifiStateTracker) {
1030 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001031 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001032 if (netId < 0) {
1033 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001034 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001035 }
1036 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001038 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001040 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001043 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 /*
1045 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001046 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 * will fail, so we don't bother to make a separate check
1048 * for the validity of the ID up front.
1049 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001051 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001052 netId,
1053 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001054 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001056 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058 break setVariables;
1059 }
1060
1061 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001062 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001063 netId,
1064 WifiConfiguration.bssidVarName,
1065 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001067 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069 break setVariables;
1070 }
1071
1072 String allowedKeyManagementString =
1073 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1074 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001075 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001076 netId,
1077 WifiConfiguration.KeyMgmt.varName,
1078 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001080 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001081 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
1083 break setVariables;
1084 }
1085
1086 String allowedProtocolsString =
1087 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1088 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001089 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001090 netId,
1091 WifiConfiguration.Protocol.varName,
1092 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001094 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001095 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
1097 break setVariables;
1098 }
1099
1100 String allowedAuthAlgorithmsString =
1101 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1102 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001103 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001104 netId,
1105 WifiConfiguration.AuthAlgorithm.varName,
1106 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001109 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
1111 break setVariables;
1112 }
1113
1114 String allowedPairwiseCiphersString =
1115 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1116 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001117 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001118 netId,
1119 WifiConfiguration.PairwiseCipher.varName,
1120 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001122 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001123 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125 break setVariables;
1126 }
1127
1128 String allowedGroupCiphersString =
1129 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1130 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001131 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001132 netId,
1133 WifiConfiguration.GroupCipher.varName,
1134 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001136 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001137 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 break setVariables;
1140 }
1141
1142 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1143 // by preventing "*" as a key.
1144 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001145 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001146 netId,
1147 WifiConfiguration.pskVarName,
1148 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001150 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152 break setVariables;
1153 }
1154
1155 boolean hasSetKey = false;
1156 if (config.wepKeys != null) {
1157 for (int i = 0; i < config.wepKeys.length; i++) {
1158 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1159 // by preventing "*" as a key.
1160 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001161 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001162 netId,
1163 WifiConfiguration.wepKeyVarNames[i],
1164 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001167 "failed to set wep_key"+i+": " +
1168 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170 break setVariables;
1171 }
1172 hasSetKey = true;
1173 }
1174 }
1175 }
1176
1177 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001178 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001179 netId,
1180 WifiConfiguration.wepTxKeyIdxVarName,
1181 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001183 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001184 "failed to set wep_tx_keyidx: "+
1185 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187 break setVariables;
1188 }
1189 }
1190
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001191 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001192 netId,
1193 WifiConfiguration.priorityVarName,
1194 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001196 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001197 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199 break setVariables;
1200 }
1201
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001202 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001203 netId,
1204 WifiConfiguration.hiddenSSIDVarName,
1205 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001208 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210 break setVariables;
1211 }
1212
Chung-yih Wang43374762009-09-16 14:28:42 +08001213 for (WifiConfiguration.EnterpriseField field
1214 : config.enterpriseFields) {
1215 String varName = field.varName();
1216 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001217 if (value != null) {
1218 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001219 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001220 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001221 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001222 netId,
1223 varName,
1224 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001225 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001226 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001227 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001228 }
1229 break setVariables;
1230 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001231 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001236 /*
1237 * For an update, if one of the setNetworkVariable operations fails,
1238 * we might want to roll back all the changes already made. But the
1239 * chances are that if anything is going to go wrong, it'll happen
1240 * the first time we try to set one of the variables.
1241 */
1242 if (newNetwork) {
1243 removeNetwork(netId);
1244 if (DBG) {
1245 Slog.d(TAG,
1246 "Failed to set a network variable, removed network: "
1247 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
1249 }
1250 return -1;
1251 }
1252
1253 private static String makeString(BitSet set, String[] strings) {
1254 StringBuffer buf = new StringBuffer();
1255 int nextSetBit = -1;
1256
1257 /* Make sure all set bits are in [0, strings.length) to avoid
1258 * going out of bounds on strings. (Shouldn't happen, but...) */
1259 set = set.get(0, strings.length);
1260
1261 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1262 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1263 }
1264
1265 // remove trailing space
1266 if (set.cardinality() > 0) {
1267 buf.setLength(buf.length() - 1);
1268 }
1269
1270 return buf.toString();
1271 }
1272
1273 private static int lookupString(String string, String[] strings) {
1274 int size = strings.length;
1275
1276 string = string.replace('-', '_');
1277
1278 for (int i = 0; i < size; i++)
1279 if (string.equals(strings[i]))
1280 return i;
1281
1282 if (DBG) {
1283 // if we ever get here, we should probably add the
1284 // value to WifiConfiguration to reflect that it's
1285 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001286 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
1288
1289 return -1;
1290 }
1291
1292 /**
1293 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1294 * @param netId the integer that identifies the network configuration
1295 * to the supplicant
1296 * @return {@code true} if the operation succeeded
1297 */
1298 public boolean removeNetwork(int netId) {
1299 enforceChangePermission();
1300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 return mWifiStateTracker.removeNetwork(netId);
1302 }
1303
1304 /**
1305 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1306 * @param netId the integer that identifies the network configuration
1307 * to the supplicant
1308 * @param disableOthers if true, disable all other networks.
1309 * @return {@code true} if the operation succeeded
1310 */
1311 public boolean enableNetwork(int netId, boolean disableOthers) {
1312 enforceChangePermission();
1313
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001314 String ifname = mWifiStateTracker.getInterfaceName();
1315 NetworkUtils.enableInterface(ifname);
1316 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1317 if (!result) {
1318 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001320 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322
1323 /**
1324 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1325 * @param netId the integer that identifies the network configuration
1326 * to the supplicant
1327 * @return {@code true} if the operation succeeded
1328 */
1329 public boolean disableNetwork(int netId) {
1330 enforceChangePermission();
1331
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001332 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
1334
1335 /**
1336 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1337 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1338 */
1339 public WifiInfo getConnectionInfo() {
1340 enforceAccessPermission();
1341 /*
1342 * Make sure we have the latest information, by sending
1343 * a status request to the supplicant.
1344 */
1345 return mWifiStateTracker.requestConnectionInfo();
1346 }
1347
1348 /**
1349 * Return the results of the most recent access point scan, in the form of
1350 * a list of {@link ScanResult} objects.
1351 * @return the list of results
1352 */
1353 public List<ScanResult> getScanResults() {
1354 enforceAccessPermission();
1355 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001356
1357 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 if (reply == null) {
1359 return null;
1360 }
1361
1362 List<ScanResult> scanList = new ArrayList<ScanResult>();
1363
1364 int lineCount = 0;
1365
1366 int replyLen = reply.length();
1367 // Parse the result string, keeping in mind that the last line does
1368 // not end with a newline.
1369 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1370 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1371 ++lineCount;
1372 /*
1373 * Skip the first line, which is a header
1374 */
1375 if (lineCount == 1) {
1376 lineBeg = lineEnd + 1;
1377 continue;
1378 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001379 if (lineEnd > lineBeg) {
1380 String line = reply.substring(lineBeg, lineEnd);
1381 ScanResult scanResult = parseScanResult(line);
1382 if (scanResult != null) {
1383 scanList.add(scanResult);
1384 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001385 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
1387 }
1388 lineBeg = lineEnd + 1;
1389 }
1390 }
1391 mWifiStateTracker.setScanResultsList(scanList);
1392 return scanList;
1393 }
1394
1395 /**
1396 * Parse the scan result line passed to us by wpa_supplicant (helper).
1397 * @param line the line to parse
1398 * @return the {@link ScanResult} object
1399 */
1400 private ScanResult parseScanResult(String line) {
1401 ScanResult scanResult = null;
1402 if (line != null) {
1403 /*
1404 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1405 * must synchronized here!
1406 */
1407 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001408 String[] result = scanResultPattern.split(line);
1409 if (3 <= result.length && result.length <= 5) {
1410 String bssid = result[0];
1411 // bssid | frequency | level | flags | ssid
1412 int frequency;
1413 int level;
1414 try {
1415 frequency = Integer.parseInt(result[1]);
1416 level = Integer.parseInt(result[2]);
1417 /* some implementations avoid negative values by adding 256
1418 * so we need to adjust for that here.
1419 */
1420 if (level > 0) level -= 256;
1421 } catch (NumberFormatException e) {
1422 frequency = 0;
1423 level = 0;
1424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425
Mike Lockwood1a645052009-06-25 13:01:12 -04001426 /*
1427 * The formatting of the results returned by
1428 * wpa_supplicant is intended to make the fields
1429 * line up nicely when printed,
1430 * not to make them easy to parse. So we have to
1431 * apply some heuristics to figure out which field
1432 * is the SSID and which field is the flags.
1433 */
1434 String ssid;
1435 String flags;
1436 if (result.length == 4) {
1437 if (result[3].charAt(0) == '[') {
1438 flags = result[3];
1439 ssid = "";
1440 } else {
1441 flags = "";
1442 ssid = result[3];
1443 }
1444 } else if (result.length == 5) {
1445 flags = result[3];
1446 ssid = result[4];
1447 } else {
1448 // Here, we must have 3 fields: no flags and ssid
1449 // set
1450 flags = "";
1451 ssid = "";
1452 }
1453
Mike Lockwood00717e22009-08-17 10:09:36 -04001454 // bssid + ssid is the hash key
1455 String key = bssid + ssid;
1456 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001457 if (scanResult != null) {
1458 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001459 scanResult.SSID = ssid;
1460 scanResult.capabilities = flags;
1461 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001462 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 // Do not add scan results that have no SSID set
1464 if (0 < ssid.trim().length()) {
1465 scanResult =
1466 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001467 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001468 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001471 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001472 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001473 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476 }
1477
1478 return scanResult;
1479 }
1480
1481 /**
1482 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1483 * and construct a {@code WifiConfiguration} that describes the encryption,
1484 * key management, and authenticaion capabilities of the access point.
1485 * @param flags the string returned by wpa_supplicant
1486 * @return the {@link WifiConfiguration} object, filled in
1487 */
1488 WifiConfiguration parseScanFlags(String flags) {
1489 WifiConfiguration config = new WifiConfiguration();
1490
1491 if (flags.length() == 0) {
1492 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1493 }
1494 // ... to be implemented
1495 return config;
1496 }
1497
1498 /**
1499 * Tell the supplicant to persist the current list of configured networks.
1500 * @return {@code true} if the operation succeeded
1501 */
1502 public boolean saveConfiguration() {
1503 boolean result;
1504 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001507 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 if (result && mNeedReconfig) {
1509 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001510 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511
1512 if (result) {
1513 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1514 mContext.sendBroadcast(intent);
1515 }
1516 }
1517 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001518 // Inform the backup manager about a data change
1519 IBackupManager ibm = IBackupManager.Stub.asInterface(
1520 ServiceManager.getService(Context.BACKUP_SERVICE));
1521 if (ibm != null) {
1522 try {
1523 ibm.dataChanged("com.android.providers.settings");
1524 } catch (Exception e) {
1525 // Try again later
1526 }
1527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 return result;
1529 }
1530
1531 /**
1532 * Set the number of radio frequency channels that are allowed to be used
1533 * in the current regulatory domain. This method should be used only
1534 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001535 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 * persisted as a Secure setting.
1537 * @param numChannels the number of allowed channels. Must be greater than 0
1538 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001539 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1541 * {@code numChannels} is outside the valid range.
1542 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001543 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001544 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001545 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 /*
1549 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1550 * but if Wi-Fi isn't currently enabled, that's not possible, and
1551 * we want to persist the setting anyway,so that it will take
1552 * effect when Wi-Fi does become enabled.
1553 */
1554 boolean found = false;
1555 for (int validChan : sValidRegulatoryChannelCounts) {
1556 if (validChan == numChannels) {
1557 found = true;
1558 break;
1559 }
1560 }
1561 if (!found) {
1562 return false;
1563 }
1564
Irfan Sheriff59610c02010-03-30 11:00:41 -07001565 if (mWifiHandler == null) return false;
1566
1567 Message.obtain(mWifiHandler,
1568 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1569
1570 return true;
1571 }
1572
1573 /**
1574 * sets the number of allowed radio frequency channels synchronously
1575 * @param numChannels the number of allowed channels. Must be greater than 0
1576 * and less than or equal to 16.
1577 * @param persist {@code true} if the setting should be remembered.
1578 * @return {@code true} if the operation succeeds, {@code false} otherwise
1579 */
1580 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001581 if (persist) {
1582 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001583 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1584 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001585 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001586 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588
1589 /**
1590 * Return the number of frequency channels that are allowed
1591 * to be used in the current regulatory domain.
1592 * @return the number of allowed channels, or {@code -1} if an error occurs
1593 */
1594 public int getNumAllowedChannels() {
1595 int numChannels;
1596
1597 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001598
1599 /*
1600 * If we can't get the value from the driver (e.g., because
1601 * Wi-Fi is not currently enabled), get the value from
1602 * Settings.
1603 */
1604 numChannels = mWifiStateTracker.getNumAllowedChannels();
1605 if (numChannels < 0) {
1606 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1607 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1608 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 return numChannels;
1611 }
1612
1613 /**
1614 * Return the list of valid values for the number of allowed radio channels
1615 * for various regulatory domains.
1616 * @return the list of channel counts
1617 */
1618 public int[] getValidChannelCounts() {
1619 enforceAccessPermission();
1620 return sValidRegulatoryChannelCounts;
1621 }
1622
1623 /**
1624 * Return the DHCP-assigned addresses from the last successful DHCP request,
1625 * if any.
1626 * @return the DHCP information
1627 */
1628 public DhcpInfo getDhcpInfo() {
1629 enforceAccessPermission();
1630 return mWifiStateTracker.getDhcpInfo();
1631 }
1632
1633 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1634 @Override
1635 public void onReceive(Context context, Intent intent) {
1636 String action = intent.getAction();
1637
Doug Zongker43866e02010-01-07 12:09:54 -08001638 long idleMillis =
1639 Settings.Secure.getLong(mContext.getContentResolver(),
1640 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001642 Settings.System.getInt(mContext.getContentResolver(),
1643 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001645 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 mAlarmManager.cancel(mIdleIntent);
1647 mDeviceIdle = false;
1648 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001649 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001651 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001653 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 /*
1655 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1656 * AND the "stay on while plugged in" setting doesn't match the
1657 * current power conditions (i.e, not plugged in, plugged in to USB,
1658 * or plugged in to AC).
1659 */
1660 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001661 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1662 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001663 // we used to go to sleep immediately, but this caused some race conditions
1664 // we don't have time to track down for this release. Delay instead, but not
1665 // as long as we would if connected (below)
1666 // TODO - fix the race conditions and switch back to the immediate turn-off
1667 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001668 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001669 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1670 // // do not keep Wifi awake when screen is off if Wifi is not associated
1671 // mDeviceIdle = true;
1672 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001673 } else {
1674 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001676 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
1679 /* we can return now -- there's nothing to do until we get the idle intent back */
1680 return;
1681 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001682 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 mDeviceIdle = true;
1684 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1685 /*
1686 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1687 * AND we are transitioning from a state in which the device was supposed
1688 * to stay awake to a state in which it is not supposed to stay awake.
1689 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1690 * the already-set timer.
1691 */
1692 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001693 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1695 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1696 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1699 mPluggedType = pluggedType;
1700 return;
1701 }
1702 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001703 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001704 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1705 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1706 boolean isBluetoothPlaying = false;
1707 for (BluetoothDevice sink : sinks) {
1708 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1709 isBluetoothPlaying = true;
1710 }
1711 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001712 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 } else {
1715 return;
1716 }
1717
1718 updateWifiState();
1719 }
1720
1721 /**
1722 * Determines whether the Wi-Fi chipset should stay awake or be put to
1723 * sleep. Looks at the setting for the sleep policy and the current
1724 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001725 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 * @see #shouldDeviceStayAwake(int, int)
1727 */
1728 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1729 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1730 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1731
1732 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1733 // Never sleep
1734 return true;
1735 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1736 (pluggedType != 0)) {
1737 // Never sleep while plugged, and we're plugged
1738 return true;
1739 } else {
1740 // Default
1741 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1742 }
1743 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 /**
1746 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1747 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1748 * of {@code 0} isn't really a plugged type, but rather an indication that the
1749 * device isn't plugged in at all, there is no bit value corresponding to a
1750 * {@code pluggedType} value of {@code 0}. That is why we shift by
1751 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1752 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1753 * keep the device (and hence Wi-Fi) awake.
1754 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1755 * being made
1756 * @return {@code true} if {@code pluggedType} indicates that the device is
1757 * supposed to stay awake, {@code false} otherwise.
1758 */
1759 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1760 return (stayAwakeConditions & pluggedType) != 0;
1761 }
1762 };
1763
Dianne Hackborn617f8772009-03-31 15:04:46 -07001764 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 Message msg = Message.obtain(mWifiHandler,
1766 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001767 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 msg.sendToTarget();
1769 }
1770
1771 private void sendStartMessage(boolean scanOnlyMode) {
1772 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1773 }
1774
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001775 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1776 Message.obtain(mWifiHandler,
1777 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001778 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001779 }
1780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001782 // send a message so it's all serialized
1783 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1784 }
1785
1786 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001788 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 boolean lockHeld = mLocks.hasLocks();
1790 int strongestLockMode;
1791 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1792 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1793 if (mDeviceIdle && lockHeld) {
1794 strongestLockMode = mLocks.getStrongestLockMode();
1795 } else {
1796 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1797 }
1798
1799 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001800 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 return;
1802 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001803
1804 /* Disable tethering when airplane mode is enabled */
1805 if (airplaneMode &&
1806 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1807 sWakeLock.acquire();
1808 sendAccessPointMessage(false, null, mLastApEnableUid);
1809 }
1810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 if (wifiShouldBeEnabled) {
1812 if (wifiShouldBeStarted) {
1813 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001814 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 sWakeLock.acquire();
1816 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001817 } else if (!mWifiStateTracker.isDriverStopped()) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001818 if (mCm == null) {
1819 mCm = (ConnectivityManager)mContext.
1820 getSystemService(Context.CONNECTIVITY_SERVICE);
1821 }
1822 mCm.requestNetworkTransitionWakelock(TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 } else {
1826 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001827 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829 }
1830 }
1831
1832 private void registerForBroadcasts() {
1833 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1835 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1836 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1837 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001838 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 mContext.registerReceiver(mReceiver, intentFilter);
1840 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 private boolean isAirplaneSensitive() {
1843 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1844 Settings.System.AIRPLANE_MODE_RADIOS);
1845 return airplaneModeRadios == null
1846 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1847 }
1848
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001849 private boolean isAirplaneToggleable() {
1850 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1851 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1852 return toggleableRadios != null
1853 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1854 }
1855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 /**
1857 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1858 * currently on.
1859 * @return {@code true} if airplane mode is on.
1860 */
1861 private boolean isAirplaneModeOn() {
1862 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1863 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1864 }
1865
1866 /**
1867 * Handler that allows posting to the WifiThread.
1868 */
1869 private class WifiHandler extends Handler {
1870 public WifiHandler(Looper looper) {
1871 super(looper);
1872 }
1873
1874 @Override
1875 public void handleMessage(Message msg) {
1876 switch (msg.what) {
1877
1878 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001879 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001880 if (mWifiWatchdogService == null) {
1881 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 sWakeLock.release();
1884 break;
1885
1886 case MESSAGE_START_WIFI:
1887 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1888 mWifiStateTracker.restart();
1889 sWakeLock.release();
1890 break;
1891
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001892 case MESSAGE_UPDATE_STATE:
1893 doUpdateWifiState();
1894 break;
1895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 case MESSAGE_DISABLE_WIFI:
1897 // a non-zero msg.arg1 value means the "enabled" setting
1898 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001899 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001900 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 sWakeLock.release();
1902 break;
1903
1904 case MESSAGE_STOP_WIFI:
1905 mWifiStateTracker.disconnectAndStop();
1906 // don't release wakelock
1907 break;
1908
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001909 case MESSAGE_START_ACCESS_POINT:
1910 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001911 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001912 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001913 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001914 break;
1915
1916 case MESSAGE_STOP_ACCESS_POINT:
1917 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001918 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001919 (WifiConfiguration) msg.obj);
1920 sWakeLock.release();
1921 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001922
1923 case MESSAGE_SET_CHANNELS:
1924 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1925 break;
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 }
1929 }
1930
1931 @Override
1932 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1933 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1934 != PackageManager.PERMISSION_GRANTED) {
1935 pw.println("Permission Denial: can't dump WifiService from from pid="
1936 + Binder.getCallingPid()
1937 + ", uid=" + Binder.getCallingUid());
1938 return;
1939 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001940 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 pw.println("Stay-awake conditions: " +
1942 Settings.System.getInt(mContext.getContentResolver(),
1943 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1944 pw.println();
1945
1946 pw.println("Internal state:");
1947 pw.println(mWifiStateTracker);
1948 pw.println();
1949 pw.println("Latest scan results:");
1950 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1951 if (scanResults != null && scanResults.size() != 0) {
1952 pw.println(" BSSID Frequency RSSI Flags SSID");
1953 for (ScanResult r : scanResults) {
1954 pw.printf(" %17s %9d %5d %-16s %s%n",
1955 r.BSSID,
1956 r.frequency,
1957 r.level,
1958 r.capabilities,
1959 r.SSID == null ? "" : r.SSID);
1960 }
1961 }
1962 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001963 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1964 mScanLocksAcquired + " scan");
1965 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1966 mScanLocksReleased + " scan");
1967 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 pw.println("Locks held:");
1969 mLocks.dump(pw);
1970 }
1971
1972 private static String stateName(int wifiState) {
1973 switch (wifiState) {
1974 case WIFI_STATE_DISABLING:
1975 return "disabling";
1976 case WIFI_STATE_DISABLED:
1977 return "disabled";
1978 case WIFI_STATE_ENABLING:
1979 return "enabling";
1980 case WIFI_STATE_ENABLED:
1981 return "enabled";
1982 case WIFI_STATE_UNKNOWN:
1983 return "unknown state";
1984 default:
1985 return "[invalid state]";
1986 }
1987 }
1988
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001989 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001991 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993
1994 public void binderDied() {
1995 synchronized (mLocks) {
1996 releaseWifiLockLocked(mBinder);
1997 }
1998 }
1999
2000 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002001 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
2003 }
2004
2005 private class LockList {
2006 private List<WifiLock> mList;
2007
2008 private LockList() {
2009 mList = new ArrayList<WifiLock>();
2010 }
2011
2012 private synchronized boolean hasLocks() {
2013 return !mList.isEmpty();
2014 }
2015
2016 private synchronized int getStrongestLockMode() {
2017 if (mList.isEmpty()) {
2018 return WifiManager.WIFI_MODE_FULL;
2019 }
2020 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002021 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 return WifiManager.WIFI_MODE_FULL;
2023 }
2024 }
2025 return WifiManager.WIFI_MODE_SCAN_ONLY;
2026 }
2027
2028 private void addLock(WifiLock lock) {
2029 if (findLockByBinder(lock.mBinder) < 0) {
2030 mList.add(lock);
2031 }
2032 }
2033
2034 private WifiLock removeLock(IBinder binder) {
2035 int index = findLockByBinder(binder);
2036 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002037 WifiLock ret = mList.remove(index);
2038 ret.unlinkDeathRecipient();
2039 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 } else {
2041 return null;
2042 }
2043 }
2044
2045 private int findLockByBinder(IBinder binder) {
2046 int size = mList.size();
2047 for (int i = size - 1; i >= 0; i--)
2048 if (mList.get(i).mBinder == binder)
2049 return i;
2050 return -1;
2051 }
2052
2053 private void dump(PrintWriter pw) {
2054 for (WifiLock l : mList) {
2055 pw.print(" ");
2056 pw.println(l);
2057 }
2058 }
2059 }
2060
2061 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2063 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
2064 return false;
2065 }
2066 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2067 synchronized (mLocks) {
2068 return acquireWifiLockLocked(wifiLock);
2069 }
2070 }
2071
2072 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002073 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002076
The Android Open Source Project10592532009-03-18 17:39:46 -07002077 int uid = Binder.getCallingUid();
2078 long ident = Binder.clearCallingIdentity();
2079 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002080 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002081 case WifiManager.WIFI_MODE_FULL:
2082 ++mFullLocksAcquired;
2083 mBatteryStats.noteFullWifiLockAcquired(uid);
2084 break;
2085 case WifiManager.WIFI_MODE_SCAN_ONLY:
2086 ++mScanLocksAcquired;
2087 mBatteryStats.noteScanWifiLockAcquired(uid);
2088 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002089 }
2090 } catch (RemoteException e) {
2091 } finally {
2092 Binder.restoreCallingIdentity(ident);
2093 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 updateWifiState();
2096 return true;
2097 }
2098
2099 public boolean releaseWifiLock(IBinder lock) {
2100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2101 synchronized (mLocks) {
2102 return releaseWifiLockLocked(lock);
2103 }
2104 }
2105
2106 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002107 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002108
The Android Open Source Project10592532009-03-18 17:39:46 -07002109 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002110
Joe Onorato8a9b2202010-02-26 18:56:32 -08002111 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002112
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002113 hadLock = (wifiLock != null);
2114
2115 if (hadLock) {
2116 int uid = Binder.getCallingUid();
2117 long ident = Binder.clearCallingIdentity();
2118 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002119 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002120 case WifiManager.WIFI_MODE_FULL:
2121 ++mFullLocksReleased;
2122 mBatteryStats.noteFullWifiLockReleased(uid);
2123 break;
2124 case WifiManager.WIFI_MODE_SCAN_ONLY:
2125 ++mScanLocksReleased;
2126 mBatteryStats.noteScanWifiLockReleased(uid);
2127 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002128 }
2129 } catch (RemoteException e) {
2130 } finally {
2131 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002132 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002133 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002134 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002136 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002138
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002139 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002140 implements IBinder.DeathRecipient {
2141 String mTag;
2142 int mMode;
2143 IBinder mBinder;
2144
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002145 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002146 super();
2147 mTag = tag;
2148 mMode = mode;
2149 mBinder = binder;
2150 try {
2151 mBinder.linkToDeath(this, 0);
2152 } catch (RemoteException e) {
2153 binderDied();
2154 }
2155 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002156
2157 void unlinkDeathRecipient() {
2158 mBinder.unlinkToDeath(this, 0);
2159 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002160 }
2161
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002162 private class Multicaster extends DeathRecipient {
2163 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002164 super(Binder.getCallingUid(), tag, binder);
2165 }
2166
2167 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002168 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002169 synchronized (mMulticasters) {
2170 int i = mMulticasters.indexOf(this);
2171 if (i != -1) {
2172 removeMulticasterLocked(i, mMode);
2173 }
2174 }
2175 }
2176
2177 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002178 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002179 }
2180
2181 public int getUid() {
2182 return mMode;
2183 }
2184 }
2185
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002186 public void initializeMulticastFiltering() {
2187 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002188
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002189 synchronized (mMulticasters) {
2190 // if anybody had requested filters be off, leave off
2191 if (mMulticasters.size() != 0) {
2192 return;
2193 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002194 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002195 }
2196 }
2197 }
2198
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002199 public void acquireMulticastLock(IBinder binder, String tag) {
2200 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002201
2202 synchronized (mMulticasters) {
2203 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002204 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002205 // Note that we could call stopPacketFiltering only when
2206 // our new size == 1 (first call), but this function won't
2207 // be called often and by making the stopPacket call each
2208 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002209 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002210 }
2211
2212 int uid = Binder.getCallingUid();
2213 Long ident = Binder.clearCallingIdentity();
2214 try {
2215 mBatteryStats.noteWifiMulticastEnabled(uid);
2216 } catch (RemoteException e) {
2217 } finally {
2218 Binder.restoreCallingIdentity(ident);
2219 }
2220 }
2221
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002222 public void releaseMulticastLock() {
2223 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002224
2225 int uid = Binder.getCallingUid();
2226 synchronized (mMulticasters) {
2227 mMulticastDisabled++;
2228 int size = mMulticasters.size();
2229 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002230 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002231 if ((m != null) && (m.getUid() == uid)) {
2232 removeMulticasterLocked(i, uid);
2233 }
2234 }
2235 }
2236 }
2237
2238 private void removeMulticasterLocked(int i, int uid)
2239 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002240 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002241
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002242 if (removed != null) {
2243 removed.unlinkDeathRecipient();
2244 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002245 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002246 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002247 }
2248
2249 Long ident = Binder.clearCallingIdentity();
2250 try {
2251 mBatteryStats.noteWifiMulticastDisabled(uid);
2252 } catch (RemoteException e) {
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
2256 }
2257
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002258 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002259 enforceAccessPermission();
2260
2261 synchronized (mMulticasters) {
2262 return (mMulticasters.size() > 0);
2263 }
2264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265}