blob: 99cacdfb836ab2499d8446d1f80439510aa388ec [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
Irfan Sheriff5321aef2010-02-12 12:35:59 -080025import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
26import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
27import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
28import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
29import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.AlarmManager;
32import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070033import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080034import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.BroadcastReceiver;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.pm.PackageManager;
41import android.net.wifi.IWifiManager;
42import android.net.wifi.WifiInfo;
43import android.net.wifi.WifiManager;
44import android.net.wifi.WifiNative;
45import android.net.wifi.WifiStateTracker;
46import android.net.wifi.ScanResult;
47import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070048import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080049import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080050import android.net.ConnectivityManager;
51import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.NetworkStateTracker;
53import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040054import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
56import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080059import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
62import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070063import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070065import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.text.TextUtils;
69
70import java.util.ArrayList;
71import java.util.BitSet;
72import java.util.HashMap;
73import java.util.LinkedHashMap;
74import java.util.List;
75import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080076import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.regex.Pattern;
78import java.io.FileDescriptor;
79import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080080import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
The Android Open Source Project10592532009-03-18 17:39:46 -070082import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080083import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070084import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080085import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087/**
88 * WifiService handles remote WiFi operation requests by implementing
89 * the IWifiManager interface. It also creates a WifiMonitor to listen
90 * for Wifi-related events.
91 *
92 * @hide
93 */
94public class WifiService extends IWifiManager.Stub {
95 private static final String TAG = "WifiService";
96 private static final boolean DBG = false;
97 private static final Pattern scanResultPattern = Pattern.compile("\t+");
98 private final WifiStateTracker mWifiStateTracker;
Irfan Sheriffc2f54c22010-03-18 14:02:22 -070099 /* TODO: fetch a configurable interface */
100 private static final String SOFTAP_IFACE = "wl0.1";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 private Context mContext;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800103 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105 private AlarmManager mAlarmManager;
106 private PendingIntent mIdleIntent;
107 private static final int IDLE_REQUEST = 0;
108 private boolean mScreenOff;
109 private boolean mDeviceIdle;
110 private int mPluggedType;
111
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800112 private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
113
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700114 // true if the user enabled Wifi while in airplane mode
115 private boolean mAirplaneModeOverwridden;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700118 // some wifi lock statistics
119 private int mFullLocksAcquired;
120 private int mFullLocksReleased;
121 private int mScanLocksAcquired;
122 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700123
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700124 private final List<Multicaster> mMulticasters =
125 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700126 private int mMulticastEnabled;
127 private int mMulticastDisabled;
128
The Android Open Source Project10592532009-03-18 17:39:46 -0700129 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800130
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800131 private INetworkManagementService nwService;
132 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800133 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800134 private String[] mWifiRegexs;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800137 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
138 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 * the approximate point at which the battery drain caused by Wi-Fi
140 * being enabled but not active exceeds the battery drain caused by
141 * re-establishing a connection to the mobile data network.
142 */
143 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
144
145 private static final String WAKELOCK_TAG = "WifiService";
146
147 /**
148 * The maximum amount of time to hold the wake lock after a disconnect
149 * caused by stopping the driver. Establishing an EDGE connection has been
150 * observed to take about 5 seconds under normal circumstances. This
151 * provides a bit of extra margin.
152 * <p>
153 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
154 * This is the default value if a Settings.Secure value is not present.
155 */
156 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
157
158 // Wake lock used by driver-stop operation
159 private static PowerManager.WakeLock sDriverStopWakeLock;
160 // Wake lock used by other operations
161 private static PowerManager.WakeLock sWakeLock;
162
Irfan Sheriff59610c02010-03-30 11:00:41 -0700163 private static final int MESSAGE_ENABLE_WIFI = 0;
164 private static final int MESSAGE_DISABLE_WIFI = 1;
165 private static final int MESSAGE_STOP_WIFI = 2;
166 private static final int MESSAGE_START_WIFI = 3;
167 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
168 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800169 private static final int MESSAGE_START_ACCESS_POINT = 6;
170 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700171 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174 private final WifiHandler mWifiHandler;
175
176 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 * Cache of scan results objects (size is somewhat arbitrary)
178 */
179 private static final int SCAN_RESULT_CACHE_SIZE = 80;
180 private final LinkedHashMap<String, ScanResult> mScanResultCache;
181
182 /*
183 * Character buffer used to parse scan results (optimization)
184 */
185 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private boolean mNeedReconfig;
187
Dianne Hackborn617f8772009-03-31 15:04:46 -0700188 /*
189 * Last UID that asked to enable WIFI.
190 */
191 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 /**
194 * Number of allowed radio frequency channels in various regulatory domains.
195 * This list is sufficient for 802.11b/g networks (2.4GHz range).
196 */
197 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
198
199 private static final String ACTION_DEVICE_IDLE =
200 "com.android.server.WifiManager.action.DEVICE_IDLE";
201
202 WifiService(Context context, WifiStateTracker tracker) {
203 mContext = context;
204 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400205 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700206 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800207
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800208 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
209 nwService = INetworkManagementService.Stub.asInterface(b);
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 mScanResultCache = new LinkedHashMap<String, ScanResult>(
212 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
213 /*
214 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
215 * elements
216 */
217 public boolean removeEldestEntry(Map.Entry eldest) {
218 return SCAN_RESULT_CACHE_SIZE < this.size();
219 }
220 };
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 HandlerThread wifiThread = new HandlerThread("WifiService");
223 wifiThread.start();
224 mWifiHandler = new WifiHandler(wifiThread.getLooper());
225
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800226 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800227 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
230 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
231 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
232
233 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
234 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
235 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 mContext.registerReceiver(
238 new BroadcastReceiver() {
239 @Override
240 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700241 // clear our flag indicating the user has overwridden airplane mode
242 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 updateWifiState();
244 }
245 },
246 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
247
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800248 mContext.registerReceiver(
249 new BroadcastReceiver() {
250 @Override
251 public void onReceive(Context context, Intent intent) {
252
253 ArrayList<String> available = intent.getStringArrayListExtra(
254 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
255 ArrayList<String> active = intent.getStringArrayListExtra(
256 ConnectivityManager.EXTRA_ACTIVE_TETHER);
257 updateTetherState(available, active);
258
259 }
260 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800261 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800262
Irfan Sheriff7b009782010-03-11 16:37:45 -0800263 /**
264 * Check if Wi-Fi needs to be enabled and start
265 * if needed
266 */
267 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700268 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
269 boolean wifiEnabled = getPersistedWifiEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800270 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
271 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700272 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800273 }
274
275 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
276
277 boolean wifiTethered = false;
278 boolean wifiAvailable = false;
279
280 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
281 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
282
283 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
284 mWifiRegexs = mCm.getTetherableWifiRegexs();
285
286 for (String intf : available) {
287 for (String regex : mWifiRegexs) {
288 if (intf.matches(regex)) {
289
290 InterfaceConfiguration ifcg = null;
291 try {
292 ifcg = service.getInterfaceConfig(intf);
293 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700294 /* IP/netmask: 192.168.43.1/255.255.255.0 */
295 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800296 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
297 ifcg.interfaceFlags = "up";
298
299 service.setInterfaceConfig(intf, ifcg);
300 }
301 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800302 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700303 try {
304 nwService.stopAccessPoint();
305 } catch (Exception ee) {
306 Slog.e(TAG, "Could not stop AP, :" + ee);
307 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800308 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800309 return;
310 }
311
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800312 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800313 Slog.e(TAG, "Error tethering "+intf);
314 }
315 break;
316 }
317 }
318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 }
320
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700321 private boolean testAndClearWifiSavedState() {
322 final ContentResolver cr = mContext.getContentResolver();
323 int wifiSavedState = 0;
324 try {
325 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
326 if(wifiSavedState == 1)
327 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
328 } catch (Settings.SettingNotFoundException e) {
329 ;
330 }
331 return (wifiSavedState == 1);
332 }
333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 private boolean getPersistedWifiEnabled() {
335 final ContentResolver cr = mContext.getContentResolver();
336 try {
337 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
338 } catch (Settings.SettingNotFoundException e) {
339 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
340 return false;
341 }
342 }
343
344 private void persistWifiEnabled(boolean enabled) {
345 final ContentResolver cr = mContext.getContentResolver();
346 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
347 }
348
349 NetworkStateTracker getNetworkStateTracker() {
350 return mWifiStateTracker;
351 }
352
353 /**
354 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
355 * @return {@code true} if the operation succeeds
356 */
357 public boolean pingSupplicant() {
358 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800359
360 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
363 /**
364 * see {@link android.net.wifi.WifiManager#startScan()}
365 * @return {@code true} if the operation succeeds
366 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400367 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800369
370 switch (mWifiStateTracker.getSupplicantState()) {
371 case DISCONNECTED:
372 case INACTIVE:
373 case SCANNING:
374 case DORMANT:
375 break;
376 default:
377 mWifiStateTracker.setScanResultHandling(
378 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
379 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800381 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
384 /**
385 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
386 * @param enable {@code true} to enable, {@code false} to disable.
387 * @return {@code true} if the enable/disable operation was
388 * started or is already in the queue.
389 */
390 public boolean setWifiEnabled(boolean enable) {
391 enforceChangePermission();
392 if (mWifiHandler == null) return false;
393
394 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700395 // caller may not have WAKE_LOCK permission - it's not required here
396 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700398 Binder.restoreCallingIdentity(ident);
399
Dianne Hackborn617f8772009-03-31 15:04:46 -0700400 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700401 // set a flag if the user is enabling Wifi while in airplane mode
402 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700403 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 }
405
406 return true;
407 }
408
409 /**
410 * Enables/disables Wi-Fi synchronously.
411 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
412 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700413 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 * @return {@code true} if the operation succeeds (or if the existing state
415 * is the same as the requested state)
416 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700417 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800419 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800421 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 return true;
423 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700424 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 return false;
426 }
427
Irfan Sheriffcd770372010-01-08 09:36:04 -0800428 /**
429 * Multiple calls to unregisterReceiver() cause exception and a system crash.
430 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
431 * disable wifi at the same time.
432 * Avoid doing a disable when the current Wifi state is UNKNOWN
433 * TODO: Handle driver load fail and supplicant lost as seperate states
434 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800435 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800436 return false;
437 }
438
Irfan Sherifff91444c2010-03-24 12:11:00 -0700439 /**
440 * Fail Wifi if AP is enabled
441 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
442 * WIFI_STATE_FAILED
443 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800444 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700445 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
446 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800447 }
448
Irfan Sherifff91444c2010-03-24 12:11:00 -0700449 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800452 if (!mWifiStateTracker.loadDriver()) {
453 Slog.e(TAG, "Failed to load Wi-Fi driver.");
454 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
455 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800457 if (!mWifiStateTracker.startSupplicant()) {
458 mWifiStateTracker.unloadDriver();
459 Slog.e(TAG, "Failed to start supplicant daemon.");
460 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
461 return false;
462 }
463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 registerForBroadcasts();
465 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 } else {
468
469 mContext.unregisterReceiver(mReceiver);
470 // Remove notification (it will no-op if it isn't visible)
471 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
472
473 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800474
475 if (!mWifiStateTracker.stopSupplicant()) {
476 Slog.e(TAG, "Failed to stop supplicant daemon.");
477 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
478 failedToStopSupplicantOrUnloadDriver = true;
479 }
480
481 /**
482 * Reset connections and disable interface
483 * before we unload the driver
484 */
485 mWifiStateTracker.resetConnections(true);
486
487 if (!mWifiStateTracker.unloadDriver()) {
488 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
489 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700490 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 failedToStopSupplicantOrUnloadDriver = true;
492 }
493 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 if (failedToStopSupplicantOrUnloadDriver) {
496 return false;
497 }
498 }
499
500 // Success!
501
502 if (persist) {
503 persistWifiEnabled(enable);
504 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700505 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 return true;
507 }
508
Dianne Hackborn617f8772009-03-31 15:04:46 -0700509 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800510 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511
The Android Open Source Project10592532009-03-18 17:39:46 -0700512 long ident = Binder.clearCallingIdentity();
513 try {
514 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700515 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700516 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700517 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700518 }
519 } catch (RemoteException e) {
520 } finally {
521 Binder.restoreCallingIdentity(ident);
522 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800525 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 // Broadcast
528 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
529 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
530 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
531 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
532 mContext.sendStickyBroadcast(intent);
533 }
534
535 private void enforceAccessPermission() {
536 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
537 "WifiService");
538 }
539
540 private void enforceChangePermission() {
541 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
542 "WifiService");
543
544 }
545
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700546 private void enforceMulticastChangePermission() {
547 mContext.enforceCallingOrSelfPermission(
548 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
549 "WifiService");
550 }
551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
553 * see {@link WifiManager#getWifiState()}
554 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
555 * {@link WifiManager#WIFI_STATE_DISABLING},
556 * {@link WifiManager#WIFI_STATE_ENABLED},
557 * {@link WifiManager#WIFI_STATE_ENABLING},
558 * {@link WifiManager#WIFI_STATE_UNKNOWN}
559 */
560 public int getWifiEnabledState() {
561 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800562 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 }
564
565 /**
566 * see {@link android.net.wifi.WifiManager#disconnect()}
567 * @return {@code true} if the operation succeeds
568 */
569 public boolean disconnect() {
570 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800571
572 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574
575 /**
576 * see {@link android.net.wifi.WifiManager#reconnect()}
577 * @return {@code true} if the operation succeeds
578 */
579 public boolean reconnect() {
580 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800581
582 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584
585 /**
586 * see {@link android.net.wifi.WifiManager#reassociate()}
587 * @return {@code true} if the operation succeeds
588 */
589 public boolean reassociate() {
590 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800591
592 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
594
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800595 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700596 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800597 * @param wifiConfig SSID, security and channel details as
598 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700599 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800600 * @return {@code true} if the start operation was
601 * started or is already in the queue.
602 */
603 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
604 enforceChangePermission();
605 if (mWifiHandler == null) return false;
606
607 synchronized (mWifiHandler) {
608
609 long ident = Binder.clearCallingIdentity();
610 sWakeLock.acquire();
611 Binder.restoreCallingIdentity(ident);
612
613 mLastEnableUid = Binder.getCallingUid();
614
615 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 {
670 persistApConfiguration(wifiConfig);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700671 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
672 SOFTAP_IFACE);
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 }
708 persistApConfiguration(wifiConfig);
709
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800710 if (!mWifiStateTracker.loadDriver()) {
711 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800712 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800713 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800714 }
715
716 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700717 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
718 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800719 } catch(Exception e) {
720 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800721 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
722 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800723 }
724
725 } else {
726
727 try {
728 nwService.stopAccessPoint();
729 } catch(Exception e) {
730 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800731 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
732 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800733 }
734
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800735 if (!mWifiStateTracker.unloadDriver()) {
736 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800737 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800738 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800739 }
740 }
741
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800742 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800743 return true;
744 }
745
746 /**
747 * see {@link WifiManager#getWifiApState()}
748 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
749 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
750 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
751 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
752 * {@link WifiManager#WIFI_AP_STATE_FAILED}
753 */
754 public int getWifiApEnabledState() {
755 enforceAccessPermission();
756 return mWifiApState;
757 }
758
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800759 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800760 final int previousWifiApState = mWifiApState;
761
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800762 /**
763 * Unload the driver if going to a failed state
764 */
765 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
766 mWifiStateTracker.unloadDriver();
767 }
768
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800769 long ident = Binder.clearCallingIdentity();
770 try {
771 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
772 mBatteryStats.noteWifiOn(uid);
773 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
774 mBatteryStats.noteWifiOff(uid);
775 }
776 } catch (RemoteException e) {
777 } finally {
778 Binder.restoreCallingIdentity(ident);
779 }
780
781 // Update state
782 mWifiApState = wifiAPState;
783
784 // Broadcast
785 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
786 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
787 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
788 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
789 mContext.sendStickyBroadcast(intent);
790 }
791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 /**
793 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
794 * @return the list of configured networks
795 */
796 public List<WifiConfiguration> getConfiguredNetworks() {
797 enforceAccessPermission();
798 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 /*
801 * We don't cache the list, because we want to allow
802 * for the possibility that the configuration file
803 * has been modified through some external means,
804 * such as the wpa_cli command line program.
805 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800806 listStr = mWifiStateTracker.listNetworks();
807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 List<WifiConfiguration> networks =
809 new ArrayList<WifiConfiguration>();
810 if (listStr == null)
811 return networks;
812
813 String[] lines = listStr.split("\n");
814 // Skip the first line, which is a header
815 for (int i = 1; i < lines.length; i++) {
816 String[] result = lines[i].split("\t");
817 // network-id | ssid | bssid | flags
818 WifiConfiguration config = new WifiConfiguration();
819 try {
820 config.networkId = Integer.parseInt(result[0]);
821 } catch(NumberFormatException e) {
822 continue;
823 }
824 if (result.length > 3) {
825 if (result[3].indexOf("[CURRENT]") != -1)
826 config.status = WifiConfiguration.Status.CURRENT;
827 else if (result[3].indexOf("[DISABLED]") != -1)
828 config.status = WifiConfiguration.Status.DISABLED;
829 else
830 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800831 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800834 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 networks.add(config);
836 }
837
838 return networks;
839 }
840
841 /**
842 * Read the variables from the supplicant daemon that are needed to
843 * fill in the WifiConfiguration object.
844 * <p/>
845 * The caller must hold the synchronization monitor.
846 * @param config the {@link WifiConfiguration} object to be filled in.
847 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800848 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849
850 int netId = config.networkId;
851 if (netId < 0)
852 return;
853
854 /*
855 * TODO: maybe should have a native method that takes an array of
856 * variable names and returns an array of values. But we'd still
857 * be doing a round trip to the supplicant daemon for each variable.
858 */
859 String value;
860
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800861 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800863 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 } else {
865 config.SSID = null;
866 }
867
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800868 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 if (!TextUtils.isEmpty(value)) {
870 config.BSSID = value;
871 } else {
872 config.BSSID = null;
873 }
874
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800875 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 config.priority = -1;
877 if (!TextUtils.isEmpty(value)) {
878 try {
879 config.priority = Integer.parseInt(value);
880 } catch (NumberFormatException ignore) {
881 }
882 }
883
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800884 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 config.hiddenSSID = false;
886 if (!TextUtils.isEmpty(value)) {
887 try {
888 config.hiddenSSID = Integer.parseInt(value) != 0;
889 } catch (NumberFormatException ignore) {
890 }
891 }
892
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800893 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 config.wepTxKeyIndex = -1;
895 if (!TextUtils.isEmpty(value)) {
896 try {
897 config.wepTxKeyIndex = Integer.parseInt(value);
898 } catch (NumberFormatException ignore) {
899 }
900 }
901
902 /*
903 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
904 * just a "*" if the key is set, or the null string otherwise.
905 */
906 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800907 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 if (!TextUtils.isEmpty(value)) {
909 config.wepKeys[i] = value;
910 } else {
911 config.wepKeys[i] = null;
912 }
913 }
914
915 /*
916 * Get the private shared key. Note that the actual keys are not passed back,
917 * just a "*" if the key is set, or the null string otherwise.
918 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800919 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 if (!TextUtils.isEmpty(value)) {
921 config.preSharedKey = value;
922 } else {
923 config.preSharedKey = null;
924 }
925
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800926 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 WifiConfiguration.Protocol.varName);
928 if (!TextUtils.isEmpty(value)) {
929 String vals[] = value.split(" ");
930 for (String val : vals) {
931 int index =
932 lookupString(val, WifiConfiguration.Protocol.strings);
933 if (0 <= index) {
934 config.allowedProtocols.set(index);
935 }
936 }
937 }
938
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800939 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 WifiConfiguration.KeyMgmt.varName);
941 if (!TextUtils.isEmpty(value)) {
942 String vals[] = value.split(" ");
943 for (String val : vals) {
944 int index =
945 lookupString(val, WifiConfiguration.KeyMgmt.strings);
946 if (0 <= index) {
947 config.allowedKeyManagement.set(index);
948 }
949 }
950 }
951
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800952 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 WifiConfiguration.AuthAlgorithm.varName);
954 if (!TextUtils.isEmpty(value)) {
955 String vals[] = value.split(" ");
956 for (String val : vals) {
957 int index =
958 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
959 if (0 <= index) {
960 config.allowedAuthAlgorithms.set(index);
961 }
962 }
963 }
964
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800965 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 WifiConfiguration.PairwiseCipher.varName);
967 if (!TextUtils.isEmpty(value)) {
968 String vals[] = value.split(" ");
969 for (String val : vals) {
970 int index =
971 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
972 if (0 <= index) {
973 config.allowedPairwiseCiphers.set(index);
974 }
975 }
976 }
977
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800978 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 WifiConfiguration.GroupCipher.varName);
980 if (!TextUtils.isEmpty(value)) {
981 String vals[] = value.split(" ");
982 for (String val : vals) {
983 int index =
984 lookupString(val, WifiConfiguration.GroupCipher.strings);
985 if (0 <= index) {
986 config.allowedGroupCiphers.set(index);
987 }
988 }
989 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800990
991 for (WifiConfiguration.EnterpriseField field :
992 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800993 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800994 field.varName());
995 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800996 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800997 field.setValue(value);
998 }
999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 }
1001
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001002 private static String removeDoubleQuotes(String string) {
1003 if (string.length() <= 2) return "";
1004 return string.substring(1, string.length() - 1);
1005 }
1006
1007 private static String convertToQuotedString(String string) {
1008 return "\"" + string + "\"";
1009 }
1010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 /**
1012 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1013 * @return the supplicant-assigned identifier for the new or updated
1014 * network if the operation succeeds, or {@code -1} if it fails
1015 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001016 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 /*
1020 * If the supplied networkId is -1, we create a new empty
1021 * network configuration. Otherwise, the networkId should
1022 * refer to an existing configuration.
1023 */
1024 int netId = config.networkId;
1025 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001026 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001028 synchronized (mWifiStateTracker) {
1029 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001030 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001031 if (netId < 0) {
1032 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001033 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001034 }
1035 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001037 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001039 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001042 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 /*
1044 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001045 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * will fail, so we don't bother to make a separate check
1047 * for the validity of the ID up front.
1048 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001050 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001051 netId,
1052 WifiConfiguration.ssidVarName,
1053 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001055 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057 break setVariables;
1058 }
1059
1060 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001061 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001062 netId,
1063 WifiConfiguration.bssidVarName,
1064 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001066 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 break setVariables;
1069 }
1070
1071 String allowedKeyManagementString =
1072 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1073 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001074 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001075 netId,
1076 WifiConfiguration.KeyMgmt.varName,
1077 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001080 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 break setVariables;
1083 }
1084
1085 String allowedProtocolsString =
1086 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1087 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001088 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001089 netId,
1090 WifiConfiguration.Protocol.varName,
1091 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001093 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001094 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 }
1096 break setVariables;
1097 }
1098
1099 String allowedAuthAlgorithmsString =
1100 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1101 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001102 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001103 netId,
1104 WifiConfiguration.AuthAlgorithm.varName,
1105 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001107 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001108 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110 break setVariables;
1111 }
1112
1113 String allowedPairwiseCiphersString =
1114 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1115 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001116 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001117 netId,
1118 WifiConfiguration.PairwiseCipher.varName,
1119 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001121 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001122 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 }
1124 break setVariables;
1125 }
1126
1127 String allowedGroupCiphersString =
1128 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1129 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001130 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001131 netId,
1132 WifiConfiguration.GroupCipher.varName,
1133 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001135 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001136 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
1138 break setVariables;
1139 }
1140
1141 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1142 // by preventing "*" as a key.
1143 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001144 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001145 netId,
1146 WifiConfiguration.pskVarName,
1147 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001149 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 }
1151 break setVariables;
1152 }
1153
1154 boolean hasSetKey = false;
1155 if (config.wepKeys != null) {
1156 for (int i = 0; i < config.wepKeys.length; i++) {
1157 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1158 // by preventing "*" as a key.
1159 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001160 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001161 netId,
1162 WifiConfiguration.wepKeyVarNames[i],
1163 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001165 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001166 "failed to set wep_key"+i+": " +
1167 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 break setVariables;
1170 }
1171 hasSetKey = true;
1172 }
1173 }
1174 }
1175
1176 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001177 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001178 netId,
1179 WifiConfiguration.wepTxKeyIdxVarName,
1180 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001182 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001183 "failed to set wep_tx_keyidx: "+
1184 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186 break setVariables;
1187 }
1188 }
1189
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001190 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001191 netId,
1192 WifiConfiguration.priorityVarName,
1193 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001195 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001196 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198 break setVariables;
1199 }
1200
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001201 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001202 netId,
1203 WifiConfiguration.hiddenSSIDVarName,
1204 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001206 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001207 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209 break setVariables;
1210 }
1211
Chung-yih Wang43374762009-09-16 14:28:42 +08001212 for (WifiConfiguration.EnterpriseField field
1213 : config.enterpriseFields) {
1214 String varName = field.varName();
1215 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001216 if (value != null) {
1217 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001218 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001219 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001220 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001221 netId,
1222 varName,
1223 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001224 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001225 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001226 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001227 }
1228 break setVariables;
1229 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001230 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001235 /*
1236 * For an update, if one of the setNetworkVariable operations fails,
1237 * we might want to roll back all the changes already made. But the
1238 * chances are that if anything is going to go wrong, it'll happen
1239 * the first time we try to set one of the variables.
1240 */
1241 if (newNetwork) {
1242 removeNetwork(netId);
1243 if (DBG) {
1244 Slog.d(TAG,
1245 "Failed to set a network variable, removed network: "
1246 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 }
1248 }
1249 return -1;
1250 }
1251
1252 private static String makeString(BitSet set, String[] strings) {
1253 StringBuffer buf = new StringBuffer();
1254 int nextSetBit = -1;
1255
1256 /* Make sure all set bits are in [0, strings.length) to avoid
1257 * going out of bounds on strings. (Shouldn't happen, but...) */
1258 set = set.get(0, strings.length);
1259
1260 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1261 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1262 }
1263
1264 // remove trailing space
1265 if (set.cardinality() > 0) {
1266 buf.setLength(buf.length() - 1);
1267 }
1268
1269 return buf.toString();
1270 }
1271
1272 private static int lookupString(String string, String[] strings) {
1273 int size = strings.length;
1274
1275 string = string.replace('-', '_');
1276
1277 for (int i = 0; i < size; i++)
1278 if (string.equals(strings[i]))
1279 return i;
1280
1281 if (DBG) {
1282 // if we ever get here, we should probably add the
1283 // value to WifiConfiguration to reflect that it's
1284 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001285 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
1287
1288 return -1;
1289 }
1290
1291 /**
1292 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1293 * @param netId the integer that identifies the network configuration
1294 * to the supplicant
1295 * @return {@code true} if the operation succeeded
1296 */
1297 public boolean removeNetwork(int netId) {
1298 enforceChangePermission();
1299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 return mWifiStateTracker.removeNetwork(netId);
1301 }
1302
1303 /**
1304 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1305 * @param netId the integer that identifies the network configuration
1306 * to the supplicant
1307 * @param disableOthers if true, disable all other networks.
1308 * @return {@code true} if the operation succeeded
1309 */
1310 public boolean enableNetwork(int netId, boolean disableOthers) {
1311 enforceChangePermission();
1312
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001313 String ifname = mWifiStateTracker.getInterfaceName();
1314 NetworkUtils.enableInterface(ifname);
1315 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1316 if (!result) {
1317 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001319 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321
1322 /**
1323 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1324 * @param netId the integer that identifies the network configuration
1325 * to the supplicant
1326 * @return {@code true} if the operation succeeded
1327 */
1328 public boolean disableNetwork(int netId) {
1329 enforceChangePermission();
1330
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001331 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333
1334 /**
1335 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1336 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1337 */
1338 public WifiInfo getConnectionInfo() {
1339 enforceAccessPermission();
1340 /*
1341 * Make sure we have the latest information, by sending
1342 * a status request to the supplicant.
1343 */
1344 return mWifiStateTracker.requestConnectionInfo();
1345 }
1346
1347 /**
1348 * Return the results of the most recent access point scan, in the form of
1349 * a list of {@link ScanResult} objects.
1350 * @return the list of results
1351 */
1352 public List<ScanResult> getScanResults() {
1353 enforceAccessPermission();
1354 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001355
1356 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 if (reply == null) {
1358 return null;
1359 }
1360
1361 List<ScanResult> scanList = new ArrayList<ScanResult>();
1362
1363 int lineCount = 0;
1364
1365 int replyLen = reply.length();
1366 // Parse the result string, keeping in mind that the last line does
1367 // not end with a newline.
1368 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1369 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1370 ++lineCount;
1371 /*
1372 * Skip the first line, which is a header
1373 */
1374 if (lineCount == 1) {
1375 lineBeg = lineEnd + 1;
1376 continue;
1377 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001378 if (lineEnd > lineBeg) {
1379 String line = reply.substring(lineBeg, lineEnd);
1380 ScanResult scanResult = parseScanResult(line);
1381 if (scanResult != null) {
1382 scanList.add(scanResult);
1383 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001384 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386 }
1387 lineBeg = lineEnd + 1;
1388 }
1389 }
1390 mWifiStateTracker.setScanResultsList(scanList);
1391 return scanList;
1392 }
1393
1394 /**
1395 * Parse the scan result line passed to us by wpa_supplicant (helper).
1396 * @param line the line to parse
1397 * @return the {@link ScanResult} object
1398 */
1399 private ScanResult parseScanResult(String line) {
1400 ScanResult scanResult = null;
1401 if (line != null) {
1402 /*
1403 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1404 * must synchronized here!
1405 */
1406 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001407 String[] result = scanResultPattern.split(line);
1408 if (3 <= result.length && result.length <= 5) {
1409 String bssid = result[0];
1410 // bssid | frequency | level | flags | ssid
1411 int frequency;
1412 int level;
1413 try {
1414 frequency = Integer.parseInt(result[1]);
1415 level = Integer.parseInt(result[2]);
1416 /* some implementations avoid negative values by adding 256
1417 * so we need to adjust for that here.
1418 */
1419 if (level > 0) level -= 256;
1420 } catch (NumberFormatException e) {
1421 frequency = 0;
1422 level = 0;
1423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Mike Lockwood1a645052009-06-25 13:01:12 -04001425 /*
1426 * The formatting of the results returned by
1427 * wpa_supplicant is intended to make the fields
1428 * line up nicely when printed,
1429 * not to make them easy to parse. So we have to
1430 * apply some heuristics to figure out which field
1431 * is the SSID and which field is the flags.
1432 */
1433 String ssid;
1434 String flags;
1435 if (result.length == 4) {
1436 if (result[3].charAt(0) == '[') {
1437 flags = result[3];
1438 ssid = "";
1439 } else {
1440 flags = "";
1441 ssid = result[3];
1442 }
1443 } else if (result.length == 5) {
1444 flags = result[3];
1445 ssid = result[4];
1446 } else {
1447 // Here, we must have 3 fields: no flags and ssid
1448 // set
1449 flags = "";
1450 ssid = "";
1451 }
1452
Mike Lockwood00717e22009-08-17 10:09:36 -04001453 // bssid + ssid is the hash key
1454 String key = bssid + ssid;
1455 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001456 if (scanResult != null) {
1457 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001458 scanResult.SSID = ssid;
1459 scanResult.capabilities = flags;
1460 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001461 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 // Do not add scan results that have no SSID set
1463 if (0 < ssid.trim().length()) {
1464 scanResult =
1465 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001466 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001467 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001470 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001471 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001472 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
1474 }
1475 }
1476
1477 return scanResult;
1478 }
1479
1480 /**
1481 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1482 * and construct a {@code WifiConfiguration} that describes the encryption,
1483 * key management, and authenticaion capabilities of the access point.
1484 * @param flags the string returned by wpa_supplicant
1485 * @return the {@link WifiConfiguration} object, filled in
1486 */
1487 WifiConfiguration parseScanFlags(String flags) {
1488 WifiConfiguration config = new WifiConfiguration();
1489
1490 if (flags.length() == 0) {
1491 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1492 }
1493 // ... to be implemented
1494 return config;
1495 }
1496
1497 /**
1498 * Tell the supplicant to persist the current list of configured networks.
1499 * @return {@code true} if the operation succeeded
1500 */
1501 public boolean saveConfiguration() {
1502 boolean result;
1503 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001506 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 if (result && mNeedReconfig) {
1508 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001509 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 if (result) {
1512 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1513 mContext.sendBroadcast(intent);
1514 }
1515 }
1516 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001517 // Inform the backup manager about a data change
1518 IBackupManager ibm = IBackupManager.Stub.asInterface(
1519 ServiceManager.getService(Context.BACKUP_SERVICE));
1520 if (ibm != null) {
1521 try {
1522 ibm.dataChanged("com.android.providers.settings");
1523 } catch (Exception e) {
1524 // Try again later
1525 }
1526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 return result;
1528 }
1529
1530 /**
1531 * Set the number of radio frequency channels that are allowed to be used
1532 * in the current regulatory domain. This method should be used only
1533 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001534 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 * persisted as a Secure setting.
1536 * @param numChannels the number of allowed channels. Must be greater than 0
1537 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001538 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1540 * {@code numChannels} is outside the valid range.
1541 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001542 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001543 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001544 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 /*
1548 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1549 * but if Wi-Fi isn't currently enabled, that's not possible, and
1550 * we want to persist the setting anyway,so that it will take
1551 * effect when Wi-Fi does become enabled.
1552 */
1553 boolean found = false;
1554 for (int validChan : sValidRegulatoryChannelCounts) {
1555 if (validChan == numChannels) {
1556 found = true;
1557 break;
1558 }
1559 }
1560 if (!found) {
1561 return false;
1562 }
1563
Irfan Sheriff59610c02010-03-30 11:00:41 -07001564 if (mWifiHandler == null) return false;
1565
1566 Message.obtain(mWifiHandler,
1567 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1568
1569 return true;
1570 }
1571
1572 /**
1573 * sets the number of allowed radio frequency channels synchronously
1574 * @param numChannels the number of allowed channels. Must be greater than 0
1575 * and less than or equal to 16.
1576 * @param persist {@code true} if the setting should be remembered.
1577 * @return {@code true} if the operation succeeds, {@code false} otherwise
1578 */
1579 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001580 if (persist) {
1581 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001582 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1583 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001584 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001585 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
1588 /**
1589 * Return the number of frequency channels that are allowed
1590 * to be used in the current regulatory domain.
1591 * @return the number of allowed channels, or {@code -1} if an error occurs
1592 */
1593 public int getNumAllowedChannels() {
1594 int numChannels;
1595
1596 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001597
1598 /*
1599 * If we can't get the value from the driver (e.g., because
1600 * Wi-Fi is not currently enabled), get the value from
1601 * Settings.
1602 */
1603 numChannels = mWifiStateTracker.getNumAllowedChannels();
1604 if (numChannels < 0) {
1605 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1606 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1607 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 return numChannels;
1610 }
1611
1612 /**
1613 * Return the list of valid values for the number of allowed radio channels
1614 * for various regulatory domains.
1615 * @return the list of channel counts
1616 */
1617 public int[] getValidChannelCounts() {
1618 enforceAccessPermission();
1619 return sValidRegulatoryChannelCounts;
1620 }
1621
1622 /**
1623 * Return the DHCP-assigned addresses from the last successful DHCP request,
1624 * if any.
1625 * @return the DHCP information
1626 */
1627 public DhcpInfo getDhcpInfo() {
1628 enforceAccessPermission();
1629 return mWifiStateTracker.getDhcpInfo();
1630 }
1631
1632 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1633 @Override
1634 public void onReceive(Context context, Intent intent) {
1635 String action = intent.getAction();
1636
Doug Zongker43866e02010-01-07 12:09:54 -08001637 long idleMillis =
1638 Settings.Secure.getLong(mContext.getContentResolver(),
1639 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001641 Settings.System.getInt(mContext.getContentResolver(),
1642 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001644 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 mAlarmManager.cancel(mIdleIntent);
1646 mDeviceIdle = false;
1647 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001648 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001652 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 /*
1654 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1655 * AND the "stay on while plugged in" setting doesn't match the
1656 * current power conditions (i.e, not plugged in, plugged in to USB,
1657 * or plugged in to AC).
1658 */
1659 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001660 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1661 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001662 // we used to go to sleep immediately, but this caused some race conditions
1663 // we don't have time to track down for this release. Delay instead, but not
1664 // as long as we would if connected (below)
1665 // TODO - fix the race conditions and switch back to the immediate turn-off
1666 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001667 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001668 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1669 // // do not keep Wifi awake when screen is off if Wifi is not associated
1670 // mDeviceIdle = true;
1671 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001672 } else {
1673 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001675 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 /* we can return now -- there's nothing to do until we get the idle intent back */
1679 return;
1680 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 mDeviceIdle = true;
1683 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1684 /*
1685 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1686 * AND we are transitioning from a state in which the device was supposed
1687 * to stay awake to a state in which it is not supposed to stay awake.
1688 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1689 * the already-set timer.
1690 */
1691 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001692 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1694 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1695 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001696 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1698 mPluggedType = pluggedType;
1699 return;
1700 }
1701 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001702 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001703 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1704 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1705 boolean isBluetoothPlaying = false;
1706 for (BluetoothDevice sink : sinks) {
1707 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1708 isBluetoothPlaying = true;
1709 }
1710 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001711 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 } else {
1714 return;
1715 }
1716
1717 updateWifiState();
1718 }
1719
1720 /**
1721 * Determines whether the Wi-Fi chipset should stay awake or be put to
1722 * sleep. Looks at the setting for the sleep policy and the current
1723 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001724 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 * @see #shouldDeviceStayAwake(int, int)
1726 */
1727 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1728 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1729 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1730
1731 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1732 // Never sleep
1733 return true;
1734 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1735 (pluggedType != 0)) {
1736 // Never sleep while plugged, and we're plugged
1737 return true;
1738 } else {
1739 // Default
1740 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1741 }
1742 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 /**
1745 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1746 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1747 * of {@code 0} isn't really a plugged type, but rather an indication that the
1748 * device isn't plugged in at all, there is no bit value corresponding to a
1749 * {@code pluggedType} value of {@code 0}. That is why we shift by
1750 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1751 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1752 * keep the device (and hence Wi-Fi) awake.
1753 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1754 * being made
1755 * @return {@code true} if {@code pluggedType} indicates that the device is
1756 * supposed to stay awake, {@code false} otherwise.
1757 */
1758 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1759 return (stayAwakeConditions & pluggedType) != 0;
1760 }
1761 };
1762
Dianne Hackborn617f8772009-03-31 15:04:46 -07001763 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 Message msg = Message.obtain(mWifiHandler,
1765 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001766 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 msg.sendToTarget();
1768 }
1769
1770 private void sendStartMessage(boolean scanOnlyMode) {
1771 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1772 }
1773
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001774 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1775 Message.obtain(mWifiHandler,
1776 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001777 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001778 }
1779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001781 // send a message so it's all serialized
1782 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1783 }
1784
1785 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001787 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 boolean lockHeld = mLocks.hasLocks();
1789 int strongestLockMode;
1790 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1791 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1792 if (mDeviceIdle && lockHeld) {
1793 strongestLockMode = mLocks.getStrongestLockMode();
1794 } else {
1795 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1796 }
1797
1798 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001799 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 return;
1801 }
1802 if (wifiShouldBeEnabled) {
1803 if (wifiShouldBeStarted) {
1804 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001805 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 sWakeLock.acquire();
1807 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001808 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 int wakeLockTimeout =
1810 Settings.Secure.getInt(
1811 mContext.getContentResolver(),
1812 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1813 DEFAULT_WAKELOCK_TIMEOUT);
1814 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001815 * We are assuming that ConnectivityService can make
1816 * a transition to cellular data within wakeLockTimeout time.
1817 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 */
1819 sDriverStopWakeLock.acquire();
1820 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1821 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1822 }
1823 } else {
1824 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001825 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828 }
1829
1830 private void registerForBroadcasts() {
1831 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1833 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1834 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1835 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001836 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 mContext.registerReceiver(mReceiver, intentFilter);
1838 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 private boolean isAirplaneSensitive() {
1841 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1842 Settings.System.AIRPLANE_MODE_RADIOS);
1843 return airplaneModeRadios == null
1844 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1845 }
1846
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001847 private boolean isAirplaneToggleable() {
1848 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1849 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1850 return toggleableRadios != null
1851 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1852 }
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 /**
1855 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1856 * currently on.
1857 * @return {@code true} if airplane mode is on.
1858 */
1859 private boolean isAirplaneModeOn() {
1860 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1861 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1862 }
1863
1864 /**
1865 * Handler that allows posting to the WifiThread.
1866 */
1867 private class WifiHandler extends Handler {
1868 public WifiHandler(Looper looper) {
1869 super(looper);
1870 }
1871
1872 @Override
1873 public void handleMessage(Message msg) {
1874 switch (msg.what) {
1875
1876 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001877 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001878 if (mWifiWatchdogService == null) {
1879 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 sWakeLock.release();
1882 break;
1883
1884 case MESSAGE_START_WIFI:
1885 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1886 mWifiStateTracker.restart();
1887 sWakeLock.release();
1888 break;
1889
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001890 case MESSAGE_UPDATE_STATE:
1891 doUpdateWifiState();
1892 break;
1893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 case MESSAGE_DISABLE_WIFI:
1895 // a non-zero msg.arg1 value means the "enabled" setting
1896 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001897 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001898 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 sWakeLock.release();
1900 break;
1901
1902 case MESSAGE_STOP_WIFI:
1903 mWifiStateTracker.disconnectAndStop();
1904 // don't release wakelock
1905 break;
1906
1907 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001908 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001910
1911 case MESSAGE_START_ACCESS_POINT:
1912 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001913 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001914 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001915 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001916 break;
1917
1918 case MESSAGE_STOP_ACCESS_POINT:
1919 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001920 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001921 (WifiConfiguration) msg.obj);
1922 sWakeLock.release();
1923 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001924
1925 case MESSAGE_SET_CHANNELS:
1926 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1927 break;
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930 }
1931 }
1932
1933 @Override
1934 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1935 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1936 != PackageManager.PERMISSION_GRANTED) {
1937 pw.println("Permission Denial: can't dump WifiService from from pid="
1938 + Binder.getCallingPid()
1939 + ", uid=" + Binder.getCallingUid());
1940 return;
1941 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001942 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 pw.println("Stay-awake conditions: " +
1944 Settings.System.getInt(mContext.getContentResolver(),
1945 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1946 pw.println();
1947
1948 pw.println("Internal state:");
1949 pw.println(mWifiStateTracker);
1950 pw.println();
1951 pw.println("Latest scan results:");
1952 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1953 if (scanResults != null && scanResults.size() != 0) {
1954 pw.println(" BSSID Frequency RSSI Flags SSID");
1955 for (ScanResult r : scanResults) {
1956 pw.printf(" %17s %9d %5d %-16s %s%n",
1957 r.BSSID,
1958 r.frequency,
1959 r.level,
1960 r.capabilities,
1961 r.SSID == null ? "" : r.SSID);
1962 }
1963 }
1964 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001965 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1966 mScanLocksAcquired + " scan");
1967 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1968 mScanLocksReleased + " scan");
1969 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 pw.println("Locks held:");
1971 mLocks.dump(pw);
1972 }
1973
1974 private static String stateName(int wifiState) {
1975 switch (wifiState) {
1976 case WIFI_STATE_DISABLING:
1977 return "disabling";
1978 case WIFI_STATE_DISABLED:
1979 return "disabled";
1980 case WIFI_STATE_ENABLING:
1981 return "enabling";
1982 case WIFI_STATE_ENABLED:
1983 return "enabled";
1984 case WIFI_STATE_UNKNOWN:
1985 return "unknown state";
1986 default:
1987 return "[invalid state]";
1988 }
1989 }
1990
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001991 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001993 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
1996 public void binderDied() {
1997 synchronized (mLocks) {
1998 releaseWifiLockLocked(mBinder);
1999 }
2000 }
2001
2002 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002003 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005 }
2006
2007 private class LockList {
2008 private List<WifiLock> mList;
2009
2010 private LockList() {
2011 mList = new ArrayList<WifiLock>();
2012 }
2013
2014 private synchronized boolean hasLocks() {
2015 return !mList.isEmpty();
2016 }
2017
2018 private synchronized int getStrongestLockMode() {
2019 if (mList.isEmpty()) {
2020 return WifiManager.WIFI_MODE_FULL;
2021 }
2022 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002023 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 return WifiManager.WIFI_MODE_FULL;
2025 }
2026 }
2027 return WifiManager.WIFI_MODE_SCAN_ONLY;
2028 }
2029
2030 private void addLock(WifiLock lock) {
2031 if (findLockByBinder(lock.mBinder) < 0) {
2032 mList.add(lock);
2033 }
2034 }
2035
2036 private WifiLock removeLock(IBinder binder) {
2037 int index = findLockByBinder(binder);
2038 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002039 WifiLock ret = mList.remove(index);
2040 ret.unlinkDeathRecipient();
2041 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 } else {
2043 return null;
2044 }
2045 }
2046
2047 private int findLockByBinder(IBinder binder) {
2048 int size = mList.size();
2049 for (int i = size - 1; i >= 0; i--)
2050 if (mList.get(i).mBinder == binder)
2051 return i;
2052 return -1;
2053 }
2054
2055 private void dump(PrintWriter pw) {
2056 for (WifiLock l : mList) {
2057 pw.print(" ");
2058 pw.println(l);
2059 }
2060 }
2061 }
2062
2063 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2064 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2065 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
2066 return false;
2067 }
2068 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2069 synchronized (mLocks) {
2070 return acquireWifiLockLocked(wifiLock);
2071 }
2072 }
2073
2074 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002075 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002078
The Android Open Source Project10592532009-03-18 17:39:46 -07002079 int uid = Binder.getCallingUid();
2080 long ident = Binder.clearCallingIdentity();
2081 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002082 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002083 case WifiManager.WIFI_MODE_FULL:
2084 ++mFullLocksAcquired;
2085 mBatteryStats.noteFullWifiLockAcquired(uid);
2086 break;
2087 case WifiManager.WIFI_MODE_SCAN_ONLY:
2088 ++mScanLocksAcquired;
2089 mBatteryStats.noteScanWifiLockAcquired(uid);
2090 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002091 }
2092 } catch (RemoteException e) {
2093 } finally {
2094 Binder.restoreCallingIdentity(ident);
2095 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 updateWifiState();
2098 return true;
2099 }
2100
2101 public boolean releaseWifiLock(IBinder lock) {
2102 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2103 synchronized (mLocks) {
2104 return releaseWifiLockLocked(lock);
2105 }
2106 }
2107
2108 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002109 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002110
The Android Open Source Project10592532009-03-18 17:39:46 -07002111 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002112
Joe Onorato8a9b2202010-02-26 18:56:32 -08002113 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002114
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002115 hadLock = (wifiLock != null);
2116
2117 if (hadLock) {
2118 int uid = Binder.getCallingUid();
2119 long ident = Binder.clearCallingIdentity();
2120 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002121 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002122 case WifiManager.WIFI_MODE_FULL:
2123 ++mFullLocksReleased;
2124 mBatteryStats.noteFullWifiLockReleased(uid);
2125 break;
2126 case WifiManager.WIFI_MODE_SCAN_ONLY:
2127 ++mScanLocksReleased;
2128 mBatteryStats.noteScanWifiLockReleased(uid);
2129 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002130 }
2131 } catch (RemoteException e) {
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002134 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002135 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002136 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002138 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002140
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002141 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002142 implements IBinder.DeathRecipient {
2143 String mTag;
2144 int mMode;
2145 IBinder mBinder;
2146
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002147 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002148 super();
2149 mTag = tag;
2150 mMode = mode;
2151 mBinder = binder;
2152 try {
2153 mBinder.linkToDeath(this, 0);
2154 } catch (RemoteException e) {
2155 binderDied();
2156 }
2157 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002158
2159 void unlinkDeathRecipient() {
2160 mBinder.unlinkToDeath(this, 0);
2161 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002162 }
2163
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002164 private class Multicaster extends DeathRecipient {
2165 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002166 super(Binder.getCallingUid(), tag, binder);
2167 }
2168
2169 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002170 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002171 synchronized (mMulticasters) {
2172 int i = mMulticasters.indexOf(this);
2173 if (i != -1) {
2174 removeMulticasterLocked(i, mMode);
2175 }
2176 }
2177 }
2178
2179 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002180 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002181 }
2182
2183 public int getUid() {
2184 return mMode;
2185 }
2186 }
2187
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002188 public void initializeMulticastFiltering() {
2189 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002190
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002191 synchronized (mMulticasters) {
2192 // if anybody had requested filters be off, leave off
2193 if (mMulticasters.size() != 0) {
2194 return;
2195 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002196 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002197 }
2198 }
2199 }
2200
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002201 public void acquireMulticastLock(IBinder binder, String tag) {
2202 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002203
2204 synchronized (mMulticasters) {
2205 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002206 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002207 // Note that we could call stopPacketFiltering only when
2208 // our new size == 1 (first call), but this function won't
2209 // be called often and by making the stopPacket call each
2210 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002211 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002212 }
2213
2214 int uid = Binder.getCallingUid();
2215 Long ident = Binder.clearCallingIdentity();
2216 try {
2217 mBatteryStats.noteWifiMulticastEnabled(uid);
2218 } catch (RemoteException e) {
2219 } finally {
2220 Binder.restoreCallingIdentity(ident);
2221 }
2222 }
2223
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002224 public void releaseMulticastLock() {
2225 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002226
2227 int uid = Binder.getCallingUid();
2228 synchronized (mMulticasters) {
2229 mMulticastDisabled++;
2230 int size = mMulticasters.size();
2231 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002232 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002233 if ((m != null) && (m.getUid() == uid)) {
2234 removeMulticasterLocked(i, uid);
2235 }
2236 }
2237 }
2238 }
2239
2240 private void removeMulticasterLocked(int i, int uid)
2241 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002242 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002243
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002244 if (removed != null) {
2245 removed.unlinkDeathRecipient();
2246 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002247 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002248 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002249 }
2250
2251 Long ident = Binder.clearCallingIdentity();
2252 try {
2253 mBatteryStats.noteWifiMulticastDisabled(uid);
2254 } catch (RemoteException e) {
2255 } finally {
2256 Binder.restoreCallingIdentity(ident);
2257 }
2258 }
2259
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002260 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002261 enforceAccessPermission();
2262
2263 synchronized (mMulticasters) {
2264 return (mMulticasters.size() > 0);
2265 }
2266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267}