blob: 0eca0825bca6a74c7a1cbd6f3dba703a0d6d3840 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
Irfan Sheriff5321aef2010-02-12 12:35:59 -080025import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
26import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
27import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
28import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
29import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.AlarmManager;
32import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070033import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080034import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.BroadcastReceiver;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.pm.PackageManager;
41import android.net.wifi.IWifiManager;
42import android.net.wifi.WifiInfo;
43import android.net.wifi.WifiManager;
44import android.net.wifi.WifiNative;
45import android.net.wifi.WifiStateTracker;
46import android.net.wifi.ScanResult;
47import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070048import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080049import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080050import android.net.ConnectivityManager;
51import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.NetworkStateTracker;
53import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040054import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
56import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080059import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
62import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070063import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070065import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.text.TextUtils;
69
70import java.util.ArrayList;
71import java.util.BitSet;
72import java.util.HashMap;
73import java.util.LinkedHashMap;
74import java.util.List;
75import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080076import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.regex.Pattern;
78import java.io.FileDescriptor;
79import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080080import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
The Android Open Source Project10592532009-03-18 17:39:46 -070082import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080083import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070084import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080085import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087/**
88 * WifiService handles remote WiFi operation requests by implementing
89 * the IWifiManager interface. It also creates a WifiMonitor to listen
90 * for Wifi-related events.
91 *
92 * @hide
93 */
94public class WifiService extends IWifiManager.Stub {
95 private static final String TAG = "WifiService";
96 private static final boolean DBG = false;
97 private static final Pattern scanResultPattern = Pattern.compile("\t+");
98 private final WifiStateTracker mWifiStateTracker;
Irfan Sheriffc2f54c22010-03-18 14:02:22 -070099 /* TODO: fetch a configurable interface */
100 private static final String SOFTAP_IFACE = "wl0.1";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 private Context mContext;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800103 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105 private AlarmManager mAlarmManager;
106 private PendingIntent mIdleIntent;
107 private static final int IDLE_REQUEST = 0;
108 private boolean mScreenOff;
109 private boolean mDeviceIdle;
110 private int mPluggedType;
111
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800112 private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
113
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700114 // true if the user enabled Wifi while in airplane mode
115 private boolean mAirplaneModeOverwridden;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700118 // some wifi lock statistics
Irfan Sheriff8c11e952010-08-12 20:26:23 -0700119 private int mFullHighPerfLocksAcquired;
120 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700121 private int mFullLocksAcquired;
122 private int mFullLocksReleased;
123 private int mScanLocksAcquired;
124 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700125
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700126 private final List<Multicaster> mMulticasters =
127 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700128 private int mMulticastEnabled;
129 private int mMulticastDisabled;
130
The Android Open Source Project10592532009-03-18 17:39:46 -0700131 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800132
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800133 private INetworkManagementService nwService;
134 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800135 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800136 private String[] mWifiRegexs;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800139 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
140 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 * the approximate point at which the battery drain caused by Wi-Fi
142 * being enabled but not active exceeds the battery drain caused by
143 * re-establishing a connection to the mobile data network.
144 */
145 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
146
147 private static final String WAKELOCK_TAG = "WifiService";
148
149 /**
150 * The maximum amount of time to hold the wake lock after a disconnect
151 * caused by stopping the driver. Establishing an EDGE connection has been
152 * observed to take about 5 seconds under normal circumstances. This
153 * provides a bit of extra margin.
154 * <p>
155 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
156 * This is the default value if a Settings.Secure value is not present.
157 */
158 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
159
160 // Wake lock used by driver-stop operation
161 private static PowerManager.WakeLock sDriverStopWakeLock;
162 // Wake lock used by other operations
163 private static PowerManager.WakeLock sWakeLock;
164
Irfan Sheriff59610c02010-03-30 11:00:41 -0700165 private static final int MESSAGE_ENABLE_WIFI = 0;
166 private static final int MESSAGE_DISABLE_WIFI = 1;
167 private static final int MESSAGE_STOP_WIFI = 2;
168 private static final int MESSAGE_START_WIFI = 3;
169 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
170 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800171 private static final int MESSAGE_START_ACCESS_POINT = 6;
172 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700173 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sherifffae66c32010-08-16 11:36:41 -0700174 private static final int MESSAGE_ENABLE_NETWORKS = 9;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177 private final WifiHandler mWifiHandler;
178
179 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 * Cache of scan results objects (size is somewhat arbitrary)
181 */
182 private static final int SCAN_RESULT_CACHE_SIZE = 80;
183 private final LinkedHashMap<String, ScanResult> mScanResultCache;
184
185 /*
186 * Character buffer used to parse scan results (optimization)
187 */
188 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 private boolean mNeedReconfig;
190
Dianne Hackborn617f8772009-03-31 15:04:46 -0700191 /*
192 * Last UID that asked to enable WIFI.
193 */
194 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800195
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700196 /*
197 * Last UID that asked to enable WIFI AP.
198 */
199 private int mLastApEnableUid = Process.myUid();
200
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 /**
203 * Number of allowed radio frequency channels in various regulatory domains.
204 * This list is sufficient for 802.11b/g networks (2.4GHz range).
205 */
206 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
207
208 private static final String ACTION_DEVICE_IDLE =
209 "com.android.server.WifiManager.action.DEVICE_IDLE";
210
211 WifiService(Context context, WifiStateTracker tracker) {
212 mContext = context;
213 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400214 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700215 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800216
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800217 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
218 nwService = INetworkManagementService.Stub.asInterface(b);
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 mScanResultCache = new LinkedHashMap<String, ScanResult>(
221 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
222 /*
223 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
224 * elements
225 */
226 public boolean removeEldestEntry(Map.Entry eldest) {
227 return SCAN_RESULT_CACHE_SIZE < this.size();
228 }
229 };
230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 HandlerThread wifiThread = new HandlerThread("WifiService");
232 wifiThread.start();
233 mWifiHandler = new WifiHandler(wifiThread.getLooper());
234
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800235 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800236 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
239 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
240 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
241
242 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
243 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
244 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 mContext.registerReceiver(
247 new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700250 // clear our flag indicating the user has overwridden airplane mode
251 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700252 // on airplane disable, restore Wifi if the saved state indicates so
253 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
254 persistWifiEnabled(true);
255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 updateWifiState();
257 }
258 },
259 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
260
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800261 mContext.registerReceiver(
262 new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265
266 ArrayList<String> available = intent.getStringArrayListExtra(
267 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
268 ArrayList<String> active = intent.getStringArrayListExtra(
269 ConnectivityManager.EXTRA_ACTIVE_TETHER);
270 updateTetherState(available, active);
271
272 }
273 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800274 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800275
Irfan Sheriff7b009782010-03-11 16:37:45 -0800276 /**
277 * Check if Wi-Fi needs to be enabled and start
278 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700279 *
280 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800281 */
282 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700283 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700284 boolean wifiEnabled = !isAirplaneModeOn()
285 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800286 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
287 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700288 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800289 }
290
291 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
292
293 boolean wifiTethered = false;
294 boolean wifiAvailable = false;
295
296 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
297 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
298
299 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
300 mWifiRegexs = mCm.getTetherableWifiRegexs();
301
302 for (String intf : available) {
303 for (String regex : mWifiRegexs) {
304 if (intf.matches(regex)) {
305
306 InterfaceConfiguration ifcg = null;
307 try {
308 ifcg = service.getInterfaceConfig(intf);
309 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700310 /* IP/netmask: 192.168.43.1/255.255.255.0 */
311 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800312 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
313 ifcg.interfaceFlags = "up";
314
315 service.setInterfaceConfig(intf, ifcg);
316 }
317 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800318 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700319 try {
320 nwService.stopAccessPoint();
321 } catch (Exception ee) {
322 Slog.e(TAG, "Could not stop AP, :" + ee);
323 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800324 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800325 return;
326 }
327
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800328 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800329 Slog.e(TAG, "Error tethering "+intf);
330 }
331 break;
332 }
333 }
334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700337 private boolean testAndClearWifiSavedState() {
338 final ContentResolver cr = mContext.getContentResolver();
339 int wifiSavedState = 0;
340 try {
341 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
342 if(wifiSavedState == 1)
343 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
344 } catch (Settings.SettingNotFoundException e) {
345 ;
346 }
347 return (wifiSavedState == 1);
348 }
349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 private boolean getPersistedWifiEnabled() {
351 final ContentResolver cr = mContext.getContentResolver();
352 try {
353 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
354 } catch (Settings.SettingNotFoundException e) {
355 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
356 return false;
357 }
358 }
359
360 private void persistWifiEnabled(boolean enabled) {
361 final ContentResolver cr = mContext.getContentResolver();
362 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
363 }
364
365 NetworkStateTracker getNetworkStateTracker() {
366 return mWifiStateTracker;
367 }
368
369 /**
370 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
371 * @return {@code true} if the operation succeeds
372 */
373 public boolean pingSupplicant() {
374 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800375
376 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
378
379 /**
380 * see {@link android.net.wifi.WifiManager#startScan()}
381 * @return {@code true} if the operation succeeds
382 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400383 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800385
386 switch (mWifiStateTracker.getSupplicantState()) {
387 case DISCONNECTED:
388 case INACTIVE:
389 case SCANNING:
390 case DORMANT:
391 break;
392 default:
393 mWifiStateTracker.setScanResultHandling(
394 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
395 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800397 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 }
399
400 /**
401 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
402 * @param enable {@code true} to enable, {@code false} to disable.
403 * @return {@code true} if the enable/disable operation was
404 * started or is already in the queue.
405 */
406 public boolean setWifiEnabled(boolean enable) {
407 enforceChangePermission();
408 if (mWifiHandler == null) return false;
409
410 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700411 // caller may not have WAKE_LOCK permission - it's not required here
412 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700414 Binder.restoreCallingIdentity(ident);
415
Dianne Hackborn617f8772009-03-31 15:04:46 -0700416 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700417 // set a flag if the user is enabling Wifi while in airplane mode
418 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700419 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 }
421
422 return true;
423 }
424
425 /**
426 * Enables/disables Wi-Fi synchronously.
427 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
428 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700429 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 * @return {@code true} if the operation succeeds (or if the existing state
431 * is the same as the requested state)
432 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700433 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800435 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800437 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 return true;
439 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700440 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 return false;
442 }
443
Irfan Sheriffcd770372010-01-08 09:36:04 -0800444 /**
445 * Multiple calls to unregisterReceiver() cause exception and a system crash.
446 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
447 * disable wifi at the same time.
448 * Avoid doing a disable when the current Wifi state is UNKNOWN
449 * TODO: Handle driver load fail and supplicant lost as seperate states
450 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800451 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800452 return false;
453 }
454
Irfan Sherifff91444c2010-03-24 12:11:00 -0700455 /**
456 * Fail Wifi if AP is enabled
457 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
458 * WIFI_STATE_FAILED
459 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800460 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700461 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
462 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800463 }
464
Irfan Sherifff91444c2010-03-24 12:11:00 -0700465 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800468 if (!mWifiStateTracker.loadDriver()) {
469 Slog.e(TAG, "Failed to load Wi-Fi driver.");
470 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
471 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800473 if (!mWifiStateTracker.startSupplicant()) {
474 mWifiStateTracker.unloadDriver();
475 Slog.e(TAG, "Failed to start supplicant daemon.");
476 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
477 return false;
478 }
479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 registerForBroadcasts();
481 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 } else {
484
485 mContext.unregisterReceiver(mReceiver);
486 // Remove notification (it will no-op if it isn't visible)
487 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
488
489 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800490
491 if (!mWifiStateTracker.stopSupplicant()) {
492 Slog.e(TAG, "Failed to stop supplicant daemon.");
493 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
494 failedToStopSupplicantOrUnloadDriver = true;
495 }
496
497 /**
498 * Reset connections and disable interface
499 * before we unload the driver
500 */
501 mWifiStateTracker.resetConnections(true);
502
503 if (!mWifiStateTracker.unloadDriver()) {
504 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
505 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700506 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 failedToStopSupplicantOrUnloadDriver = true;
508 }
509 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 if (failedToStopSupplicantOrUnloadDriver) {
512 return false;
513 }
514 }
515
516 // Success!
517
518 if (persist) {
519 persistWifiEnabled(enable);
520 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700521 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 return true;
523 }
524
Dianne Hackborn617f8772009-03-31 15:04:46 -0700525 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800526 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
The Android Open Source Project10592532009-03-18 17:39:46 -0700528 long ident = Binder.clearCallingIdentity();
529 try {
530 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700531 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700532 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700533 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700534 }
535 } catch (RemoteException e) {
536 } finally {
537 Binder.restoreCallingIdentity(ident);
538 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800541 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542
543 // Broadcast
544 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
545 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
546 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
547 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
548 mContext.sendStickyBroadcast(intent);
549 }
550
551 private void enforceAccessPermission() {
552 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
553 "WifiService");
554 }
555
556 private void enforceChangePermission() {
557 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
558 "WifiService");
559
560 }
561
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700562 private void enforceMulticastChangePermission() {
563 mContext.enforceCallingOrSelfPermission(
564 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
565 "WifiService");
566 }
567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 /**
569 * see {@link WifiManager#getWifiState()}
570 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
571 * {@link WifiManager#WIFI_STATE_DISABLING},
572 * {@link WifiManager#WIFI_STATE_ENABLED},
573 * {@link WifiManager#WIFI_STATE_ENABLING},
574 * {@link WifiManager#WIFI_STATE_UNKNOWN}
575 */
576 public int getWifiEnabledState() {
577 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800578 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580
581 /**
582 * see {@link android.net.wifi.WifiManager#disconnect()}
583 * @return {@code true} if the operation succeeds
584 */
585 public boolean disconnect() {
586 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800587
588 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 }
590
591 /**
592 * see {@link android.net.wifi.WifiManager#reconnect()}
593 * @return {@code true} if the operation succeeds
594 */
595 public boolean reconnect() {
596 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800597
598 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
600
601 /**
602 * see {@link android.net.wifi.WifiManager#reassociate()}
603 * @return {@code true} if the operation succeeds
604 */
605 public boolean reassociate() {
606 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800607
608 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
610
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800611 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700612 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800613 * @param wifiConfig SSID, security and channel details as
614 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700615 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800616 * @return {@code true} if the start operation was
617 * started or is already in the queue.
618 */
619 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
620 enforceChangePermission();
621 if (mWifiHandler == null) return false;
622
623 synchronized (mWifiHandler) {
624
625 long ident = Binder.clearCallingIdentity();
626 sWakeLock.acquire();
627 Binder.restoreCallingIdentity(ident);
628
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700629 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800630 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
631 }
632
633 return true;
634 }
635
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800636 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700637 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800638 final ContentResolver cr = mContext.getContentResolver();
639 WifiConfiguration wifiConfig = new WifiConfiguration();
640 int authType;
641 try {
642 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
643 if (wifiConfig.SSID == null)
644 return null;
645 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
646 wifiConfig.allowedKeyManagement.set(authType);
647 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
648 return wifiConfig;
649 } catch (Settings.SettingNotFoundException e) {
650 Slog.e(TAG,"AP settings not found, returning");
651 return null;
652 }
653 }
654
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700655 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
656 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800657 final ContentResolver cr = mContext.getContentResolver();
658 boolean isWpa;
659 if (wifiConfig == null)
660 return;
661 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
662 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
663 Settings.Secure.putInt(cr,
664 Settings.Secure.WIFI_AP_SECURITY,
665 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
666 if (isWpa)
667 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
668 }
669
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800670 /**
671 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
672 * and soft access point configured as a single operation.
673 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800674 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800675 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800676 * @return {@code true} if the operation succeeds (or if the existing state
677 * is the same as the requested state)
678 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800679 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800680 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800681 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
682
683 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800684 /* Configuration changed on a running access point */
685 if(enable && (wifiConfig != null)) {
686 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700687 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
688 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700689 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800690 return true;
691 } catch(Exception e) {
692 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700693 try {
694 nwService.stopAccessPoint();
695 } catch (Exception ee) {
696 Slog.e(TAG, "Could not stop AP, :" + ee);
697 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800698 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
699 return false;
700 }
701 } else {
702 return true;
703 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800704 }
705
Irfan Sherifff91444c2010-03-24 12:11:00 -0700706 /**
707 * Fail AP if Wifi is enabled
708 */
709 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
710 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
711 return false;
712 }
713
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800714 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
715 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800716
717 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800718
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800719 /* Use default config if there is no existing config */
720 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
721 wifiConfig = new WifiConfiguration();
722 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
723 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
724 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800725
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800726 if (!mWifiStateTracker.loadDriver()) {
727 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800728 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800729 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800730 }
731
732 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700733 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
734 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800735 } catch(Exception e) {
736 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800737 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
738 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800739 }
740
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700741 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700742
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800743 } else {
744
745 try {
746 nwService.stopAccessPoint();
747 } catch(Exception e) {
748 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800749 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
750 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800751 }
752
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800753 if (!mWifiStateTracker.unloadDriver()) {
754 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800755 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800756 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800757 }
758 }
759
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800760 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800761 return true;
762 }
763
764 /**
765 * see {@link WifiManager#getWifiApState()}
766 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
767 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
768 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
769 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
770 * {@link WifiManager#WIFI_AP_STATE_FAILED}
771 */
772 public int getWifiApEnabledState() {
773 enforceAccessPermission();
774 return mWifiApState;
775 }
776
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800777 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800778 final int previousWifiApState = mWifiApState;
779
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800780 /**
781 * Unload the driver if going to a failed state
782 */
783 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
784 mWifiStateTracker.unloadDriver();
785 }
786
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800787 long ident = Binder.clearCallingIdentity();
788 try {
789 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
790 mBatteryStats.noteWifiOn(uid);
791 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
792 mBatteryStats.noteWifiOff(uid);
793 }
794 } catch (RemoteException e) {
795 } finally {
796 Binder.restoreCallingIdentity(ident);
797 }
798
799 // Update state
800 mWifiApState = wifiAPState;
801
802 // Broadcast
803 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
804 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
805 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
806 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
807 mContext.sendStickyBroadcast(intent);
808 }
809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 /**
811 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
812 * @return the list of configured networks
813 */
814 public List<WifiConfiguration> getConfiguredNetworks() {
815 enforceAccessPermission();
816 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 /*
819 * We don't cache the list, because we want to allow
820 * for the possibility that the configuration file
821 * has been modified through some external means,
822 * such as the wpa_cli command line program.
823 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800824 listStr = mWifiStateTracker.listNetworks();
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 List<WifiConfiguration> networks =
827 new ArrayList<WifiConfiguration>();
828 if (listStr == null)
829 return networks;
830
831 String[] lines = listStr.split("\n");
832 // Skip the first line, which is a header
833 for (int i = 1; i < lines.length; i++) {
834 String[] result = lines[i].split("\t");
835 // network-id | ssid | bssid | flags
836 WifiConfiguration config = new WifiConfiguration();
837 try {
838 config.networkId = Integer.parseInt(result[0]);
839 } catch(NumberFormatException e) {
840 continue;
841 }
842 if (result.length > 3) {
843 if (result[3].indexOf("[CURRENT]") != -1)
844 config.status = WifiConfiguration.Status.CURRENT;
845 else if (result[3].indexOf("[DISABLED]") != -1)
846 config.status = WifiConfiguration.Status.DISABLED;
847 else
848 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800849 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800852 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 networks.add(config);
854 }
855
856 return networks;
857 }
858
859 /**
860 * Read the variables from the supplicant daemon that are needed to
861 * fill in the WifiConfiguration object.
862 * <p/>
863 * The caller must hold the synchronization monitor.
864 * @param config the {@link WifiConfiguration} object to be filled in.
865 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800866 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
868 int netId = config.networkId;
869 if (netId < 0)
870 return;
871
872 /*
873 * TODO: maybe should have a native method that takes an array of
874 * variable names and returns an array of values. But we'd still
875 * be doing a round trip to the supplicant daemon for each variable.
876 */
877 String value;
878
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800879 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800881 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 } else {
883 config.SSID = null;
884 }
885
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800886 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 if (!TextUtils.isEmpty(value)) {
888 config.BSSID = value;
889 } else {
890 config.BSSID = null;
891 }
892
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800893 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 config.priority = -1;
895 if (!TextUtils.isEmpty(value)) {
896 try {
897 config.priority = Integer.parseInt(value);
898 } catch (NumberFormatException ignore) {
899 }
900 }
901
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800902 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 config.hiddenSSID = false;
904 if (!TextUtils.isEmpty(value)) {
905 try {
906 config.hiddenSSID = Integer.parseInt(value) != 0;
907 } catch (NumberFormatException ignore) {
908 }
909 }
910
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800911 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 config.wepTxKeyIndex = -1;
913 if (!TextUtils.isEmpty(value)) {
914 try {
915 config.wepTxKeyIndex = Integer.parseInt(value);
916 } catch (NumberFormatException ignore) {
917 }
918 }
919
920 /*
921 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
922 * just a "*" if the key is set, or the null string otherwise.
923 */
924 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800925 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 if (!TextUtils.isEmpty(value)) {
927 config.wepKeys[i] = value;
928 } else {
929 config.wepKeys[i] = null;
930 }
931 }
932
933 /*
934 * Get the private shared key. Note that the actual keys are not passed back,
935 * just a "*" if the key is set, or the null string otherwise.
936 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800937 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 if (!TextUtils.isEmpty(value)) {
939 config.preSharedKey = value;
940 } else {
941 config.preSharedKey = null;
942 }
943
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800944 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 WifiConfiguration.Protocol.varName);
946 if (!TextUtils.isEmpty(value)) {
947 String vals[] = value.split(" ");
948 for (String val : vals) {
949 int index =
950 lookupString(val, WifiConfiguration.Protocol.strings);
951 if (0 <= index) {
952 config.allowedProtocols.set(index);
953 }
954 }
955 }
956
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800957 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 WifiConfiguration.KeyMgmt.varName);
959 if (!TextUtils.isEmpty(value)) {
960 String vals[] = value.split(" ");
961 for (String val : vals) {
962 int index =
963 lookupString(val, WifiConfiguration.KeyMgmt.strings);
964 if (0 <= index) {
965 config.allowedKeyManagement.set(index);
966 }
967 }
968 }
969
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800970 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 WifiConfiguration.AuthAlgorithm.varName);
972 if (!TextUtils.isEmpty(value)) {
973 String vals[] = value.split(" ");
974 for (String val : vals) {
975 int index =
976 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
977 if (0 <= index) {
978 config.allowedAuthAlgorithms.set(index);
979 }
980 }
981 }
982
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800983 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 WifiConfiguration.PairwiseCipher.varName);
985 if (!TextUtils.isEmpty(value)) {
986 String vals[] = value.split(" ");
987 for (String val : vals) {
988 int index =
989 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
990 if (0 <= index) {
991 config.allowedPairwiseCiphers.set(index);
992 }
993 }
994 }
995
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800996 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 WifiConfiguration.GroupCipher.varName);
998 if (!TextUtils.isEmpty(value)) {
999 String vals[] = value.split(" ");
1000 for (String val : vals) {
1001 int index =
1002 lookupString(val, WifiConfiguration.GroupCipher.strings);
1003 if (0 <= index) {
1004 config.allowedGroupCiphers.set(index);
1005 }
1006 }
1007 }
Chung-yih Wang43374762009-09-16 14:28:42 +08001008
1009 for (WifiConfiguration.EnterpriseField field :
1010 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001011 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +08001012 field.varName());
1013 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001014 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001015 field.setValue(value);
1016 }
1017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001020 private static String removeDoubleQuotes(String string) {
1021 if (string.length() <= 2) return "";
1022 return string.substring(1, string.length() - 1);
1023 }
1024
1025 private static String convertToQuotedString(String string) {
1026 return "\"" + string + "\"";
1027 }
1028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 /**
1030 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1031 * @return the supplicant-assigned identifier for the new or updated
1032 * network if the operation succeeds, or {@code -1} if it fails
1033 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001034 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /*
1038 * If the supplied networkId is -1, we create a new empty
1039 * network configuration. Otherwise, the networkId should
1040 * refer to an existing configuration.
1041 */
1042 int netId = config.networkId;
1043 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001044 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001046 synchronized (mWifiStateTracker) {
1047 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001048 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001049 if (netId < 0) {
1050 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001051 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001052 }
1053 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001055 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001057 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001060 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 /*
1062 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001063 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 * will fail, so we don't bother to make a separate check
1065 * for the validity of the ID up front.
1066 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001068 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001069 netId,
1070 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001071 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001073 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075 break setVariables;
1076 }
1077
1078 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001079 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001080 netId,
1081 WifiConfiguration.bssidVarName,
1082 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001084 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086 break setVariables;
1087 }
1088
1089 String allowedKeyManagementString =
1090 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1091 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001092 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001093 netId,
1094 WifiConfiguration.KeyMgmt.varName,
1095 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001097 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001098 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100 break setVariables;
1101 }
1102
1103 String allowedProtocolsString =
1104 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1105 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001106 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001107 netId,
1108 WifiConfiguration.Protocol.varName,
1109 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001111 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001112 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
1114 break setVariables;
1115 }
1116
1117 String allowedAuthAlgorithmsString =
1118 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1119 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001120 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001121 netId,
1122 WifiConfiguration.AuthAlgorithm.varName,
1123 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001125 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001126 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 }
1128 break setVariables;
1129 }
1130
1131 String allowedPairwiseCiphersString =
1132 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1133 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001134 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001135 netId,
1136 WifiConfiguration.PairwiseCipher.varName,
1137 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001139 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001140 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142 break setVariables;
1143 }
1144
1145 String allowedGroupCiphersString =
1146 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1147 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001148 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001149 netId,
1150 WifiConfiguration.GroupCipher.varName,
1151 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001154 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156 break setVariables;
1157 }
1158
1159 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1160 // by preventing "*" as a key.
1161 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001162 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001163 netId,
1164 WifiConfiguration.pskVarName,
1165 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001167 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 break setVariables;
1170 }
1171
1172 boolean hasSetKey = false;
1173 if (config.wepKeys != null) {
1174 for (int i = 0; i < config.wepKeys.length; i++) {
1175 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1176 // by preventing "*" as a key.
1177 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001178 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001179 netId,
1180 WifiConfiguration.wepKeyVarNames[i],
1181 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001183 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001184 "failed to set wep_key"+i+": " +
1185 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187 break setVariables;
1188 }
1189 hasSetKey = true;
1190 }
1191 }
1192 }
1193
1194 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001195 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001196 netId,
1197 WifiConfiguration.wepTxKeyIdxVarName,
1198 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001200 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001201 "failed to set wep_tx_keyidx: "+
1202 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 }
1204 break setVariables;
1205 }
1206 }
1207
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001208 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001209 netId,
1210 WifiConfiguration.priorityVarName,
1211 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001213 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001214 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 }
1216 break setVariables;
1217 }
1218
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001219 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001220 netId,
1221 WifiConfiguration.hiddenSSIDVarName,
1222 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001225 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227 break setVariables;
1228 }
1229
Chung-yih Wang43374762009-09-16 14:28:42 +08001230 for (WifiConfiguration.EnterpriseField field
1231 : config.enterpriseFields) {
1232 String varName = field.varName();
1233 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001234 if (value != null) {
1235 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001236 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001237 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001238 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001239 netId,
1240 varName,
1241 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001242 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001243 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001244 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001245 }
1246 break setVariables;
1247 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001248 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001253 /*
1254 * For an update, if one of the setNetworkVariable operations fails,
1255 * we might want to roll back all the changes already made. But the
1256 * chances are that if anything is going to go wrong, it'll happen
1257 * the first time we try to set one of the variables.
1258 */
1259 if (newNetwork) {
1260 removeNetwork(netId);
1261 if (DBG) {
1262 Slog.d(TAG,
1263 "Failed to set a network variable, removed network: "
1264 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
1266 }
1267 return -1;
1268 }
1269
1270 private static String makeString(BitSet set, String[] strings) {
1271 StringBuffer buf = new StringBuffer();
1272 int nextSetBit = -1;
1273
1274 /* Make sure all set bits are in [0, strings.length) to avoid
1275 * going out of bounds on strings. (Shouldn't happen, but...) */
1276 set = set.get(0, strings.length);
1277
1278 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1279 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1280 }
1281
1282 // remove trailing space
1283 if (set.cardinality() > 0) {
1284 buf.setLength(buf.length() - 1);
1285 }
1286
1287 return buf.toString();
1288 }
1289
1290 private static int lookupString(String string, String[] strings) {
1291 int size = strings.length;
1292
1293 string = string.replace('-', '_');
1294
1295 for (int i = 0; i < size; i++)
1296 if (string.equals(strings[i]))
1297 return i;
1298
1299 if (DBG) {
1300 // if we ever get here, we should probably add the
1301 // value to WifiConfiguration to reflect that it's
1302 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001303 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305
1306 return -1;
1307 }
1308
1309 /**
1310 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1311 * @param netId the integer that identifies the network configuration
1312 * to the supplicant
1313 * @return {@code true} if the operation succeeded
1314 */
1315 public boolean removeNetwork(int netId) {
1316 enforceChangePermission();
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 return mWifiStateTracker.removeNetwork(netId);
1319 }
1320
1321 /**
1322 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1323 * @param netId the integer that identifies the network configuration
1324 * to the supplicant
1325 * @param disableOthers if true, disable all other networks.
1326 * @return {@code true} if the operation succeeded
1327 */
1328 public boolean enableNetwork(int netId, boolean disableOthers) {
1329 enforceChangePermission();
1330
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001331 String ifname = mWifiStateTracker.getInterfaceName();
1332 NetworkUtils.enableInterface(ifname);
1333 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1334 if (!result) {
1335 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001337 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
1340 /**
1341 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1342 * @param netId the integer that identifies the network configuration
1343 * to the supplicant
1344 * @return {@code true} if the operation succeeded
1345 */
1346 public boolean disableNetwork(int netId) {
1347 enforceChangePermission();
1348
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001349 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351
1352 /**
1353 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1354 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1355 */
1356 public WifiInfo getConnectionInfo() {
1357 enforceAccessPermission();
1358 /*
1359 * Make sure we have the latest information, by sending
1360 * a status request to the supplicant.
1361 */
1362 return mWifiStateTracker.requestConnectionInfo();
1363 }
1364
1365 /**
1366 * Return the results of the most recent access point scan, in the form of
1367 * a list of {@link ScanResult} objects.
1368 * @return the list of results
1369 */
1370 public List<ScanResult> getScanResults() {
1371 enforceAccessPermission();
1372 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001373
1374 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 if (reply == null) {
1376 return null;
1377 }
1378
1379 List<ScanResult> scanList = new ArrayList<ScanResult>();
1380
1381 int lineCount = 0;
1382
1383 int replyLen = reply.length();
1384 // Parse the result string, keeping in mind that the last line does
1385 // not end with a newline.
1386 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1387 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1388 ++lineCount;
1389 /*
1390 * Skip the first line, which is a header
1391 */
1392 if (lineCount == 1) {
1393 lineBeg = lineEnd + 1;
1394 continue;
1395 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001396 if (lineEnd > lineBeg) {
1397 String line = reply.substring(lineBeg, lineEnd);
1398 ScanResult scanResult = parseScanResult(line);
1399 if (scanResult != null) {
1400 scanList.add(scanResult);
1401 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001402 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 }
1405 lineBeg = lineEnd + 1;
1406 }
1407 }
1408 mWifiStateTracker.setScanResultsList(scanList);
1409 return scanList;
1410 }
1411
1412 /**
1413 * Parse the scan result line passed to us by wpa_supplicant (helper).
1414 * @param line the line to parse
1415 * @return the {@link ScanResult} object
1416 */
1417 private ScanResult parseScanResult(String line) {
1418 ScanResult scanResult = null;
1419 if (line != null) {
1420 /*
1421 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1422 * must synchronized here!
1423 */
1424 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001425 String[] result = scanResultPattern.split(line);
1426 if (3 <= result.length && result.length <= 5) {
1427 String bssid = result[0];
1428 // bssid | frequency | level | flags | ssid
1429 int frequency;
1430 int level;
1431 try {
1432 frequency = Integer.parseInt(result[1]);
1433 level = Integer.parseInt(result[2]);
1434 /* some implementations avoid negative values by adding 256
1435 * so we need to adjust for that here.
1436 */
1437 if (level > 0) level -= 256;
1438 } catch (NumberFormatException e) {
1439 frequency = 0;
1440 level = 0;
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442
Mike Lockwood1a645052009-06-25 13:01:12 -04001443 /*
1444 * The formatting of the results returned by
1445 * wpa_supplicant is intended to make the fields
1446 * line up nicely when printed,
1447 * not to make them easy to parse. So we have to
1448 * apply some heuristics to figure out which field
1449 * is the SSID and which field is the flags.
1450 */
1451 String ssid;
1452 String flags;
1453 if (result.length == 4) {
1454 if (result[3].charAt(0) == '[') {
1455 flags = result[3];
1456 ssid = "";
1457 } else {
1458 flags = "";
1459 ssid = result[3];
1460 }
1461 } else if (result.length == 5) {
1462 flags = result[3];
1463 ssid = result[4];
1464 } else {
1465 // Here, we must have 3 fields: no flags and ssid
1466 // set
1467 flags = "";
1468 ssid = "";
1469 }
1470
Mike Lockwood00717e22009-08-17 10:09:36 -04001471 // bssid + ssid is the hash key
1472 String key = bssid + ssid;
1473 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001474 if (scanResult != null) {
1475 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001476 scanResult.SSID = ssid;
1477 scanResult.capabilities = flags;
1478 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001479 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 // Do not add scan results that have no SSID set
1481 if (0 < ssid.trim().length()) {
1482 scanResult =
1483 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001484 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001485 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001488 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001489 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001490 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 }
1493 }
1494
1495 return scanResult;
1496 }
1497
1498 /**
1499 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1500 * and construct a {@code WifiConfiguration} that describes the encryption,
1501 * key management, and authenticaion capabilities of the access point.
1502 * @param flags the string returned by wpa_supplicant
1503 * @return the {@link WifiConfiguration} object, filled in
1504 */
1505 WifiConfiguration parseScanFlags(String flags) {
1506 WifiConfiguration config = new WifiConfiguration();
1507
1508 if (flags.length() == 0) {
1509 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1510 }
1511 // ... to be implemented
1512 return config;
1513 }
1514
1515 /**
1516 * Tell the supplicant to persist the current list of configured networks.
1517 * @return {@code true} if the operation succeeded
1518 */
1519 public boolean saveConfiguration() {
1520 boolean result;
1521 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001524 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 if (result && mNeedReconfig) {
1526 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001527 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528
1529 if (result) {
1530 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1531 mContext.sendBroadcast(intent);
1532 }
1533 }
1534 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001535 // Inform the backup manager about a data change
1536 IBackupManager ibm = IBackupManager.Stub.asInterface(
1537 ServiceManager.getService(Context.BACKUP_SERVICE));
1538 if (ibm != null) {
1539 try {
1540 ibm.dataChanged("com.android.providers.settings");
1541 } catch (Exception e) {
1542 // Try again later
1543 }
1544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 return result;
1546 }
1547
1548 /**
1549 * Set the number of radio frequency channels that are allowed to be used
1550 * in the current regulatory domain. This method should be used only
1551 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001552 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 * persisted as a Secure setting.
1554 * @param numChannels the number of allowed channels. Must be greater than 0
1555 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001556 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1558 * {@code numChannels} is outside the valid range.
1559 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001560 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001561 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001562 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 /*
1566 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1567 * but if Wi-Fi isn't currently enabled, that's not possible, and
1568 * we want to persist the setting anyway,so that it will take
1569 * effect when Wi-Fi does become enabled.
1570 */
1571 boolean found = false;
1572 for (int validChan : sValidRegulatoryChannelCounts) {
1573 if (validChan == numChannels) {
1574 found = true;
1575 break;
1576 }
1577 }
1578 if (!found) {
1579 return false;
1580 }
1581
Irfan Sheriff59610c02010-03-30 11:00:41 -07001582 if (mWifiHandler == null) return false;
1583
1584 Message.obtain(mWifiHandler,
1585 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1586
1587 return true;
1588 }
1589
1590 /**
1591 * sets the number of allowed radio frequency channels synchronously
1592 * @param numChannels the number of allowed channels. Must be greater than 0
1593 * and less than or equal to 16.
1594 * @param persist {@code true} if the setting should be remembered.
1595 * @return {@code true} if the operation succeeds, {@code false} otherwise
1596 */
1597 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001598 if (persist) {
1599 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001600 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1601 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001602 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001603 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
1605
1606 /**
1607 * Return the number of frequency channels that are allowed
1608 * to be used in the current regulatory domain.
1609 * @return the number of allowed channels, or {@code -1} if an error occurs
1610 */
1611 public int getNumAllowedChannels() {
1612 int numChannels;
1613
1614 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001615
1616 /*
1617 * If we can't get the value from the driver (e.g., because
1618 * Wi-Fi is not currently enabled), get the value from
1619 * Settings.
1620 */
1621 numChannels = mWifiStateTracker.getNumAllowedChannels();
1622 if (numChannels < 0) {
1623 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1624 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1625 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627 return numChannels;
1628 }
1629
1630 /**
1631 * Return the list of valid values for the number of allowed radio channels
1632 * for various regulatory domains.
1633 * @return the list of channel counts
1634 */
1635 public int[] getValidChannelCounts() {
1636 enforceAccessPermission();
1637 return sValidRegulatoryChannelCounts;
1638 }
1639
1640 /**
1641 * Return the DHCP-assigned addresses from the last successful DHCP request,
1642 * if any.
1643 * @return the DHCP information
1644 */
1645 public DhcpInfo getDhcpInfo() {
1646 enforceAccessPermission();
1647 return mWifiStateTracker.getDhcpInfo();
1648 }
1649
1650 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1651 @Override
1652 public void onReceive(Context context, Intent intent) {
1653 String action = intent.getAction();
1654
Doug Zongker43866e02010-01-07 12:09:54 -08001655 long idleMillis =
1656 Settings.Secure.getLong(mContext.getContentResolver(),
1657 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001659 Settings.System.getInt(mContext.getContentResolver(),
1660 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001662 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 mAlarmManager.cancel(mIdleIntent);
1664 mDeviceIdle = false;
1665 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001666 mWifiStateTracker.enableRssiPolling(true);
Irfan Sherifffae66c32010-08-16 11:36:41 -07001667 /* DHCP or other temporary failures in the past can prevent
1668 * a disabled network from being connected to, enable on screen on
1669 */
1670 if (mWifiStateTracker.isAnyNetworkDisabled()) {
1671 sendEnableNetworksMessage();
1672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001676 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /*
1678 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1679 * AND the "stay on while plugged in" setting doesn't match the
1680 * current power conditions (i.e, not plugged in, plugged in to USB,
1681 * or plugged in to AC).
1682 */
1683 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001684 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1685 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001686 // we used to go to sleep immediately, but this caused some race conditions
1687 // we don't have time to track down for this release. Delay instead, but not
1688 // as long as we would if connected (below)
1689 // TODO - fix the race conditions and switch back to the immediate turn-off
1690 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001691 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001692 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1693 // // do not keep Wifi awake when screen is off if Wifi is not associated
1694 // mDeviceIdle = true;
1695 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001696 } else {
1697 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001698 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001699 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 /* we can return now -- there's nothing to do until we get the idle intent back */
1703 return;
1704 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 mDeviceIdle = true;
1707 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1708 /*
1709 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1710 * AND we are transitioning from a state in which the device was supposed
1711 * to stay awake to a state in which it is not supposed to stay awake.
1712 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1713 * the already-set timer.
1714 */
1715 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001716 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1718 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1719 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001720 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1722 mPluggedType = pluggedType;
1723 return;
1724 }
1725 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001726 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001727 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1728 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1729 boolean isBluetoothPlaying = false;
1730 for (BluetoothDevice sink : sinks) {
1731 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1732 isBluetoothPlaying = true;
1733 }
1734 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001735 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 } else {
1738 return;
1739 }
1740
1741 updateWifiState();
1742 }
1743
1744 /**
1745 * Determines whether the Wi-Fi chipset should stay awake or be put to
1746 * sleep. Looks at the setting for the sleep policy and the current
1747 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001748 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 * @see #shouldDeviceStayAwake(int, int)
1750 */
1751 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1752 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1753 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1754
1755 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1756 // Never sleep
1757 return true;
1758 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1759 (pluggedType != 0)) {
1760 // Never sleep while plugged, and we're plugged
1761 return true;
1762 } else {
1763 // Default
1764 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1765 }
1766 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 /**
1769 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1770 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1771 * of {@code 0} isn't really a plugged type, but rather an indication that the
1772 * device isn't plugged in at all, there is no bit value corresponding to a
1773 * {@code pluggedType} value of {@code 0}. That is why we shift by
1774 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1775 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1776 * keep the device (and hence Wi-Fi) awake.
1777 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1778 * being made
1779 * @return {@code true} if {@code pluggedType} indicates that the device is
1780 * supposed to stay awake, {@code false} otherwise.
1781 */
1782 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1783 return (stayAwakeConditions & pluggedType) != 0;
1784 }
1785 };
1786
Dianne Hackborn617f8772009-03-31 15:04:46 -07001787 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 Message msg = Message.obtain(mWifiHandler,
1789 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001790 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 msg.sendToTarget();
1792 }
1793
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001794 private void sendStartMessage(int lockMode) {
1795 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, lockMode, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001798 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1799 Message.obtain(mWifiHandler,
1800 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001801 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001802 }
1803
Irfan Sherifffae66c32010-08-16 11:36:41 -07001804 private void sendEnableNetworksMessage() {
1805 Message.obtain(mWifiHandler, MESSAGE_ENABLE_NETWORKS).sendToTarget();
1806 }
1807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001809 // send a message so it's all serialized
1810 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1811 }
1812
1813 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001815 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001817 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1819 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001820
1821 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001823 }
1824 /* If device is not idle, lockmode cannot be scan only */
1825 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1827 }
1828
1829 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001830 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 return;
1832 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001833
1834 /* Disable tethering when airplane mode is enabled */
1835 if (airplaneMode &&
1836 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1837 sWakeLock.acquire();
1838 sendAccessPointMessage(false, null, mLastApEnableUid);
1839 }
1840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 if (wifiShouldBeEnabled) {
1842 if (wifiShouldBeStarted) {
1843 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001844 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 sWakeLock.acquire();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001846 sendStartMessage(strongestLockMode);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001847 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 int wakeLockTimeout =
1849 Settings.Secure.getInt(
1850 mContext.getContentResolver(),
1851 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1852 DEFAULT_WAKELOCK_TIMEOUT);
1853 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001854 * We are assuming that ConnectivityService can make
1855 * a transition to cellular data within wakeLockTimeout time.
1856 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 */
1858 sDriverStopWakeLock.acquire();
1859 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1860 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1861 }
1862 } else {
1863 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001864 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866 }
1867 }
1868
1869 private void registerForBroadcasts() {
1870 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1872 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1873 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1874 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001875 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 mContext.registerReceiver(mReceiver, intentFilter);
1877 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 private boolean isAirplaneSensitive() {
1880 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1881 Settings.System.AIRPLANE_MODE_RADIOS);
1882 return airplaneModeRadios == null
1883 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1884 }
1885
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001886 private boolean isAirplaneToggleable() {
1887 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1888 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1889 return toggleableRadios != null
1890 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1891 }
1892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 /**
1894 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1895 * currently on.
1896 * @return {@code true} if airplane mode is on.
1897 */
1898 private boolean isAirplaneModeOn() {
1899 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1900 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1901 }
1902
1903 /**
1904 * Handler that allows posting to the WifiThread.
1905 */
1906 private class WifiHandler extends Handler {
1907 public WifiHandler(Looper looper) {
1908 super(looper);
1909 }
1910
1911 @Override
1912 public void handleMessage(Message msg) {
1913 switch (msg.what) {
1914
1915 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001916 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001917 if (mWifiWatchdogService == null) {
1918 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 sWakeLock.release();
1921 break;
1922
1923 case MESSAGE_START_WIFI:
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001924 mWifiStateTracker.setScanOnlyMode(msg.arg1 == WifiManager.WIFI_MODE_SCAN_ONLY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 mWifiStateTracker.restart();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001926 mWifiStateTracker.setHighPerfMode(msg.arg1 ==
1927 WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 sWakeLock.release();
1929 break;
1930
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001931 case MESSAGE_UPDATE_STATE:
1932 doUpdateWifiState();
1933 break;
1934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 case MESSAGE_DISABLE_WIFI:
1936 // a non-zero msg.arg1 value means the "enabled" setting
1937 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001938 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001939 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 sWakeLock.release();
1941 break;
1942
1943 case MESSAGE_STOP_WIFI:
1944 mWifiStateTracker.disconnectAndStop();
1945 // don't release wakelock
1946 break;
1947
1948 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001949 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001951
1952 case MESSAGE_START_ACCESS_POINT:
1953 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001954 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001955 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001956 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001957 break;
1958
1959 case MESSAGE_STOP_ACCESS_POINT:
1960 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001961 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001962 (WifiConfiguration) msg.obj);
1963 sWakeLock.release();
1964 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001965
1966 case MESSAGE_SET_CHANNELS:
1967 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1968 break;
1969
Irfan Sherifffae66c32010-08-16 11:36:41 -07001970 case MESSAGE_ENABLE_NETWORKS:
1971 mWifiStateTracker.enableAllNetworks(getConfiguredNetworks());
1972 break;
1973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975 }
1976 }
1977
1978 @Override
1979 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1980 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1981 != PackageManager.PERMISSION_GRANTED) {
1982 pw.println("Permission Denial: can't dump WifiService from from pid="
1983 + Binder.getCallingPid()
1984 + ", uid=" + Binder.getCallingUid());
1985 return;
1986 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001987 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 pw.println("Stay-awake conditions: " +
1989 Settings.System.getInt(mContext.getContentResolver(),
1990 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1991 pw.println();
1992
1993 pw.println("Internal state:");
1994 pw.println(mWifiStateTracker);
1995 pw.println();
1996 pw.println("Latest scan results:");
1997 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1998 if (scanResults != null && scanResults.size() != 0) {
1999 pw.println(" BSSID Frequency RSSI Flags SSID");
2000 for (ScanResult r : scanResults) {
2001 pw.printf(" %17s %9d %5d %-16s %s%n",
2002 r.BSSID,
2003 r.frequency,
2004 r.level,
2005 r.capabilities,
2006 r.SSID == null ? "" : r.SSID);
2007 }
2008 }
2009 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002010 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002011 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002012 mScanLocksAcquired + " scan");
2013 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002014 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002015 mScanLocksReleased + " scan");
2016 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 pw.println("Locks held:");
2018 mLocks.dump(pw);
2019 }
2020
2021 private static String stateName(int wifiState) {
2022 switch (wifiState) {
2023 case WIFI_STATE_DISABLING:
2024 return "disabling";
2025 case WIFI_STATE_DISABLED:
2026 return "disabled";
2027 case WIFI_STATE_ENABLING:
2028 return "enabling";
2029 case WIFI_STATE_ENABLED:
2030 return "enabled";
2031 case WIFI_STATE_UNKNOWN:
2032 return "unknown state";
2033 default:
2034 return "[invalid state]";
2035 }
2036 }
2037
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002038 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002040 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042
2043 public void binderDied() {
2044 synchronized (mLocks) {
2045 releaseWifiLockLocked(mBinder);
2046 }
2047 }
2048
2049 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002050 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 }
2053
2054 private class LockList {
2055 private List<WifiLock> mList;
2056
2057 private LockList() {
2058 mList = new ArrayList<WifiLock>();
2059 }
2060
2061 private synchronized boolean hasLocks() {
2062 return !mList.isEmpty();
2063 }
2064
2065 private synchronized int getStrongestLockMode() {
2066 if (mList.isEmpty()) {
2067 return WifiManager.WIFI_MODE_FULL;
2068 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002069
2070 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
2071 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002073
2074 if (mFullLocksAcquired > mFullLocksReleased) {
2075 return WifiManager.WIFI_MODE_FULL;
2076 }
2077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 return WifiManager.WIFI_MODE_SCAN_ONLY;
2079 }
2080
2081 private void addLock(WifiLock lock) {
2082 if (findLockByBinder(lock.mBinder) < 0) {
2083 mList.add(lock);
2084 }
2085 }
2086
2087 private WifiLock removeLock(IBinder binder) {
2088 int index = findLockByBinder(binder);
2089 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002090 WifiLock ret = mList.remove(index);
2091 ret.unlinkDeathRecipient();
2092 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 } else {
2094 return null;
2095 }
2096 }
2097
2098 private int findLockByBinder(IBinder binder) {
2099 int size = mList.size();
2100 for (int i = size - 1; i >= 0; i--)
2101 if (mList.get(i).mBinder == binder)
2102 return i;
2103 return -1;
2104 }
2105
2106 private void dump(PrintWriter pw) {
2107 for (WifiLock l : mList) {
2108 pw.print(" ");
2109 pw.println(l);
2110 }
2111 }
2112 }
2113
2114 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002116 if (lockMode != WifiManager.WIFI_MODE_FULL &&
2117 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
2118 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
2119 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
2120 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 return false;
2122 }
2123 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2124 synchronized (mLocks) {
2125 return acquireWifiLockLocked(wifiLock);
2126 }
2127 }
2128
2129 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002130 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002133
The Android Open Source Project10592532009-03-18 17:39:46 -07002134 int uid = Binder.getCallingUid();
2135 long ident = Binder.clearCallingIdentity();
2136 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002137 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002138 case WifiManager.WIFI_MODE_FULL:
2139 ++mFullLocksAcquired;
2140 mBatteryStats.noteFullWifiLockAcquired(uid);
2141 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002142 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2143 ++mFullHighPerfLocksAcquired;
2144 /* Treat high power as a full lock for battery stats */
2145 mBatteryStats.noteFullWifiLockAcquired(uid);
2146 break;
2147
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002148 case WifiManager.WIFI_MODE_SCAN_ONLY:
2149 ++mScanLocksAcquired;
2150 mBatteryStats.noteScanWifiLockAcquired(uid);
2151 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002152 }
2153 } catch (RemoteException e) {
2154 } finally {
2155 Binder.restoreCallingIdentity(ident);
2156 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 updateWifiState();
2159 return true;
2160 }
2161
2162 public boolean releaseWifiLock(IBinder lock) {
2163 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2164 synchronized (mLocks) {
2165 return releaseWifiLockLocked(lock);
2166 }
2167 }
2168
2169 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002170 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002171
The Android Open Source Project10592532009-03-18 17:39:46 -07002172 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002173
Joe Onorato8a9b2202010-02-26 18:56:32 -08002174 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002175
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002176 hadLock = (wifiLock != null);
2177
2178 if (hadLock) {
2179 int uid = Binder.getCallingUid();
2180 long ident = Binder.clearCallingIdentity();
2181 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002182 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002183 case WifiManager.WIFI_MODE_FULL:
2184 ++mFullLocksReleased;
2185 mBatteryStats.noteFullWifiLockReleased(uid);
2186 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002187 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2188 ++mFullHighPerfLocksReleased;
2189 mBatteryStats.noteFullWifiLockReleased(uid);
2190 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002191 case WifiManager.WIFI_MODE_SCAN_ONLY:
2192 ++mScanLocksReleased;
2193 mBatteryStats.noteScanWifiLockReleased(uid);
2194 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002195 }
2196 } catch (RemoteException e) {
2197 } finally {
2198 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002199 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002200 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002201 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002203 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002205
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002206 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002207 implements IBinder.DeathRecipient {
2208 String mTag;
2209 int mMode;
2210 IBinder mBinder;
2211
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002212 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002213 super();
2214 mTag = tag;
2215 mMode = mode;
2216 mBinder = binder;
2217 try {
2218 mBinder.linkToDeath(this, 0);
2219 } catch (RemoteException e) {
2220 binderDied();
2221 }
2222 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002223
2224 void unlinkDeathRecipient() {
2225 mBinder.unlinkToDeath(this, 0);
2226 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002227 }
2228
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002229 private class Multicaster extends DeathRecipient {
2230 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002231 super(Binder.getCallingUid(), tag, binder);
2232 }
2233
2234 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002235 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002236 synchronized (mMulticasters) {
2237 int i = mMulticasters.indexOf(this);
2238 if (i != -1) {
2239 removeMulticasterLocked(i, mMode);
2240 }
2241 }
2242 }
2243
2244 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002245 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002246 }
2247
2248 public int getUid() {
2249 return mMode;
2250 }
2251 }
2252
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002253 public void initializeMulticastFiltering() {
2254 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002255
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002256 synchronized (mMulticasters) {
2257 // if anybody had requested filters be off, leave off
2258 if (mMulticasters.size() != 0) {
2259 return;
2260 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002261 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002262 }
2263 }
2264 }
2265
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002266 public void acquireMulticastLock(IBinder binder, String tag) {
2267 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002268
2269 synchronized (mMulticasters) {
2270 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002271 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002272 // Note that we could call stopPacketFiltering only when
2273 // our new size == 1 (first call), but this function won't
2274 // be called often and by making the stopPacket call each
2275 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002276 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002277 }
2278
2279 int uid = Binder.getCallingUid();
2280 Long ident = Binder.clearCallingIdentity();
2281 try {
2282 mBatteryStats.noteWifiMulticastEnabled(uid);
2283 } catch (RemoteException e) {
2284 } finally {
2285 Binder.restoreCallingIdentity(ident);
2286 }
2287 }
2288
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002289 public void releaseMulticastLock() {
2290 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002291
2292 int uid = Binder.getCallingUid();
2293 synchronized (mMulticasters) {
2294 mMulticastDisabled++;
2295 int size = mMulticasters.size();
2296 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002297 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002298 if ((m != null) && (m.getUid() == uid)) {
2299 removeMulticasterLocked(i, uid);
2300 }
2301 }
2302 }
2303 }
2304
2305 private void removeMulticasterLocked(int i, int uid)
2306 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002307 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002308
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002309 if (removed != null) {
2310 removed.unlinkDeathRecipient();
2311 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002312 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002313 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002314 }
2315
2316 Long ident = Binder.clearCallingIdentity();
2317 try {
2318 mBatteryStats.noteWifiMulticastDisabled(uid);
2319 } catch (RemoteException e) {
2320 } finally {
2321 Binder.restoreCallingIdentity(ident);
2322 }
2323 }
2324
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002325 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002326 enforceAccessPermission();
2327
2328 synchronized (mMulticasters) {
2329 return (mMulticasters.size() > 0);
2330 }
2331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332}