blob: 5aa01119ac71d08a6ab624f5a54901510393da98 [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;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070066import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080068import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.text.TextUtils;
70
71import java.util.ArrayList;
72import java.util.BitSet;
73import java.util.HashMap;
74import java.util.LinkedHashMap;
75import java.util.List;
76import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080077import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.util.regex.Pattern;
79import java.io.FileDescriptor;
80import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080081import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
The Android Open Source Project10592532009-03-18 17:39:46 -070083import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080084import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070085import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080086import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088/**
89 * WifiService handles remote WiFi operation requests by implementing
90 * the IWifiManager interface. It also creates a WifiMonitor to listen
91 * for Wifi-related events.
92 *
93 * @hide
94 */
95public class WifiService extends IWifiManager.Stub {
96 private static final String TAG = "WifiService";
97 private static final boolean DBG = false;
98 private static final Pattern scanResultPattern = Pattern.compile("\t+");
99 private final WifiStateTracker mWifiStateTracker;
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700100 /* TODO: fetch a configurable interface */
101 private static final String SOFTAP_IFACE = "wl0.1";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103 private Context mContext;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800104 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
106 private AlarmManager mAlarmManager;
107 private PendingIntent mIdleIntent;
108 private static final int IDLE_REQUEST = 0;
109 private boolean mScreenOff;
110 private boolean mDeviceIdle;
111 private int mPluggedType;
112
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800113 private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
114
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700115 // true if the user enabled Wifi while in airplane mode
116 private boolean mAirplaneModeOverwridden;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700119 // some wifi lock statistics
Irfan Sheriff8c11e952010-08-12 20:26:23 -0700120 private int mFullHighPerfLocksAcquired;
121 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700122 private int mFullLocksAcquired;
123 private int mFullLocksReleased;
124 private int mScanLocksAcquired;
125 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700126
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700127 private final List<Multicaster> mMulticasters =
128 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700129 private int mMulticastEnabled;
130 private int mMulticastDisabled;
131
The Android Open Source Project10592532009-03-18 17:39:46 -0700132 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800133
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800134 private INetworkManagementService nwService;
135 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800136 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800137 private String[] mWifiRegexs;
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800140 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
141 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 * the approximate point at which the battery drain caused by Wi-Fi
143 * being enabled but not active exceeds the battery drain caused by
144 * re-establishing a connection to the mobile data network.
145 */
146 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
147
Dianne Hackbornc8314b02010-09-20 11:34:11 -0700148 private static final String WAKELOCK_TAG = "*wifi*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 /**
151 * The maximum amount of time to hold the wake lock after a disconnect
152 * caused by stopping the driver. Establishing an EDGE connection has been
153 * observed to take about 5 seconds under normal circumstances. This
154 * provides a bit of extra margin.
155 * <p>
156 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
157 * This is the default value if a Settings.Secure value is not present.
158 */
159 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
160
161 // Wake lock used by driver-stop operation
162 private static PowerManager.WakeLock sDriverStopWakeLock;
163 // Wake lock used by other operations
164 private static PowerManager.WakeLock sWakeLock;
165
Irfan Sheriff59610c02010-03-30 11:00:41 -0700166 private static final int MESSAGE_ENABLE_WIFI = 0;
167 private static final int MESSAGE_DISABLE_WIFI = 1;
168 private static final int MESSAGE_STOP_WIFI = 2;
169 private static final int MESSAGE_START_WIFI = 3;
170 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
171 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800172 private static final int MESSAGE_START_ACCESS_POINT = 6;
173 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700174 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sherifffae66c32010-08-16 11:36:41 -0700175 private static final int MESSAGE_ENABLE_NETWORKS = 9;
Irfan Sheriff0859b762010-09-06 15:34:50 -0700176 private static final int MESSAGE_START_SCAN = 10;
Irfan Sherifff92b4532010-11-03 11:13:10 -0700177 private static final int MESSAGE_REPORT_WORKSOURCE = 11;
178 private static final int MESSAGE_ENABLE_RSSI_POLLING = 12;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
181 private final WifiHandler mWifiHandler;
182
183 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 * Cache of scan results objects (size is somewhat arbitrary)
185 */
186 private static final int SCAN_RESULT_CACHE_SIZE = 80;
187 private final LinkedHashMap<String, ScanResult> mScanResultCache;
188
189 /*
190 * Character buffer used to parse scan results (optimization)
191 */
192 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private boolean mNeedReconfig;
194
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700195 /**
196 * Temporary for computing UIDS that are responsible for starting WIFI.
197 * Protected by mWifiStateTracker lock.
198 */
199 private final WorkSource mTmpWorkSource = new WorkSource();
200
Dianne Hackborn617f8772009-03-31 15:04:46 -0700201 /*
202 * Last UID that asked to enable WIFI.
203 */
204 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800205
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700206 /*
207 * Last UID that asked to enable WIFI AP.
208 */
209 private int mLastApEnableUid = Process.myUid();
210
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 /**
213 * Number of allowed radio frequency channels in various regulatory domains.
214 * This list is sufficient for 802.11b/g networks (2.4GHz range).
215 */
216 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
217
218 private static final String ACTION_DEVICE_IDLE =
219 "com.android.server.WifiManager.action.DEVICE_IDLE";
220
221 WifiService(Context context, WifiStateTracker tracker) {
222 mContext = context;
223 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400224 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700225 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800226
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800227 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
228 nwService = INetworkManagementService.Stub.asInterface(b);
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 mScanResultCache = new LinkedHashMap<String, ScanResult>(
231 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
232 /*
233 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
234 * elements
235 */
236 public boolean removeEldestEntry(Map.Entry eldest) {
237 return SCAN_RESULT_CACHE_SIZE < this.size();
238 }
239 };
240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 HandlerThread wifiThread = new HandlerThread("WifiService");
242 wifiThread.start();
243 mWifiHandler = new WifiHandler(wifiThread.getLooper());
244
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800245 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800246 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
249 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
250 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
251
252 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
253 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
254 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 mContext.registerReceiver(
257 new BroadcastReceiver() {
258 @Override
259 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700260 // clear our flag indicating the user has overwridden airplane mode
261 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700262 // on airplane disable, restore Wifi if the saved state indicates so
263 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
264 persistWifiEnabled(true);
265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 updateWifiState();
267 }
268 },
269 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
270
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800271 mContext.registerReceiver(
272 new BroadcastReceiver() {
273 @Override
274 public void onReceive(Context context, Intent intent) {
275
276 ArrayList<String> available = intent.getStringArrayListExtra(
277 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
278 ArrayList<String> active = intent.getStringArrayListExtra(
279 ConnectivityManager.EXTRA_ACTIVE_TETHER);
280 updateTetherState(available, active);
281
282 }
283 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800284 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800285
Irfan Sheriff7b009782010-03-11 16:37:45 -0800286 /**
287 * Check if Wi-Fi needs to be enabled and start
288 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700289 *
290 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800291 */
292 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700293 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700294 boolean wifiEnabled = !isAirplaneModeOn()
295 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800296 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
297 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700298 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800299 }
300
301 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
302
303 boolean wifiTethered = false;
304 boolean wifiAvailable = false;
305
306 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
307 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
308
309 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
310 mWifiRegexs = mCm.getTetherableWifiRegexs();
311
312 for (String intf : available) {
313 for (String regex : mWifiRegexs) {
314 if (intf.matches(regex)) {
315
316 InterfaceConfiguration ifcg = null;
317 try {
318 ifcg = service.getInterfaceConfig(intf);
319 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700320 /* IP/netmask: 192.168.43.1/255.255.255.0 */
321 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800322 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
323 ifcg.interfaceFlags = "up";
324
325 service.setInterfaceConfig(intf, ifcg);
326 }
327 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800328 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700329 try {
330 nwService.stopAccessPoint();
331 } catch (Exception ee) {
332 Slog.e(TAG, "Could not stop AP, :" + ee);
333 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800334 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800335 return;
336 }
337
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800338 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800339 Slog.e(TAG, "Error tethering "+intf);
340 }
341 break;
342 }
343 }
344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700347 private boolean testAndClearWifiSavedState() {
348 final ContentResolver cr = mContext.getContentResolver();
349 int wifiSavedState = 0;
350 try {
351 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
352 if(wifiSavedState == 1)
353 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
354 } catch (Settings.SettingNotFoundException e) {
355 ;
356 }
357 return (wifiSavedState == 1);
358 }
359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 private boolean getPersistedWifiEnabled() {
361 final ContentResolver cr = mContext.getContentResolver();
362 try {
363 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
364 } catch (Settings.SettingNotFoundException e) {
365 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
366 return false;
367 }
368 }
369
370 private void persistWifiEnabled(boolean enabled) {
371 final ContentResolver cr = mContext.getContentResolver();
372 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
373 }
374
375 NetworkStateTracker getNetworkStateTracker() {
376 return mWifiStateTracker;
377 }
378
379 /**
380 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
381 * @return {@code true} if the operation succeeds
382 */
383 public boolean pingSupplicant() {
384 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800385
386 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
388
389 /**
390 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 */
Irfan Sheriff0859b762010-09-06 15:34:50 -0700392 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 enforceChangePermission();
Irfan Sheriff0859b762010-09-06 15:34:50 -0700394 if (mWifiHandler == null) return;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800395
Irfan Sheriff0859b762010-09-06 15:34:50 -0700396 Message.obtain(mWifiHandler, MESSAGE_START_SCAN, forceActive ? 1 : 0, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 }
398
399 /**
400 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
401 * @param enable {@code true} to enable, {@code false} to disable.
402 * @return {@code true} if the enable/disable operation was
403 * started or is already in the queue.
404 */
405 public boolean setWifiEnabled(boolean enable) {
406 enforceChangePermission();
407 if (mWifiHandler == null) return false;
408
409 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700410 // caller may not have WAKE_LOCK permission - it's not required here
411 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700413 Binder.restoreCallingIdentity(ident);
414
Dianne Hackborn617f8772009-03-31 15:04:46 -0700415 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700416 // set a flag if the user is enabling Wifi while in airplane mode
417 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700418 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420
421 return true;
422 }
423
424 /**
425 * Enables/disables Wi-Fi synchronously.
426 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
427 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700428 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 * @return {@code true} if the operation succeeds (or if the existing state
430 * is the same as the requested state)
431 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700432 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800434 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800436 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 return true;
438 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700439 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 return false;
441 }
442
Irfan Sheriffcd770372010-01-08 09:36:04 -0800443 /**
444 * Multiple calls to unregisterReceiver() cause exception and a system crash.
445 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
446 * disable wifi at the same time.
447 * Avoid doing a disable when the current Wifi state is UNKNOWN
448 * TODO: Handle driver load fail and supplicant lost as seperate states
449 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800450 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800451 return false;
452 }
453
Irfan Sherifff91444c2010-03-24 12:11:00 -0700454 /**
455 * Fail Wifi if AP is enabled
456 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
457 * WIFI_STATE_FAILED
458 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800459 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700460 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
461 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800462 }
463
Irfan Sherifff91444c2010-03-24 12:11:00 -0700464 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800467 if (!mWifiStateTracker.loadDriver()) {
468 Slog.e(TAG, "Failed to load Wi-Fi driver.");
469 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
470 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800472 if (!mWifiStateTracker.startSupplicant()) {
473 mWifiStateTracker.unloadDriver();
474 Slog.e(TAG, "Failed to start supplicant daemon.");
475 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
476 return false;
477 }
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 registerForBroadcasts();
480 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 } else {
483
484 mContext.unregisterReceiver(mReceiver);
485 // Remove notification (it will no-op if it isn't visible)
486 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
487
488 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800489
490 if (!mWifiStateTracker.stopSupplicant()) {
491 Slog.e(TAG, "Failed to stop supplicant daemon.");
492 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
493 failedToStopSupplicantOrUnloadDriver = true;
494 }
495
496 /**
497 * Reset connections and disable interface
498 * before we unload the driver
499 */
500 mWifiStateTracker.resetConnections(true);
501
502 if (!mWifiStateTracker.unloadDriver()) {
503 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
504 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700505 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 failedToStopSupplicantOrUnloadDriver = true;
507 }
508 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 if (failedToStopSupplicantOrUnloadDriver) {
511 return false;
512 }
513 }
514
515 // Success!
516
517 if (persist) {
518 persistWifiEnabled(enable);
519 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700520 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 return true;
522 }
523
Dianne Hackborn617f8772009-03-31 15:04:46 -0700524 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800525 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
The Android Open Source Project10592532009-03-18 17:39:46 -0700527 long ident = Binder.clearCallingIdentity();
528 try {
529 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700530 mBatteryStats.noteWifiOn();
The Android Open Source Project10592532009-03-18 17:39:46 -0700531 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700532 mBatteryStats.noteWifiOff();
The Android Open Source Project10592532009-03-18 17:39:46 -0700533 }
534 } catch (RemoteException e) {
535 } finally {
536 Binder.restoreCallingIdentity(ident);
537 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800540 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541
542 // Broadcast
543 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
544 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
545 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
546 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
547 mContext.sendStickyBroadcast(intent);
548 }
549
550 private void enforceAccessPermission() {
551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
552 "WifiService");
553 }
554
555 private void enforceChangePermission() {
556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
557 "WifiService");
558
559 }
560
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700561 private void enforceMulticastChangePermission() {
562 mContext.enforceCallingOrSelfPermission(
563 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
564 "WifiService");
565 }
566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 /**
568 * see {@link WifiManager#getWifiState()}
569 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
570 * {@link WifiManager#WIFI_STATE_DISABLING},
571 * {@link WifiManager#WIFI_STATE_ENABLED},
572 * {@link WifiManager#WIFI_STATE_ENABLING},
573 * {@link WifiManager#WIFI_STATE_UNKNOWN}
574 */
575 public int getWifiEnabledState() {
576 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800577 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579
580 /**
581 * see {@link android.net.wifi.WifiManager#disconnect()}
582 * @return {@code true} if the operation succeeds
583 */
584 public boolean disconnect() {
585 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800586
587 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
589
590 /**
591 * see {@link android.net.wifi.WifiManager#reconnect()}
592 * @return {@code true} if the operation succeeds
593 */
594 public boolean reconnect() {
595 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800596
597 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599
600 /**
601 * see {@link android.net.wifi.WifiManager#reassociate()}
602 * @return {@code true} if the operation succeeds
603 */
604 public boolean reassociate() {
605 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800606
607 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
609
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800610 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700611 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800612 * @param wifiConfig SSID, security and channel details as
613 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700614 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800615 * @return {@code true} if the start operation was
616 * started or is already in the queue.
617 */
618 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
619 enforceChangePermission();
620 if (mWifiHandler == null) return false;
621
622 synchronized (mWifiHandler) {
623
624 long ident = Binder.clearCallingIdentity();
625 sWakeLock.acquire();
626 Binder.restoreCallingIdentity(ident);
627
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700628 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800629 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
630 }
631
632 return true;
633 }
634
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800635 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700636 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800637 final ContentResolver cr = mContext.getContentResolver();
638 WifiConfiguration wifiConfig = new WifiConfiguration();
639 int authType;
640 try {
641 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
642 if (wifiConfig.SSID == null)
643 return null;
644 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
645 wifiConfig.allowedKeyManagement.set(authType);
646 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
647 return wifiConfig;
648 } catch (Settings.SettingNotFoundException e) {
649 Slog.e(TAG,"AP settings not found, returning");
650 return null;
651 }
652 }
653
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700654 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
655 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800656 final ContentResolver cr = mContext.getContentResolver();
657 boolean isWpa;
658 if (wifiConfig == null)
659 return;
660 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
661 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
662 Settings.Secure.putInt(cr,
663 Settings.Secure.WIFI_AP_SECURITY,
664 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
665 if (isWpa)
666 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
667 }
668
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800669 /**
670 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
671 * and soft access point configured as a single operation.
672 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800673 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800674 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800675 * @return {@code true} if the operation succeeds (or if the existing state
676 * is the same as the requested state)
677 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800678 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800679 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800680 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
681
682 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800683 /* Configuration changed on a running access point */
684 if(enable && (wifiConfig != null)) {
685 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700686 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
687 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700688 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800689 return true;
690 } catch(Exception e) {
691 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700692 try {
693 nwService.stopAccessPoint();
694 } catch (Exception ee) {
695 Slog.e(TAG, "Could not stop AP, :" + ee);
696 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800697 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
698 return false;
699 }
700 } else {
701 return true;
702 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800703 }
704
Irfan Sherifff91444c2010-03-24 12:11:00 -0700705 /**
706 * Fail AP if Wifi is enabled
707 */
708 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
709 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
710 return false;
711 }
712
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800713 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
714 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800715
716 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800717
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800718 /* Use default config if there is no existing config */
719 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
720 wifiConfig = new WifiConfiguration();
721 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
722 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
723 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800724
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800725 if (!mWifiStateTracker.loadDriver()) {
726 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800727 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800728 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800729 }
730
731 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700732 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
733 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800734 } catch(Exception e) {
735 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800736 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
737 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800738 }
739
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700740 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700741
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 } else {
743
744 try {
745 nwService.stopAccessPoint();
746 } catch(Exception e) {
747 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800748 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
749 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800750 }
751
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800752 if (!mWifiStateTracker.unloadDriver()) {
753 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800754 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800755 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800756 }
757 }
758
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800759 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800760 return true;
761 }
762
763 /**
764 * see {@link WifiManager#getWifiApState()}
765 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
766 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
767 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
768 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
769 * {@link WifiManager#WIFI_AP_STATE_FAILED}
770 */
771 public int getWifiApEnabledState() {
772 enforceAccessPermission();
773 return mWifiApState;
774 }
775
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800776 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800777 final int previousWifiApState = mWifiApState;
778
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800779 /**
780 * Unload the driver if going to a failed state
781 */
782 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
783 mWifiStateTracker.unloadDriver();
784 }
785
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800786 long ident = Binder.clearCallingIdentity();
787 try {
788 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700789 mBatteryStats.noteWifiOn();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800790 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700791 mBatteryStats.noteWifiOff();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800792 }
793 } catch (RemoteException e) {
794 } finally {
795 Binder.restoreCallingIdentity(ident);
796 }
797
798 // Update state
799 mWifiApState = wifiAPState;
800
801 // Broadcast
802 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
803 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
804 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
805 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
806 mContext.sendStickyBroadcast(intent);
807 }
808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 /**
810 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
811 * @return the list of configured networks
812 */
813 public List<WifiConfiguration> getConfiguredNetworks() {
814 enforceAccessPermission();
815 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /*
818 * We don't cache the list, because we want to allow
819 * for the possibility that the configuration file
820 * has been modified through some external means,
821 * such as the wpa_cli command line program.
822 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800823 listStr = mWifiStateTracker.listNetworks();
824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 List<WifiConfiguration> networks =
826 new ArrayList<WifiConfiguration>();
827 if (listStr == null)
828 return networks;
829
830 String[] lines = listStr.split("\n");
831 // Skip the first line, which is a header
832 for (int i = 1; i < lines.length; i++) {
833 String[] result = lines[i].split("\t");
834 // network-id | ssid | bssid | flags
835 WifiConfiguration config = new WifiConfiguration();
836 try {
837 config.networkId = Integer.parseInt(result[0]);
838 } catch(NumberFormatException e) {
839 continue;
840 }
841 if (result.length > 3) {
842 if (result[3].indexOf("[CURRENT]") != -1)
843 config.status = WifiConfiguration.Status.CURRENT;
844 else if (result[3].indexOf("[DISABLED]") != -1)
845 config.status = WifiConfiguration.Status.DISABLED;
846 else
847 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800848 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800851 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 networks.add(config);
853 }
854
855 return networks;
856 }
857
858 /**
859 * Read the variables from the supplicant daemon that are needed to
860 * fill in the WifiConfiguration object.
861 * <p/>
862 * The caller must hold the synchronization monitor.
863 * @param config the {@link WifiConfiguration} object to be filled in.
864 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800865 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866
867 int netId = config.networkId;
868 if (netId < 0)
869 return;
870
871 /*
872 * TODO: maybe should have a native method that takes an array of
873 * variable names and returns an array of values. But we'd still
874 * be doing a round trip to the supplicant daemon for each variable.
875 */
876 String value;
877
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800878 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800880 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } else {
882 config.SSID = null;
883 }
884
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800885 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 if (!TextUtils.isEmpty(value)) {
887 config.BSSID = value;
888 } else {
889 config.BSSID = null;
890 }
891
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800892 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 config.priority = -1;
894 if (!TextUtils.isEmpty(value)) {
895 try {
896 config.priority = Integer.parseInt(value);
897 } catch (NumberFormatException ignore) {
898 }
899 }
900
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800901 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 config.hiddenSSID = false;
903 if (!TextUtils.isEmpty(value)) {
904 try {
905 config.hiddenSSID = Integer.parseInt(value) != 0;
906 } catch (NumberFormatException ignore) {
907 }
908 }
909
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800910 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 config.wepTxKeyIndex = -1;
912 if (!TextUtils.isEmpty(value)) {
913 try {
914 config.wepTxKeyIndex = Integer.parseInt(value);
915 } catch (NumberFormatException ignore) {
916 }
917 }
918
919 /*
920 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
921 * just a "*" if the key is set, or the null string otherwise.
922 */
923 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800924 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 if (!TextUtils.isEmpty(value)) {
926 config.wepKeys[i] = value;
927 } else {
928 config.wepKeys[i] = null;
929 }
930 }
931
932 /*
933 * Get the private shared key. Note that the actual keys are not passed back,
934 * just a "*" if the key is set, or the null string otherwise.
935 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800936 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (!TextUtils.isEmpty(value)) {
938 config.preSharedKey = value;
939 } else {
940 config.preSharedKey = null;
941 }
942
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800943 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 WifiConfiguration.Protocol.varName);
945 if (!TextUtils.isEmpty(value)) {
946 String vals[] = value.split(" ");
947 for (String val : vals) {
948 int index =
949 lookupString(val, WifiConfiguration.Protocol.strings);
950 if (0 <= index) {
951 config.allowedProtocols.set(index);
952 }
953 }
954 }
955
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800956 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 WifiConfiguration.KeyMgmt.varName);
958 if (!TextUtils.isEmpty(value)) {
959 String vals[] = value.split(" ");
960 for (String val : vals) {
961 int index =
962 lookupString(val, WifiConfiguration.KeyMgmt.strings);
963 if (0 <= index) {
964 config.allowedKeyManagement.set(index);
965 }
966 }
967 }
968
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800969 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 WifiConfiguration.AuthAlgorithm.varName);
971 if (!TextUtils.isEmpty(value)) {
972 String vals[] = value.split(" ");
973 for (String val : vals) {
974 int index =
975 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
976 if (0 <= index) {
977 config.allowedAuthAlgorithms.set(index);
978 }
979 }
980 }
981
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800982 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 WifiConfiguration.PairwiseCipher.varName);
984 if (!TextUtils.isEmpty(value)) {
985 String vals[] = value.split(" ");
986 for (String val : vals) {
987 int index =
988 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
989 if (0 <= index) {
990 config.allowedPairwiseCiphers.set(index);
991 }
992 }
993 }
994
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800995 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 WifiConfiguration.GroupCipher.varName);
997 if (!TextUtils.isEmpty(value)) {
998 String vals[] = value.split(" ");
999 for (String val : vals) {
1000 int index =
1001 lookupString(val, WifiConfiguration.GroupCipher.strings);
1002 if (0 <= index) {
1003 config.allowedGroupCiphers.set(index);
1004 }
1005 }
1006 }
Chung-yih Wang43374762009-09-16 14:28:42 +08001007
1008 for (WifiConfiguration.EnterpriseField field :
1009 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001010 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +08001011 field.varName());
1012 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001013 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001014 field.setValue(value);
1015 }
1016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001019 private static String removeDoubleQuotes(String string) {
1020 if (string.length() <= 2) return "";
1021 return string.substring(1, string.length() - 1);
1022 }
1023
1024 private static String convertToQuotedString(String string) {
1025 return "\"" + string + "\"";
1026 }
1027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 /**
1029 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1030 * @return the supplicant-assigned identifier for the new or updated
1031 * network if the operation succeeds, or {@code -1} if it fails
1032 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001033 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /*
1037 * If the supplied networkId is -1, we create a new empty
1038 * network configuration. Otherwise, the networkId should
1039 * refer to an existing configuration.
1040 */
1041 int netId = config.networkId;
1042 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001043 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001045 synchronized (mWifiStateTracker) {
1046 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001047 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001048 if (netId < 0) {
1049 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001050 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001051 }
1052 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001054 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001056 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001059 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /*
1061 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001062 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * will fail, so we don't bother to make a separate check
1064 * for the validity of the ID up front.
1065 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001067 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001068 netId,
1069 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001070 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001072 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 break setVariables;
1075 }
1076
1077 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001078 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001079 netId,
1080 WifiConfiguration.bssidVarName,
1081 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001083 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 break setVariables;
1086 }
1087
1088 String allowedKeyManagementString =
1089 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1090 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001091 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001092 netId,
1093 WifiConfiguration.KeyMgmt.varName,
1094 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001096 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001097 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099 break setVariables;
1100 }
1101
1102 String allowedProtocolsString =
1103 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1104 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001105 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001106 netId,
1107 WifiConfiguration.Protocol.varName,
1108 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001110 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001111 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 break setVariables;
1114 }
1115
1116 String allowedAuthAlgorithmsString =
1117 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1118 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001119 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001120 netId,
1121 WifiConfiguration.AuthAlgorithm.varName,
1122 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001124 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001125 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 break setVariables;
1128 }
1129
1130 String allowedPairwiseCiphersString =
1131 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1132 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001133 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001134 netId,
1135 WifiConfiguration.PairwiseCipher.varName,
1136 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001138 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001139 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141 break setVariables;
1142 }
1143
1144 String allowedGroupCiphersString =
1145 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1146 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001147 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001148 netId,
1149 WifiConfiguration.GroupCipher.varName,
1150 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001152 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001153 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 break setVariables;
1156 }
1157
1158 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1159 // by preventing "*" as a key.
1160 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001161 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001162 netId,
1163 WifiConfiguration.pskVarName,
1164 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168 break setVariables;
1169 }
1170
1171 boolean hasSetKey = false;
1172 if (config.wepKeys != null) {
1173 for (int i = 0; i < config.wepKeys.length; i++) {
1174 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1175 // by preventing "*" as a key.
1176 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001177 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001178 netId,
1179 WifiConfiguration.wepKeyVarNames[i],
1180 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001182 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001183 "failed to set wep_key"+i+": " +
1184 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186 break setVariables;
1187 }
1188 hasSetKey = true;
1189 }
1190 }
1191 }
1192
1193 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001194 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001195 netId,
1196 WifiConfiguration.wepTxKeyIdxVarName,
1197 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001199 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001200 "failed to set wep_tx_keyidx: "+
1201 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203 break setVariables;
1204 }
1205 }
1206
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001207 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001208 netId,
1209 WifiConfiguration.priorityVarName,
1210 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001212 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001213 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215 break setVariables;
1216 }
1217
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001218 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001219 netId,
1220 WifiConfiguration.hiddenSSIDVarName,
1221 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001223 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001224 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 break setVariables;
1227 }
1228
Chung-yih Wang43374762009-09-16 14:28:42 +08001229 for (WifiConfiguration.EnterpriseField field
1230 : config.enterpriseFields) {
1231 String varName = field.varName();
1232 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001233 if (value != null) {
1234 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001235 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001236 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001237 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001238 netId,
1239 varName,
1240 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001241 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001242 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001243 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001244 }
1245 break setVariables;
1246 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001247 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001252 /*
1253 * For an update, if one of the setNetworkVariable operations fails,
1254 * we might want to roll back all the changes already made. But the
1255 * chances are that if anything is going to go wrong, it'll happen
1256 * the first time we try to set one of the variables.
1257 */
1258 if (newNetwork) {
1259 removeNetwork(netId);
1260 if (DBG) {
1261 Slog.d(TAG,
1262 "Failed to set a network variable, removed network: "
1263 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265 }
1266 return -1;
1267 }
1268
1269 private static String makeString(BitSet set, String[] strings) {
1270 StringBuffer buf = new StringBuffer();
1271 int nextSetBit = -1;
1272
1273 /* Make sure all set bits are in [0, strings.length) to avoid
1274 * going out of bounds on strings. (Shouldn't happen, but...) */
1275 set = set.get(0, strings.length);
1276
1277 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1278 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1279 }
1280
1281 // remove trailing space
1282 if (set.cardinality() > 0) {
1283 buf.setLength(buf.length() - 1);
1284 }
1285
1286 return buf.toString();
1287 }
1288
1289 private static int lookupString(String string, String[] strings) {
1290 int size = strings.length;
1291
1292 string = string.replace('-', '_');
1293
1294 for (int i = 0; i < size; i++)
1295 if (string.equals(strings[i]))
1296 return i;
1297
1298 if (DBG) {
1299 // if we ever get here, we should probably add the
1300 // value to WifiConfiguration to reflect that it's
1301 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001302 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304
1305 return -1;
1306 }
1307
1308 /**
1309 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1310 * @param netId the integer that identifies the network configuration
1311 * to the supplicant
1312 * @return {@code true} if the operation succeeded
1313 */
1314 public boolean removeNetwork(int netId) {
1315 enforceChangePermission();
1316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 return mWifiStateTracker.removeNetwork(netId);
1318 }
1319
1320 /**
1321 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1322 * @param netId the integer that identifies the network configuration
1323 * to the supplicant
1324 * @param disableOthers if true, disable all other networks.
1325 * @return {@code true} if the operation succeeded
1326 */
1327 public boolean enableNetwork(int netId, boolean disableOthers) {
1328 enforceChangePermission();
1329
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001330 String ifname = mWifiStateTracker.getInterfaceName();
1331 NetworkUtils.enableInterface(ifname);
1332 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1333 if (!result) {
1334 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001336 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
1339 /**
1340 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1341 * @param netId the integer that identifies the network configuration
1342 * to the supplicant
1343 * @return {@code true} if the operation succeeded
1344 */
1345 public boolean disableNetwork(int netId) {
1346 enforceChangePermission();
1347
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001348 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350
1351 /**
1352 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1353 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1354 */
1355 public WifiInfo getConnectionInfo() {
1356 enforceAccessPermission();
1357 /*
1358 * Make sure we have the latest information, by sending
1359 * a status request to the supplicant.
1360 */
1361 return mWifiStateTracker.requestConnectionInfo();
1362 }
1363
1364 /**
1365 * Return the results of the most recent access point scan, in the form of
1366 * a list of {@link ScanResult} objects.
1367 * @return the list of results
1368 */
1369 public List<ScanResult> getScanResults() {
1370 enforceAccessPermission();
1371 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001372
1373 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (reply == null) {
1375 return null;
1376 }
1377
1378 List<ScanResult> scanList = new ArrayList<ScanResult>();
1379
1380 int lineCount = 0;
1381
1382 int replyLen = reply.length();
1383 // Parse the result string, keeping in mind that the last line does
1384 // not end with a newline.
1385 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1386 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1387 ++lineCount;
1388 /*
1389 * Skip the first line, which is a header
1390 */
1391 if (lineCount == 1) {
1392 lineBeg = lineEnd + 1;
1393 continue;
1394 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001395 if (lineEnd > lineBeg) {
1396 String line = reply.substring(lineBeg, lineEnd);
1397 ScanResult scanResult = parseScanResult(line);
1398 if (scanResult != null) {
1399 scanList.add(scanResult);
1400 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403 }
1404 lineBeg = lineEnd + 1;
1405 }
1406 }
1407 mWifiStateTracker.setScanResultsList(scanList);
1408 return scanList;
1409 }
1410
1411 /**
1412 * Parse the scan result line passed to us by wpa_supplicant (helper).
1413 * @param line the line to parse
1414 * @return the {@link ScanResult} object
1415 */
1416 private ScanResult parseScanResult(String line) {
1417 ScanResult scanResult = null;
1418 if (line != null) {
1419 /*
1420 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1421 * must synchronized here!
1422 */
1423 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001424 String[] result = scanResultPattern.split(line);
1425 if (3 <= result.length && result.length <= 5) {
1426 String bssid = result[0];
1427 // bssid | frequency | level | flags | ssid
1428 int frequency;
1429 int level;
1430 try {
1431 frequency = Integer.parseInt(result[1]);
1432 level = Integer.parseInt(result[2]);
1433 /* some implementations avoid negative values by adding 256
1434 * so we need to adjust for that here.
1435 */
1436 if (level > 0) level -= 256;
1437 } catch (NumberFormatException e) {
1438 frequency = 0;
1439 level = 0;
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441
Mike Lockwood1a645052009-06-25 13:01:12 -04001442 /*
1443 * The formatting of the results returned by
1444 * wpa_supplicant is intended to make the fields
1445 * line up nicely when printed,
1446 * not to make them easy to parse. So we have to
1447 * apply some heuristics to figure out which field
1448 * is the SSID and which field is the flags.
1449 */
1450 String ssid;
1451 String flags;
1452 if (result.length == 4) {
1453 if (result[3].charAt(0) == '[') {
1454 flags = result[3];
1455 ssid = "";
1456 } else {
1457 flags = "";
1458 ssid = result[3];
1459 }
1460 } else if (result.length == 5) {
1461 flags = result[3];
1462 ssid = result[4];
1463 } else {
1464 // Here, we must have 3 fields: no flags and ssid
1465 // set
1466 flags = "";
1467 ssid = "";
1468 }
1469
Mike Lockwood00717e22009-08-17 10:09:36 -04001470 // bssid + ssid is the hash key
1471 String key = bssid + ssid;
1472 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001473 if (scanResult != null) {
1474 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001475 scanResult.SSID = ssid;
1476 scanResult.capabilities = flags;
1477 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001478 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 // Do not add scan results that have no SSID set
1480 if (0 < ssid.trim().length()) {
1481 scanResult =
1482 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001483 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001484 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001487 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001489 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491 }
1492 }
1493
1494 return scanResult;
1495 }
1496
1497 /**
1498 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1499 * and construct a {@code WifiConfiguration} that describes the encryption,
1500 * key management, and authenticaion capabilities of the access point.
1501 * @param flags the string returned by wpa_supplicant
1502 * @return the {@link WifiConfiguration} object, filled in
1503 */
1504 WifiConfiguration parseScanFlags(String flags) {
1505 WifiConfiguration config = new WifiConfiguration();
1506
1507 if (flags.length() == 0) {
1508 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1509 }
1510 // ... to be implemented
1511 return config;
1512 }
1513
1514 /**
1515 * Tell the supplicant to persist the current list of configured networks.
1516 * @return {@code true} if the operation succeeded
1517 */
1518 public boolean saveConfiguration() {
1519 boolean result;
1520 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001523 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 if (result && mNeedReconfig) {
1525 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001526 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527
1528 if (result) {
1529 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1530 mContext.sendBroadcast(intent);
1531 }
1532 }
1533 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001534 // Inform the backup manager about a data change
1535 IBackupManager ibm = IBackupManager.Stub.asInterface(
1536 ServiceManager.getService(Context.BACKUP_SERVICE));
1537 if (ibm != null) {
1538 try {
1539 ibm.dataChanged("com.android.providers.settings");
1540 } catch (Exception e) {
1541 // Try again later
1542 }
1543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 return result;
1545 }
1546
1547 /**
1548 * Set the number of radio frequency channels that are allowed to be used
1549 * in the current regulatory domain. This method should be used only
1550 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001551 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 * persisted as a Secure setting.
1553 * @param numChannels the number of allowed channels. Must be greater than 0
1554 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001555 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1557 * {@code numChannels} is outside the valid range.
1558 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001559 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001561 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 /*
1565 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1566 * but if Wi-Fi isn't currently enabled, that's not possible, and
1567 * we want to persist the setting anyway,so that it will take
1568 * effect when Wi-Fi does become enabled.
1569 */
1570 boolean found = false;
1571 for (int validChan : sValidRegulatoryChannelCounts) {
1572 if (validChan == numChannels) {
1573 found = true;
1574 break;
1575 }
1576 }
1577 if (!found) {
1578 return false;
1579 }
1580
Irfan Sheriff59610c02010-03-30 11:00:41 -07001581 if (mWifiHandler == null) return false;
1582
1583 Message.obtain(mWifiHandler,
1584 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1585
1586 return true;
1587 }
1588
1589 /**
1590 * sets the number of allowed radio frequency channels synchronously
1591 * @param numChannels the number of allowed channels. Must be greater than 0
1592 * and less than or equal to 16.
1593 * @param persist {@code true} if the setting should be remembered.
1594 * @return {@code true} if the operation succeeds, {@code false} otherwise
1595 */
1596 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001597 if (persist) {
1598 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001599 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1600 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001601 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001602 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
1605 /**
1606 * Return the number of frequency channels that are allowed
1607 * to be used in the current regulatory domain.
1608 * @return the number of allowed channels, or {@code -1} if an error occurs
1609 */
1610 public int getNumAllowedChannels() {
1611 int numChannels;
1612
1613 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001614
1615 /*
1616 * If we can't get the value from the driver (e.g., because
1617 * Wi-Fi is not currently enabled), get the value from
1618 * Settings.
1619 */
1620 numChannels = mWifiStateTracker.getNumAllowedChannels();
1621 if (numChannels < 0) {
1622 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1623 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1624 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
1626 return numChannels;
1627 }
1628
1629 /**
1630 * Return the list of valid values for the number of allowed radio channels
1631 * for various regulatory domains.
1632 * @return the list of channel counts
1633 */
1634 public int[] getValidChannelCounts() {
1635 enforceAccessPermission();
1636 return sValidRegulatoryChannelCounts;
1637 }
1638
1639 /**
1640 * Return the DHCP-assigned addresses from the last successful DHCP request,
1641 * if any.
1642 * @return the DHCP information
1643 */
1644 public DhcpInfo getDhcpInfo() {
1645 enforceAccessPermission();
1646 return mWifiStateTracker.getDhcpInfo();
1647 }
1648
1649 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1650 @Override
1651 public void onReceive(Context context, Intent intent) {
1652 String action = intent.getAction();
1653
Doug Zongker43866e02010-01-07 12:09:54 -08001654 long idleMillis =
1655 Settings.Secure.getLong(mContext.getContentResolver(),
1656 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001658 Settings.System.getInt(mContext.getContentResolver(),
1659 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001661 if (DBG) {
1662 Slog.d(TAG, "ACTION_SCREEN_ON");
1663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 mAlarmManager.cancel(mIdleIntent);
1665 mDeviceIdle = false;
1666 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001667 // Once the screen is on, we are not keeping WIFI running
1668 // because of any locks so clear that tracking immediately.
Irfan Sherifff92b4532010-11-03 11:13:10 -07001669 sendReportWorkSourceMessage();
1670 sendEnableRssiPollingMessage(true);
Irfan Sherifffae66c32010-08-16 11:36:41 -07001671 /* DHCP or other temporary failures in the past can prevent
1672 * a disabled network from being connected to, enable on screen on
1673 */
1674 if (mWifiStateTracker.isAnyNetworkDisabled()) {
1675 sendEnableNetworksMessage();
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001678 if (DBG) {
1679 Slog.d(TAG, "ACTION_SCREEN_OFF");
1680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 mScreenOff = true;
Irfan Sherifff92b4532010-11-03 11:13:10 -07001682 sendEnableRssiPollingMessage(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /*
1684 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1685 * AND the "stay on while plugged in" setting doesn't match the
1686 * current power conditions (i.e, not plugged in, plugged in to USB,
1687 * or plugged in to AC).
1688 */
1689 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001690 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1691 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001692 // we used to go to sleep immediately, but this caused some race conditions
1693 // we don't have time to track down for this release. Delay instead, but not
1694 // as long as we would if connected (below)
1695 // TODO - fix the race conditions and switch back to the immediate turn-off
1696 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -04001697 if (DBG) {
1698 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
1699 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001700 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1701 // // do not keep Wifi awake when screen is off if Wifi is not associated
1702 // mDeviceIdle = true;
1703 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001704 } else {
1705 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -04001706 if (DBG) {
1707 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
1708 + "ms");
1709 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001710 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 /* we can return now -- there's nothing to do until we get the idle intent back */
1714 return;
1715 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001716 if (DBG) {
1717 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
1718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 mDeviceIdle = true;
Irfan Sherifff92b4532010-11-03 11:13:10 -07001720 sendReportWorkSourceMessage();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1722 /*
1723 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1724 * AND we are transitioning from a state in which the device was supposed
1725 * to stay awake to a state in which it is not supposed to stay awake.
1726 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1727 * the already-set timer.
1728 */
1729 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -04001730 if (DBG) {
1731 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
1732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1734 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1735 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -04001736 if (DBG) {
1737 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1740 mPluggedType = pluggedType;
1741 return;
1742 }
1743 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001744 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001745 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1746 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1747 boolean isBluetoothPlaying = false;
1748 for (BluetoothDevice sink : sinks) {
1749 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1750 isBluetoothPlaying = true;
1751 }
1752 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001753 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 } else {
1756 return;
1757 }
1758
1759 updateWifiState();
1760 }
1761
1762 /**
1763 * Determines whether the Wi-Fi chipset should stay awake or be put to
1764 * sleep. Looks at the setting for the sleep policy and the current
1765 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001766 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 * @see #shouldDeviceStayAwake(int, int)
1768 */
1769 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1770 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1771 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1772
1773 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1774 // Never sleep
1775 return true;
1776 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1777 (pluggedType != 0)) {
1778 // Never sleep while plugged, and we're plugged
1779 return true;
1780 } else {
1781 // Default
1782 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1783 }
1784 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 /**
1787 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1788 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1789 * of {@code 0} isn't really a plugged type, but rather an indication that the
1790 * device isn't plugged in at all, there is no bit value corresponding to a
1791 * {@code pluggedType} value of {@code 0}. That is why we shift by
1792 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1793 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1794 * keep the device (and hence Wi-Fi) awake.
1795 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1796 * being made
1797 * @return {@code true} if {@code pluggedType} indicates that the device is
1798 * supposed to stay awake, {@code false} otherwise.
1799 */
1800 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1801 return (stayAwakeConditions & pluggedType) != 0;
1802 }
1803 };
1804
Dianne Hackborn617f8772009-03-31 15:04:46 -07001805 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 Message msg = Message.obtain(mWifiHandler,
1807 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001808 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 msg.sendToTarget();
1810 }
1811
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001812 private void sendStartMessage(int lockMode) {
1813 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, lockMode, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001816 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1817 Message.obtain(mWifiHandler,
1818 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001819 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001820 }
1821
Irfan Sherifffae66c32010-08-16 11:36:41 -07001822 private void sendEnableNetworksMessage() {
1823 Message.obtain(mWifiHandler, MESSAGE_ENABLE_NETWORKS).sendToTarget();
1824 }
1825
Irfan Sherifff92b4532010-11-03 11:13:10 -07001826 private void sendReportWorkSourceMessage() {
1827 Message.obtain(mWifiHandler, MESSAGE_REPORT_WORKSOURCE).sendToTarget();
1828 }
1829
1830 private void sendEnableRssiPollingMessage(boolean enable) {
1831 Message.obtain(mWifiHandler, MESSAGE_ENABLE_RSSI_POLLING, enable ? 1 : 0, 0).sendToTarget();
1832 }
1833
1834
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001835 private void reportStartWorkSource() {
1836 synchronized (mWifiStateTracker) {
1837 mTmpWorkSource.clear();
1838 if (mDeviceIdle) {
1839 for (int i=0; i<mLocks.mList.size(); i++) {
1840 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
1841 }
1842 }
1843 mWifiStateTracker.updateBatteryWorkSourceLocked(mTmpWorkSource);
Dianne Hackbornc8314b02010-09-20 11:34:11 -07001844 sWakeLock.setWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001845 }
1846 }
1847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001849 // send a message so it's all serialized
1850 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1851 }
1852
1853 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001855 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001856
1857 boolean lockHeld;
1858 synchronized (mLocks) {
1859 lockHeld = mLocks.hasLocks();
1860 }
1861
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001862 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1864 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001865
1866 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001868 }
1869 /* If device is not idle, lockmode cannot be scan only */
1870 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1872 }
1873
1874 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001875 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 return;
1877 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001878
1879 /* Disable tethering when airplane mode is enabled */
1880 if (airplaneMode &&
1881 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1882 sWakeLock.acquire();
1883 sendAccessPointMessage(false, null, mLastApEnableUid);
1884 }
1885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 if (wifiShouldBeEnabled) {
1887 if (wifiShouldBeStarted) {
1888 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001889 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 sWakeLock.acquire();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001891 sendStartMessage(strongestLockMode);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001892 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 int wakeLockTimeout =
1894 Settings.Secure.getInt(
1895 mContext.getContentResolver(),
1896 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1897 DEFAULT_WAKELOCK_TIMEOUT);
1898 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001899 * We are assuming that ConnectivityService can make
1900 * a transition to cellular data within wakeLockTimeout time.
1901 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 */
1903 sDriverStopWakeLock.acquire();
1904 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1905 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1906 }
1907 } else {
1908 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001909 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911 }
1912 }
1913
1914 private void registerForBroadcasts() {
1915 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1917 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1918 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1919 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001920 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 mContext.registerReceiver(mReceiver, intentFilter);
1922 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 private boolean isAirplaneSensitive() {
1925 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1926 Settings.System.AIRPLANE_MODE_RADIOS);
1927 return airplaneModeRadios == null
1928 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1929 }
1930
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001931 private boolean isAirplaneToggleable() {
1932 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1933 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1934 return toggleableRadios != null
1935 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1936 }
1937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 /**
1939 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1940 * currently on.
1941 * @return {@code true} if airplane mode is on.
1942 */
1943 private boolean isAirplaneModeOn() {
1944 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1945 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1946 }
1947
1948 /**
1949 * Handler that allows posting to the WifiThread.
1950 */
1951 private class WifiHandler extends Handler {
1952 public WifiHandler(Looper looper) {
1953 super(looper);
1954 }
1955
1956 @Override
1957 public void handleMessage(Message msg) {
1958 switch (msg.what) {
1959
1960 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001961 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001962 if (mWifiWatchdogService == null) {
1963 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 sWakeLock.release();
1966 break;
1967
1968 case MESSAGE_START_WIFI:
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001969 reportStartWorkSource();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001970 mWifiStateTracker.setScanOnlyMode(msg.arg1 == WifiManager.WIFI_MODE_SCAN_ONLY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 mWifiStateTracker.restart();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001972 mWifiStateTracker.setHighPerfMode(msg.arg1 ==
1973 WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 sWakeLock.release();
1975 break;
1976
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001977 case MESSAGE_UPDATE_STATE:
1978 doUpdateWifiState();
1979 break;
1980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 case MESSAGE_DISABLE_WIFI:
1982 // a non-zero msg.arg1 value means the "enabled" setting
1983 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001984 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001985 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 sWakeLock.release();
1987 break;
1988
1989 case MESSAGE_STOP_WIFI:
1990 mWifiStateTracker.disconnectAndStop();
1991 // don't release wakelock
1992 break;
1993
1994 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001995 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001997
1998 case MESSAGE_START_ACCESS_POINT:
1999 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08002000 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08002001 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07002002 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08002003 break;
2004
2005 case MESSAGE_STOP_ACCESS_POINT:
2006 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08002007 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08002008 (WifiConfiguration) msg.obj);
2009 sWakeLock.release();
2010 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07002011
2012 case MESSAGE_SET_CHANNELS:
2013 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
2014 break;
2015
Irfan Sherifffae66c32010-08-16 11:36:41 -07002016 case MESSAGE_ENABLE_NETWORKS:
2017 mWifiStateTracker.enableAllNetworks(getConfiguredNetworks());
2018 break;
2019
Irfan Sheriff0859b762010-09-06 15:34:50 -07002020 case MESSAGE_START_SCAN:
2021 boolean forceActive = (msg.arg1 == 1);
2022 switch (mWifiStateTracker.getSupplicantState()) {
2023 case DISCONNECTED:
2024 case INACTIVE:
2025 case SCANNING:
2026 case DORMANT:
2027 break;
2028 default:
2029 mWifiStateTracker.setScanResultHandling(
2030 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
2031 break;
2032 }
2033 mWifiStateTracker.scan(forceActive);
2034 break;
Irfan Sherifff92b4532010-11-03 11:13:10 -07002035 case MESSAGE_REPORT_WORKSOURCE:
2036 reportStartWorkSource();
2037 break;
2038 case MESSAGE_ENABLE_RSSI_POLLING:
2039 mWifiStateTracker.enableRssiPolling(msg.arg1 == 1);
2040 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 }
2043 }
2044
2045 @Override
2046 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2047 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2048 != PackageManager.PERMISSION_GRANTED) {
2049 pw.println("Permission Denial: can't dump WifiService from from pid="
2050 + Binder.getCallingPid()
2051 + ", uid=" + Binder.getCallingUid());
2052 return;
2053 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08002054 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 pw.println("Stay-awake conditions: " +
2056 Settings.System.getInt(mContext.getContentResolver(),
2057 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
2058 pw.println();
2059
2060 pw.println("Internal state:");
2061 pw.println(mWifiStateTracker);
2062 pw.println();
2063 pw.println("Latest scan results:");
2064 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
2065 if (scanResults != null && scanResults.size() != 0) {
2066 pw.println(" BSSID Frequency RSSI Flags SSID");
2067 for (ScanResult r : scanResults) {
2068 pw.printf(" %17s %9d %5d %-16s %s%n",
2069 r.BSSID,
2070 r.frequency,
2071 r.level,
2072 r.capabilities,
2073 r.SSID == null ? "" : r.SSID);
2074 }
2075 }
2076 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002077 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002078 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002079 mScanLocksAcquired + " scan");
2080 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002081 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002082 mScanLocksReleased + " scan");
2083 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 pw.println("Locks held:");
2085 mLocks.dump(pw);
2086 }
2087
2088 private static String stateName(int wifiState) {
2089 switch (wifiState) {
2090 case WIFI_STATE_DISABLING:
2091 return "disabling";
2092 case WIFI_STATE_DISABLED:
2093 return "disabled";
2094 case WIFI_STATE_ENABLING:
2095 return "enabling";
2096 case WIFI_STATE_ENABLED:
2097 return "enabled";
2098 case WIFI_STATE_UNKNOWN:
2099 return "unknown state";
2100 default:
2101 return "[invalid state]";
2102 }
2103 }
2104
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002105 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002106 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
2107 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
2110 public void binderDied() {
2111 synchronized (mLocks) {
2112 releaseWifiLockLocked(mBinder);
2113 }
2114 }
2115
2116 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002117 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119 }
2120
2121 private class LockList {
2122 private List<WifiLock> mList;
2123
2124 private LockList() {
2125 mList = new ArrayList<WifiLock>();
2126 }
2127
2128 private synchronized boolean hasLocks() {
2129 return !mList.isEmpty();
2130 }
2131
2132 private synchronized int getStrongestLockMode() {
2133 if (mList.isEmpty()) {
2134 return WifiManager.WIFI_MODE_FULL;
2135 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002136
2137 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
2138 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002140
2141 if (mFullLocksAcquired > mFullLocksReleased) {
2142 return WifiManager.WIFI_MODE_FULL;
2143 }
2144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 return WifiManager.WIFI_MODE_SCAN_ONLY;
2146 }
2147
2148 private void addLock(WifiLock lock) {
2149 if (findLockByBinder(lock.mBinder) < 0) {
2150 mList.add(lock);
2151 }
2152 }
2153
2154 private WifiLock removeLock(IBinder binder) {
2155 int index = findLockByBinder(binder);
2156 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002157 WifiLock ret = mList.remove(index);
2158 ret.unlinkDeathRecipient();
2159 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 } else {
2161 return null;
2162 }
2163 }
2164
2165 private int findLockByBinder(IBinder binder) {
2166 int size = mList.size();
2167 for (int i = size - 1; i >= 0; i--)
2168 if (mList.get(i).mBinder == binder)
2169 return i;
2170 return -1;
2171 }
2172
2173 private void dump(PrintWriter pw) {
2174 for (WifiLock l : mList) {
2175 pw.print(" ");
2176 pw.println(l);
2177 }
2178 }
2179 }
2180
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002181 void enforceWakeSourcePermission(int uid, int pid) {
2182 if (uid == Process.myUid()) {
2183 return;
2184 }
2185 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
2186 pid, uid, null);
2187 }
2188
2189 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002191 if (lockMode != WifiManager.WIFI_MODE_FULL &&
2192 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
2193 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
2194 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
2195 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 return false;
2197 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002198 if (ws != null && ws.size() == 0) {
2199 ws = null;
2200 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002201 if (ws != null) {
2202 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
2203 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002204 if (ws == null) {
2205 ws = new WorkSource(Binder.getCallingUid());
2206 }
2207 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 synchronized (mLocks) {
2209 return acquireWifiLockLocked(wifiLock);
2210 }
2211 }
2212
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002213 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
2214 switch(wifiLock.mMode) {
2215 case WifiManager.WIFI_MODE_FULL:
2216 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2217 break;
2218 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2219 /* Treat high power as a full lock for battery stats */
2220 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2221 break;
2222 case WifiManager.WIFI_MODE_SCAN_ONLY:
2223 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2224 break;
2225 }
2226 }
2227
2228 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
2229 switch(wifiLock.mMode) {
2230 case WifiManager.WIFI_MODE_FULL:
2231 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2232 break;
2233 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2234 /* Treat high power as a full lock for battery stats */
2235 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2236 break;
2237 case WifiManager.WIFI_MODE_SCAN_ONLY:
2238 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
2239 break;
2240 }
2241 }
2242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07002244 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002247
The Android Open Source Project10592532009-03-18 17:39:46 -07002248 long ident = Binder.clearCallingIdentity();
2249 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002250 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002251 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002252 case WifiManager.WIFI_MODE_FULL:
2253 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002254 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002255 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2256 ++mFullHighPerfLocksAcquired;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002257 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002258 case WifiManager.WIFI_MODE_SCAN_ONLY:
2259 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002260 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002261 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002262
2263 // Be aggressive about adding new locks into the accounted state...
2264 // we want to over-report rather than under-report.
Irfan Sherifff92b4532010-11-03 11:13:10 -07002265 sendReportWorkSourceMessage();
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002266
2267 updateWifiState();
2268 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07002269 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002270 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07002271 } finally {
2272 Binder.restoreCallingIdentity(ident);
2273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 }
2275
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002276 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
2277 int uid = Binder.getCallingUid();
2278 int pid = Binder.getCallingPid();
2279 if (ws != null && ws.size() == 0) {
2280 ws = null;
2281 }
2282 if (ws != null) {
2283 enforceWakeSourcePermission(uid, pid);
2284 }
2285 long ident = Binder.clearCallingIdentity();
2286 try {
2287 synchronized (mLocks) {
2288 int index = mLocks.findLockByBinder(lock);
2289 if (index < 0) {
2290 throw new IllegalArgumentException("Wifi lock not active");
2291 }
2292 WifiLock wl = mLocks.mList.get(index);
2293 noteReleaseWifiLock(wl);
2294 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
2295 noteAcquireWifiLock(wl);
2296 }
2297 } catch (RemoteException e) {
2298 } finally {
2299 Binder.restoreCallingIdentity(ident);
2300 }
2301 }
2302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 public boolean releaseWifiLock(IBinder lock) {
2304 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2305 synchronized (mLocks) {
2306 return releaseWifiLockLocked(lock);
2307 }
2308 }
2309
2310 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002311 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002312
The Android Open Source Project10592532009-03-18 17:39:46 -07002313 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002314
Irfan Sheriffc89dd542010-09-28 08:40:54 -07002315 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002316
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002317 hadLock = (wifiLock != null);
2318
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002319 long ident = Binder.clearCallingIdentity();
2320 try {
2321 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002322 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002323 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002324 case WifiManager.WIFI_MODE_FULL:
2325 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002326 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002327 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2328 ++mFullHighPerfLocksReleased;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002329 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002330 case WifiManager.WIFI_MODE_SCAN_ONLY:
2331 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002332 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002333 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002334 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002335
2336 // TODO - should this only happen if you hadLock?
2337 updateWifiState();
2338
2339 } catch (RemoteException e) {
2340 } finally {
2341 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002342 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002343
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002344 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002346
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002347 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002348 implements IBinder.DeathRecipient {
2349 String mTag;
2350 int mMode;
2351 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002352 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002353
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002354 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002355 super();
2356 mTag = tag;
2357 mMode = mode;
2358 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002359 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002360 try {
2361 mBinder.linkToDeath(this, 0);
2362 } catch (RemoteException e) {
2363 binderDied();
2364 }
2365 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002366
2367 void unlinkDeathRecipient() {
2368 mBinder.unlinkToDeath(this, 0);
2369 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002370 }
2371
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002372 private class Multicaster extends DeathRecipient {
2373 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002374 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002375 }
2376
2377 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002378 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002379 synchronized (mMulticasters) {
2380 int i = mMulticasters.indexOf(this);
2381 if (i != -1) {
2382 removeMulticasterLocked(i, mMode);
2383 }
2384 }
2385 }
2386
2387 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002388 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002389 }
2390
2391 public int getUid() {
2392 return mMode;
2393 }
2394 }
2395
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002396 public void initializeMulticastFiltering() {
2397 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002398
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002399 synchronized (mMulticasters) {
2400 // if anybody had requested filters be off, leave off
2401 if (mMulticasters.size() != 0) {
2402 return;
2403 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002404 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002405 }
2406 }
2407 }
2408
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002409 public void acquireMulticastLock(IBinder binder, String tag) {
2410 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002411
2412 synchronized (mMulticasters) {
2413 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002414 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002415 // Note that we could call stopPacketFiltering only when
2416 // our new size == 1 (first call), but this function won't
2417 // be called often and by making the stopPacket call each
2418 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002419 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002420 }
2421
2422 int uid = Binder.getCallingUid();
2423 Long ident = Binder.clearCallingIdentity();
2424 try {
2425 mBatteryStats.noteWifiMulticastEnabled(uid);
2426 } catch (RemoteException e) {
2427 } finally {
2428 Binder.restoreCallingIdentity(ident);
2429 }
2430 }
2431
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002432 public void releaseMulticastLock() {
2433 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002434
2435 int uid = Binder.getCallingUid();
2436 synchronized (mMulticasters) {
2437 mMulticastDisabled++;
2438 int size = mMulticasters.size();
2439 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002440 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002441 if ((m != null) && (m.getUid() == uid)) {
2442 removeMulticasterLocked(i, uid);
2443 }
2444 }
2445 }
2446 }
2447
2448 private void removeMulticasterLocked(int i, int uid)
2449 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002450 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002451
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002452 if (removed != null) {
2453 removed.unlinkDeathRecipient();
2454 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002455 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002456 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002457 }
2458
2459 Long ident = Binder.clearCallingIdentity();
2460 try {
2461 mBatteryStats.noteWifiMulticastDisabled(uid);
2462 } catch (RemoteException e) {
2463 } finally {
2464 Binder.restoreCallingIdentity(ident);
2465 }
2466 }
2467
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002468 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002469 enforceAccessPermission();
2470
2471 synchronized (mMulticasters) {
2472 return (mMulticasters.size() > 0);
2473 }
2474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475}