blob: 371f22ee085eca94cae22216891f4ea5d5ce82e5 [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
148 private static final String WAKELOCK_TAG = "WifiService";
149
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 Sheriff5321aef2010-02-12 12:35:59 -0800176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178 private final WifiHandler mWifiHandler;
179
180 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 * Cache of scan results objects (size is somewhat arbitrary)
182 */
183 private static final int SCAN_RESULT_CACHE_SIZE = 80;
184 private final LinkedHashMap<String, ScanResult> mScanResultCache;
185
186 /*
187 * Character buffer used to parse scan results (optimization)
188 */
189 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private boolean mNeedReconfig;
191
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700192 /**
193 * Temporary for computing UIDS that are responsible for starting WIFI.
194 * Protected by mWifiStateTracker lock.
195 */
196 private final WorkSource mTmpWorkSource = new WorkSource();
197
Dianne Hackborn617f8772009-03-31 15:04:46 -0700198 /*
199 * Last UID that asked to enable WIFI.
200 */
201 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800202
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700203 /*
204 * Last UID that asked to enable WIFI AP.
205 */
206 private int mLastApEnableUid = Process.myUid();
207
208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 /**
210 * Number of allowed radio frequency channels in various regulatory domains.
211 * This list is sufficient for 802.11b/g networks (2.4GHz range).
212 */
213 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
214
215 private static final String ACTION_DEVICE_IDLE =
216 "com.android.server.WifiManager.action.DEVICE_IDLE";
217
218 WifiService(Context context, WifiStateTracker tracker) {
219 mContext = context;
220 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400221 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700222 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800223
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800224 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
225 nwService = INetworkManagementService.Stub.asInterface(b);
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 mScanResultCache = new LinkedHashMap<String, ScanResult>(
228 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
229 /*
230 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
231 * elements
232 */
233 public boolean removeEldestEntry(Map.Entry eldest) {
234 return SCAN_RESULT_CACHE_SIZE < this.size();
235 }
236 };
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 HandlerThread wifiThread = new HandlerThread("WifiService");
239 wifiThread.start();
240 mWifiHandler = new WifiHandler(wifiThread.getLooper());
241
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800242 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800243 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
246 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
247 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
248
249 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
250 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
251 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 mContext.registerReceiver(
254 new BroadcastReceiver() {
255 @Override
256 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700257 // clear our flag indicating the user has overwridden airplane mode
258 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700259 // on airplane disable, restore Wifi if the saved state indicates so
260 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
261 persistWifiEnabled(true);
262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 updateWifiState();
264 }
265 },
266 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
267
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800268 mContext.registerReceiver(
269 new BroadcastReceiver() {
270 @Override
271 public void onReceive(Context context, Intent intent) {
272
273 ArrayList<String> available = intent.getStringArrayListExtra(
274 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
275 ArrayList<String> active = intent.getStringArrayListExtra(
276 ConnectivityManager.EXTRA_ACTIVE_TETHER);
277 updateTetherState(available, active);
278
279 }
280 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800281 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800282
Irfan Sheriff7b009782010-03-11 16:37:45 -0800283 /**
284 * Check if Wi-Fi needs to be enabled and start
285 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700286 *
287 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800288 */
289 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700290 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700291 boolean wifiEnabled = !isAirplaneModeOn()
292 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800293 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
294 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700295 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800296 }
297
298 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
299
300 boolean wifiTethered = false;
301 boolean wifiAvailable = false;
302
303 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
304 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
305
306 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
307 mWifiRegexs = mCm.getTetherableWifiRegexs();
308
309 for (String intf : available) {
310 for (String regex : mWifiRegexs) {
311 if (intf.matches(regex)) {
312
313 InterfaceConfiguration ifcg = null;
314 try {
315 ifcg = service.getInterfaceConfig(intf);
316 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700317 /* IP/netmask: 192.168.43.1/255.255.255.0 */
318 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800319 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
320 ifcg.interfaceFlags = "up";
321
322 service.setInterfaceConfig(intf, ifcg);
323 }
324 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800325 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700326 try {
327 nwService.stopAccessPoint();
328 } catch (Exception ee) {
329 Slog.e(TAG, "Could not stop AP, :" + ee);
330 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800331 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800332 return;
333 }
334
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800335 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800336 Slog.e(TAG, "Error tethering "+intf);
337 }
338 break;
339 }
340 }
341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 }
343
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700344 private boolean testAndClearWifiSavedState() {
345 final ContentResolver cr = mContext.getContentResolver();
346 int wifiSavedState = 0;
347 try {
348 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
349 if(wifiSavedState == 1)
350 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
351 } catch (Settings.SettingNotFoundException e) {
352 ;
353 }
354 return (wifiSavedState == 1);
355 }
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 private boolean getPersistedWifiEnabled() {
358 final ContentResolver cr = mContext.getContentResolver();
359 try {
360 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
361 } catch (Settings.SettingNotFoundException e) {
362 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
363 return false;
364 }
365 }
366
367 private void persistWifiEnabled(boolean enabled) {
368 final ContentResolver cr = mContext.getContentResolver();
369 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
370 }
371
372 NetworkStateTracker getNetworkStateTracker() {
373 return mWifiStateTracker;
374 }
375
376 /**
377 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
378 * @return {@code true} if the operation succeeds
379 */
380 public boolean pingSupplicant() {
381 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800382
383 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385
386 /**
387 * see {@link android.net.wifi.WifiManager#startScan()}
388 * @return {@code true} if the operation succeeds
389 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400390 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800392
393 switch (mWifiStateTracker.getSupplicantState()) {
394 case DISCONNECTED:
395 case INACTIVE:
396 case SCANNING:
397 case DORMANT:
398 break;
399 default:
400 mWifiStateTracker.setScanResultHandling(
401 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
402 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800404 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
407 /**
408 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
409 * @param enable {@code true} to enable, {@code false} to disable.
410 * @return {@code true} if the enable/disable operation was
411 * started or is already in the queue.
412 */
413 public boolean setWifiEnabled(boolean enable) {
414 enforceChangePermission();
415 if (mWifiHandler == null) return false;
416
417 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700418 // caller may not have WAKE_LOCK permission - it's not required here
419 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700421 Binder.restoreCallingIdentity(ident);
422
Dianne Hackborn617f8772009-03-31 15:04:46 -0700423 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700424 // set a flag if the user is enabling Wifi while in airplane mode
425 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700426 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
428
429 return true;
430 }
431
432 /**
433 * Enables/disables Wi-Fi synchronously.
434 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
435 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700436 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * @return {@code true} if the operation succeeds (or if the existing state
438 * is the same as the requested state)
439 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700440 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800442 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800444 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 return true;
446 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700447 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 return false;
449 }
450
Irfan Sheriffcd770372010-01-08 09:36:04 -0800451 /**
452 * Multiple calls to unregisterReceiver() cause exception and a system crash.
453 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
454 * disable wifi at the same time.
455 * Avoid doing a disable when the current Wifi state is UNKNOWN
456 * TODO: Handle driver load fail and supplicant lost as seperate states
457 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800458 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800459 return false;
460 }
461
Irfan Sherifff91444c2010-03-24 12:11:00 -0700462 /**
463 * Fail Wifi if AP is enabled
464 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
465 * WIFI_STATE_FAILED
466 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800467 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700468 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
469 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800470 }
471
Irfan Sherifff91444c2010-03-24 12:11:00 -0700472 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800475 if (!mWifiStateTracker.loadDriver()) {
476 Slog.e(TAG, "Failed to load Wi-Fi driver.");
477 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
478 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800480 if (!mWifiStateTracker.startSupplicant()) {
481 mWifiStateTracker.unloadDriver();
482 Slog.e(TAG, "Failed to start supplicant daemon.");
483 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
484 return false;
485 }
486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 registerForBroadcasts();
488 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 } else {
491
492 mContext.unregisterReceiver(mReceiver);
493 // Remove notification (it will no-op if it isn't visible)
494 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
495
496 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800497
498 if (!mWifiStateTracker.stopSupplicant()) {
499 Slog.e(TAG, "Failed to stop supplicant daemon.");
500 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
501 failedToStopSupplicantOrUnloadDriver = true;
502 }
503
504 /**
505 * Reset connections and disable interface
506 * before we unload the driver
507 */
508 mWifiStateTracker.resetConnections(true);
509
510 if (!mWifiStateTracker.unloadDriver()) {
511 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
512 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700513 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 failedToStopSupplicantOrUnloadDriver = true;
515 }
516 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 if (failedToStopSupplicantOrUnloadDriver) {
519 return false;
520 }
521 }
522
523 // Success!
524
525 if (persist) {
526 persistWifiEnabled(enable);
527 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700528 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 return true;
530 }
531
Dianne Hackborn617f8772009-03-31 15:04:46 -0700532 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800533 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534
The Android Open Source Project10592532009-03-18 17:39:46 -0700535 long ident = Binder.clearCallingIdentity();
536 try {
537 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700538 mBatteryStats.noteWifiOn();
The Android Open Source Project10592532009-03-18 17:39:46 -0700539 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700540 mBatteryStats.noteWifiOff();
The Android Open Source Project10592532009-03-18 17:39:46 -0700541 }
542 } catch (RemoteException e) {
543 } finally {
544 Binder.restoreCallingIdentity(ident);
545 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800548 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
550 // Broadcast
551 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
552 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
553 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
554 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
555 mContext.sendStickyBroadcast(intent);
556 }
557
558 private void enforceAccessPermission() {
559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
560 "WifiService");
561 }
562
563 private void enforceChangePermission() {
564 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
565 "WifiService");
566
567 }
568
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700569 private void enforceMulticastChangePermission() {
570 mContext.enforceCallingOrSelfPermission(
571 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
572 "WifiService");
573 }
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 /**
576 * see {@link WifiManager#getWifiState()}
577 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
578 * {@link WifiManager#WIFI_STATE_DISABLING},
579 * {@link WifiManager#WIFI_STATE_ENABLED},
580 * {@link WifiManager#WIFI_STATE_ENABLING},
581 * {@link WifiManager#WIFI_STATE_UNKNOWN}
582 */
583 public int getWifiEnabledState() {
584 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800585 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
587
588 /**
589 * see {@link android.net.wifi.WifiManager#disconnect()}
590 * @return {@code true} if the operation succeeds
591 */
592 public boolean disconnect() {
593 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800594
595 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597
598 /**
599 * see {@link android.net.wifi.WifiManager#reconnect()}
600 * @return {@code true} if the operation succeeds
601 */
602 public boolean reconnect() {
603 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800604
605 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607
608 /**
609 * see {@link android.net.wifi.WifiManager#reassociate()}
610 * @return {@code true} if the operation succeeds
611 */
612 public boolean reassociate() {
613 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800614
615 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
617
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800618 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700619 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800620 * @param wifiConfig SSID, security and channel details as
621 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700622 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800623 * @return {@code true} if the start operation was
624 * started or is already in the queue.
625 */
626 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
627 enforceChangePermission();
628 if (mWifiHandler == null) return false;
629
630 synchronized (mWifiHandler) {
631
632 long ident = Binder.clearCallingIdentity();
633 sWakeLock.acquire();
634 Binder.restoreCallingIdentity(ident);
635
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700636 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800637 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
638 }
639
640 return true;
641 }
642
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800643 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700644 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800645 final ContentResolver cr = mContext.getContentResolver();
646 WifiConfiguration wifiConfig = new WifiConfiguration();
647 int authType;
648 try {
649 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
650 if (wifiConfig.SSID == null)
651 return null;
652 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
653 wifiConfig.allowedKeyManagement.set(authType);
654 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
655 return wifiConfig;
656 } catch (Settings.SettingNotFoundException e) {
657 Slog.e(TAG,"AP settings not found, returning");
658 return null;
659 }
660 }
661
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700662 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
663 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800664 final ContentResolver cr = mContext.getContentResolver();
665 boolean isWpa;
666 if (wifiConfig == null)
667 return;
668 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
669 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
670 Settings.Secure.putInt(cr,
671 Settings.Secure.WIFI_AP_SECURITY,
672 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
673 if (isWpa)
674 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
675 }
676
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800677 /**
678 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
679 * and soft access point configured as a single operation.
680 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800681 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800682 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800683 * @return {@code true} if the operation succeeds (or if the existing state
684 * is the same as the requested state)
685 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800686 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800687 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800688 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
689
690 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800691 /* Configuration changed on a running access point */
692 if(enable && (wifiConfig != null)) {
693 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700694 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
695 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700696 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800697 return true;
698 } catch(Exception e) {
699 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700700 try {
701 nwService.stopAccessPoint();
702 } catch (Exception ee) {
703 Slog.e(TAG, "Could not stop AP, :" + ee);
704 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800705 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
706 return false;
707 }
708 } else {
709 return true;
710 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800711 }
712
Irfan Sherifff91444c2010-03-24 12:11:00 -0700713 /**
714 * Fail AP if Wifi is enabled
715 */
716 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
717 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
718 return false;
719 }
720
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800721 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
722 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800723
724 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800725
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800726 /* Use default config if there is no existing config */
727 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
728 wifiConfig = new WifiConfiguration();
729 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
730 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
731 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800732
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800733 if (!mWifiStateTracker.loadDriver()) {
734 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800735 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800736 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800737 }
738
739 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700740 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
741 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 } catch(Exception e) {
743 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800744 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
745 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800746 }
747
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700748 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700749
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800750 } else {
751
752 try {
753 nwService.stopAccessPoint();
754 } catch(Exception e) {
755 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800756 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
757 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800758 }
759
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800760 if (!mWifiStateTracker.unloadDriver()) {
761 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800762 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800763 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800764 }
765 }
766
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800767 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800768 return true;
769 }
770
771 /**
772 * see {@link WifiManager#getWifiApState()}
773 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
774 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
775 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
776 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
777 * {@link WifiManager#WIFI_AP_STATE_FAILED}
778 */
779 public int getWifiApEnabledState() {
780 enforceAccessPermission();
781 return mWifiApState;
782 }
783
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800784 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800785 final int previousWifiApState = mWifiApState;
786
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800787 /**
788 * Unload the driver if going to a failed state
789 */
790 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
791 mWifiStateTracker.unloadDriver();
792 }
793
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800794 long ident = Binder.clearCallingIdentity();
795 try {
796 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700797 mBatteryStats.noteWifiOn();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800798 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700799 mBatteryStats.noteWifiOff();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800800 }
801 } catch (RemoteException e) {
802 } finally {
803 Binder.restoreCallingIdentity(ident);
804 }
805
806 // Update state
807 mWifiApState = wifiAPState;
808
809 // Broadcast
810 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
811 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
812 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
813 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
814 mContext.sendStickyBroadcast(intent);
815 }
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
818 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
819 * @return the list of configured networks
820 */
821 public List<WifiConfiguration> getConfiguredNetworks() {
822 enforceAccessPermission();
823 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 /*
826 * We don't cache the list, because we want to allow
827 * for the possibility that the configuration file
828 * has been modified through some external means,
829 * such as the wpa_cli command line program.
830 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800831 listStr = mWifiStateTracker.listNetworks();
832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 List<WifiConfiguration> networks =
834 new ArrayList<WifiConfiguration>();
835 if (listStr == null)
836 return networks;
837
838 String[] lines = listStr.split("\n");
839 // Skip the first line, which is a header
840 for (int i = 1; i < lines.length; i++) {
841 String[] result = lines[i].split("\t");
842 // network-id | ssid | bssid | flags
843 WifiConfiguration config = new WifiConfiguration();
844 try {
845 config.networkId = Integer.parseInt(result[0]);
846 } catch(NumberFormatException e) {
847 continue;
848 }
849 if (result.length > 3) {
850 if (result[3].indexOf("[CURRENT]") != -1)
851 config.status = WifiConfiguration.Status.CURRENT;
852 else if (result[3].indexOf("[DISABLED]") != -1)
853 config.status = WifiConfiguration.Status.DISABLED;
854 else
855 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800856 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800859 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 networks.add(config);
861 }
862
863 return networks;
864 }
865
866 /**
867 * Read the variables from the supplicant daemon that are needed to
868 * fill in the WifiConfiguration object.
869 * <p/>
870 * The caller must hold the synchronization monitor.
871 * @param config the {@link WifiConfiguration} object to be filled in.
872 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800873 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874
875 int netId = config.networkId;
876 if (netId < 0)
877 return;
878
879 /*
880 * TODO: maybe should have a native method that takes an array of
881 * variable names and returns an array of values. But we'd still
882 * be doing a round trip to the supplicant daemon for each variable.
883 */
884 String value;
885
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800886 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800888 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } else {
890 config.SSID = null;
891 }
892
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800893 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 if (!TextUtils.isEmpty(value)) {
895 config.BSSID = value;
896 } else {
897 config.BSSID = null;
898 }
899
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800900 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 config.priority = -1;
902 if (!TextUtils.isEmpty(value)) {
903 try {
904 config.priority = Integer.parseInt(value);
905 } catch (NumberFormatException ignore) {
906 }
907 }
908
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800909 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 config.hiddenSSID = false;
911 if (!TextUtils.isEmpty(value)) {
912 try {
913 config.hiddenSSID = Integer.parseInt(value) != 0;
914 } catch (NumberFormatException ignore) {
915 }
916 }
917
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800918 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 config.wepTxKeyIndex = -1;
920 if (!TextUtils.isEmpty(value)) {
921 try {
922 config.wepTxKeyIndex = Integer.parseInt(value);
923 } catch (NumberFormatException ignore) {
924 }
925 }
926
927 /*
928 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
929 * just a "*" if the key is set, or the null string otherwise.
930 */
931 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800932 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 if (!TextUtils.isEmpty(value)) {
934 config.wepKeys[i] = value;
935 } else {
936 config.wepKeys[i] = null;
937 }
938 }
939
940 /*
941 * Get the private shared key. Note that the actual keys are not passed back,
942 * just a "*" if the key is set, or the null string otherwise.
943 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800944 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (!TextUtils.isEmpty(value)) {
946 config.preSharedKey = value;
947 } else {
948 config.preSharedKey = null;
949 }
950
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800951 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 WifiConfiguration.Protocol.varName);
953 if (!TextUtils.isEmpty(value)) {
954 String vals[] = value.split(" ");
955 for (String val : vals) {
956 int index =
957 lookupString(val, WifiConfiguration.Protocol.strings);
958 if (0 <= index) {
959 config.allowedProtocols.set(index);
960 }
961 }
962 }
963
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800964 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 WifiConfiguration.KeyMgmt.varName);
966 if (!TextUtils.isEmpty(value)) {
967 String vals[] = value.split(" ");
968 for (String val : vals) {
969 int index =
970 lookupString(val, WifiConfiguration.KeyMgmt.strings);
971 if (0 <= index) {
972 config.allowedKeyManagement.set(index);
973 }
974 }
975 }
976
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800977 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 WifiConfiguration.AuthAlgorithm.varName);
979 if (!TextUtils.isEmpty(value)) {
980 String vals[] = value.split(" ");
981 for (String val : vals) {
982 int index =
983 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
984 if (0 <= index) {
985 config.allowedAuthAlgorithms.set(index);
986 }
987 }
988 }
989
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800990 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 WifiConfiguration.PairwiseCipher.varName);
992 if (!TextUtils.isEmpty(value)) {
993 String vals[] = value.split(" ");
994 for (String val : vals) {
995 int index =
996 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
997 if (0 <= index) {
998 config.allowedPairwiseCiphers.set(index);
999 }
1000 }
1001 }
1002
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001003 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 WifiConfiguration.GroupCipher.varName);
1005 if (!TextUtils.isEmpty(value)) {
1006 String vals[] = value.split(" ");
1007 for (String val : vals) {
1008 int index =
1009 lookupString(val, WifiConfiguration.GroupCipher.strings);
1010 if (0 <= index) {
1011 config.allowedGroupCiphers.set(index);
1012 }
1013 }
1014 }
Chung-yih Wang43374762009-09-16 14:28:42 +08001015
1016 for (WifiConfiguration.EnterpriseField field :
1017 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001018 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +08001019 field.varName());
1020 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001021 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001022 field.setValue(value);
1023 }
1024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001027 private static String removeDoubleQuotes(String string) {
1028 if (string.length() <= 2) return "";
1029 return string.substring(1, string.length() - 1);
1030 }
1031
1032 private static String convertToQuotedString(String string) {
1033 return "\"" + string + "\"";
1034 }
1035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1038 * @return the supplicant-assigned identifier for the new or updated
1039 * network if the operation succeeds, or {@code -1} if it fails
1040 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001041 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 /*
1045 * If the supplied networkId is -1, we create a new empty
1046 * network configuration. Otherwise, the networkId should
1047 * refer to an existing configuration.
1048 */
1049 int netId = config.networkId;
1050 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001051 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001053 synchronized (mWifiStateTracker) {
1054 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001055 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001056 if (netId < 0) {
1057 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001058 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001059 }
1060 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001062 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001064 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001067 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 /*
1069 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001070 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 * will fail, so we don't bother to make a separate check
1072 * for the validity of the ID up front.
1073 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001075 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001076 netId,
1077 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001078 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001080 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 break setVariables;
1083 }
1084
1085 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001086 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001087 netId,
1088 WifiConfiguration.bssidVarName,
1089 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001091 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 break setVariables;
1094 }
1095
1096 String allowedKeyManagementString =
1097 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1098 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001099 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001100 netId,
1101 WifiConfiguration.KeyMgmt.varName,
1102 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001104 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001105 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107 break setVariables;
1108 }
1109
1110 String allowedProtocolsString =
1111 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1112 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001113 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001114 netId,
1115 WifiConfiguration.Protocol.varName,
1116 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001118 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001119 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121 break setVariables;
1122 }
1123
1124 String allowedAuthAlgorithmsString =
1125 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1126 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001127 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001128 netId,
1129 WifiConfiguration.AuthAlgorithm.varName,
1130 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001132 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001133 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 break setVariables;
1136 }
1137
1138 String allowedPairwiseCiphersString =
1139 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1140 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001141 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001142 netId,
1143 WifiConfiguration.PairwiseCipher.varName,
1144 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001146 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001147 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 }
1149 break setVariables;
1150 }
1151
1152 String allowedGroupCiphersString =
1153 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1154 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001155 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001156 netId,
1157 WifiConfiguration.GroupCipher.varName,
1158 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001160 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001161 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163 break setVariables;
1164 }
1165
1166 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1167 // by preventing "*" as a key.
1168 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001169 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001170 netId,
1171 WifiConfiguration.pskVarName,
1172 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001174 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176 break setVariables;
1177 }
1178
1179 boolean hasSetKey = false;
1180 if (config.wepKeys != null) {
1181 for (int i = 0; i < config.wepKeys.length; i++) {
1182 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1183 // by preventing "*" as a key.
1184 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001185 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001186 netId,
1187 WifiConfiguration.wepKeyVarNames[i],
1188 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001190 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001191 "failed to set wep_key"+i+": " +
1192 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194 break setVariables;
1195 }
1196 hasSetKey = true;
1197 }
1198 }
1199 }
1200
1201 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001202 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001203 netId,
1204 WifiConfiguration.wepTxKeyIdxVarName,
1205 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001208 "failed to set wep_tx_keyidx: "+
1209 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 break setVariables;
1212 }
1213 }
1214
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001215 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001216 netId,
1217 WifiConfiguration.priorityVarName,
1218 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001220 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001221 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
1223 break setVariables;
1224 }
1225
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001226 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001227 netId,
1228 WifiConfiguration.hiddenSSIDVarName,
1229 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001231 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001232 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 break setVariables;
1235 }
1236
Chung-yih Wang43374762009-09-16 14:28:42 +08001237 for (WifiConfiguration.EnterpriseField field
1238 : config.enterpriseFields) {
1239 String varName = field.varName();
1240 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001241 if (value != null) {
1242 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001243 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001244 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001245 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001246 netId,
1247 varName,
1248 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001249 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001250 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001251 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001252 }
1253 break setVariables;
1254 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001255 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001260 /*
1261 * For an update, if one of the setNetworkVariable operations fails,
1262 * we might want to roll back all the changes already made. But the
1263 * chances are that if anything is going to go wrong, it'll happen
1264 * the first time we try to set one of the variables.
1265 */
1266 if (newNetwork) {
1267 removeNetwork(netId);
1268 if (DBG) {
1269 Slog.d(TAG,
1270 "Failed to set a network variable, removed network: "
1271 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
1273 }
1274 return -1;
1275 }
1276
1277 private static String makeString(BitSet set, String[] strings) {
1278 StringBuffer buf = new StringBuffer();
1279 int nextSetBit = -1;
1280
1281 /* Make sure all set bits are in [0, strings.length) to avoid
1282 * going out of bounds on strings. (Shouldn't happen, but...) */
1283 set = set.get(0, strings.length);
1284
1285 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1286 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1287 }
1288
1289 // remove trailing space
1290 if (set.cardinality() > 0) {
1291 buf.setLength(buf.length() - 1);
1292 }
1293
1294 return buf.toString();
1295 }
1296
1297 private static int lookupString(String string, String[] strings) {
1298 int size = strings.length;
1299
1300 string = string.replace('-', '_');
1301
1302 for (int i = 0; i < size; i++)
1303 if (string.equals(strings[i]))
1304 return i;
1305
1306 if (DBG) {
1307 // if we ever get here, we should probably add the
1308 // value to WifiConfiguration to reflect that it's
1309 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001310 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312
1313 return -1;
1314 }
1315
1316 /**
1317 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1318 * @param netId the integer that identifies the network configuration
1319 * to the supplicant
1320 * @return {@code true} if the operation succeeded
1321 */
1322 public boolean removeNetwork(int netId) {
1323 enforceChangePermission();
1324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 return mWifiStateTracker.removeNetwork(netId);
1326 }
1327
1328 /**
1329 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1330 * @param netId the integer that identifies the network configuration
1331 * to the supplicant
1332 * @param disableOthers if true, disable all other networks.
1333 * @return {@code true} if the operation succeeded
1334 */
1335 public boolean enableNetwork(int netId, boolean disableOthers) {
1336 enforceChangePermission();
1337
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001338 String ifname = mWifiStateTracker.getInterfaceName();
1339 NetworkUtils.enableInterface(ifname);
1340 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1341 if (!result) {
1342 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001344 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346
1347 /**
1348 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1349 * @param netId the integer that identifies the network configuration
1350 * to the supplicant
1351 * @return {@code true} if the operation succeeded
1352 */
1353 public boolean disableNetwork(int netId) {
1354 enforceChangePermission();
1355
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001356 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358
1359 /**
1360 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1361 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1362 */
1363 public WifiInfo getConnectionInfo() {
1364 enforceAccessPermission();
1365 /*
1366 * Make sure we have the latest information, by sending
1367 * a status request to the supplicant.
1368 */
1369 return mWifiStateTracker.requestConnectionInfo();
1370 }
1371
1372 /**
1373 * Return the results of the most recent access point scan, in the form of
1374 * a list of {@link ScanResult} objects.
1375 * @return the list of results
1376 */
1377 public List<ScanResult> getScanResults() {
1378 enforceAccessPermission();
1379 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001380
1381 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 if (reply == null) {
1383 return null;
1384 }
1385
1386 List<ScanResult> scanList = new ArrayList<ScanResult>();
1387
1388 int lineCount = 0;
1389
1390 int replyLen = reply.length();
1391 // Parse the result string, keeping in mind that the last line does
1392 // not end with a newline.
1393 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1394 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1395 ++lineCount;
1396 /*
1397 * Skip the first line, which is a header
1398 */
1399 if (lineCount == 1) {
1400 lineBeg = lineEnd + 1;
1401 continue;
1402 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001403 if (lineEnd > lineBeg) {
1404 String line = reply.substring(lineBeg, lineEnd);
1405 ScanResult scanResult = parseScanResult(line);
1406 if (scanResult != null) {
1407 scanList.add(scanResult);
1408 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001409 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
1411 }
1412 lineBeg = lineEnd + 1;
1413 }
1414 }
1415 mWifiStateTracker.setScanResultsList(scanList);
1416 return scanList;
1417 }
1418
1419 /**
1420 * Parse the scan result line passed to us by wpa_supplicant (helper).
1421 * @param line the line to parse
1422 * @return the {@link ScanResult} object
1423 */
1424 private ScanResult parseScanResult(String line) {
1425 ScanResult scanResult = null;
1426 if (line != null) {
1427 /*
1428 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1429 * must synchronized here!
1430 */
1431 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001432 String[] result = scanResultPattern.split(line);
1433 if (3 <= result.length && result.length <= 5) {
1434 String bssid = result[0];
1435 // bssid | frequency | level | flags | ssid
1436 int frequency;
1437 int level;
1438 try {
1439 frequency = Integer.parseInt(result[1]);
1440 level = Integer.parseInt(result[2]);
1441 /* some implementations avoid negative values by adding 256
1442 * so we need to adjust for that here.
1443 */
1444 if (level > 0) level -= 256;
1445 } catch (NumberFormatException e) {
1446 frequency = 0;
1447 level = 0;
1448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449
Mike Lockwood1a645052009-06-25 13:01:12 -04001450 /*
1451 * The formatting of the results returned by
1452 * wpa_supplicant is intended to make the fields
1453 * line up nicely when printed,
1454 * not to make them easy to parse. So we have to
1455 * apply some heuristics to figure out which field
1456 * is the SSID and which field is the flags.
1457 */
1458 String ssid;
1459 String flags;
1460 if (result.length == 4) {
1461 if (result[3].charAt(0) == '[') {
1462 flags = result[3];
1463 ssid = "";
1464 } else {
1465 flags = "";
1466 ssid = result[3];
1467 }
1468 } else if (result.length == 5) {
1469 flags = result[3];
1470 ssid = result[4];
1471 } else {
1472 // Here, we must have 3 fields: no flags and ssid
1473 // set
1474 flags = "";
1475 ssid = "";
1476 }
1477
Mike Lockwood00717e22009-08-17 10:09:36 -04001478 // bssid + ssid is the hash key
1479 String key = bssid + ssid;
1480 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001481 if (scanResult != null) {
1482 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001483 scanResult.SSID = ssid;
1484 scanResult.capabilities = flags;
1485 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001486 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 // Do not add scan results that have no SSID set
1488 if (0 < ssid.trim().length()) {
1489 scanResult =
1490 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001491 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001492 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001495 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001496 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001497 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 }
1500 }
1501
1502 return scanResult;
1503 }
1504
1505 /**
1506 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1507 * and construct a {@code WifiConfiguration} that describes the encryption,
1508 * key management, and authenticaion capabilities of the access point.
1509 * @param flags the string returned by wpa_supplicant
1510 * @return the {@link WifiConfiguration} object, filled in
1511 */
1512 WifiConfiguration parseScanFlags(String flags) {
1513 WifiConfiguration config = new WifiConfiguration();
1514
1515 if (flags.length() == 0) {
1516 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1517 }
1518 // ... to be implemented
1519 return config;
1520 }
1521
1522 /**
1523 * Tell the supplicant to persist the current list of configured networks.
1524 * @return {@code true} if the operation succeeded
1525 */
1526 public boolean saveConfiguration() {
1527 boolean result;
1528 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001531 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 if (result && mNeedReconfig) {
1533 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001534 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535
1536 if (result) {
1537 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1538 mContext.sendBroadcast(intent);
1539 }
1540 }
1541 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001542 // Inform the backup manager about a data change
1543 IBackupManager ibm = IBackupManager.Stub.asInterface(
1544 ServiceManager.getService(Context.BACKUP_SERVICE));
1545 if (ibm != null) {
1546 try {
1547 ibm.dataChanged("com.android.providers.settings");
1548 } catch (Exception e) {
1549 // Try again later
1550 }
1551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 return result;
1553 }
1554
1555 /**
1556 * Set the number of radio frequency channels that are allowed to be used
1557 * in the current regulatory domain. This method should be used only
1558 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001559 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 * persisted as a Secure setting.
1561 * @param numChannels the number of allowed channels. Must be greater than 0
1562 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001563 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1565 * {@code numChannels} is outside the valid range.
1566 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001567 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001568 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001569 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 /*
1573 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1574 * but if Wi-Fi isn't currently enabled, that's not possible, and
1575 * we want to persist the setting anyway,so that it will take
1576 * effect when Wi-Fi does become enabled.
1577 */
1578 boolean found = false;
1579 for (int validChan : sValidRegulatoryChannelCounts) {
1580 if (validChan == numChannels) {
1581 found = true;
1582 break;
1583 }
1584 }
1585 if (!found) {
1586 return false;
1587 }
1588
Irfan Sheriff59610c02010-03-30 11:00:41 -07001589 if (mWifiHandler == null) return false;
1590
1591 Message.obtain(mWifiHandler,
1592 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1593
1594 return true;
1595 }
1596
1597 /**
1598 * sets the number of allowed radio frequency channels synchronously
1599 * @param numChannels the number of allowed channels. Must be greater than 0
1600 * and less than or equal to 16.
1601 * @param persist {@code true} if the setting should be remembered.
1602 * @return {@code true} if the operation succeeds, {@code false} otherwise
1603 */
1604 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001605 if (persist) {
1606 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001607 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1608 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001609 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001610 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
1613 /**
1614 * Return the number of frequency channels that are allowed
1615 * to be used in the current regulatory domain.
1616 * @return the number of allowed channels, or {@code -1} if an error occurs
1617 */
1618 public int getNumAllowedChannels() {
1619 int numChannels;
1620
1621 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001622
1623 /*
1624 * If we can't get the value from the driver (e.g., because
1625 * Wi-Fi is not currently enabled), get the value from
1626 * Settings.
1627 */
1628 numChannels = mWifiStateTracker.getNumAllowedChannels();
1629 if (numChannels < 0) {
1630 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1631 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1632 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 return numChannels;
1635 }
1636
1637 /**
1638 * Return the list of valid values for the number of allowed radio channels
1639 * for various regulatory domains.
1640 * @return the list of channel counts
1641 */
1642 public int[] getValidChannelCounts() {
1643 enforceAccessPermission();
1644 return sValidRegulatoryChannelCounts;
1645 }
1646
1647 /**
1648 * Return the DHCP-assigned addresses from the last successful DHCP request,
1649 * if any.
1650 * @return the DHCP information
1651 */
1652 public DhcpInfo getDhcpInfo() {
1653 enforceAccessPermission();
1654 return mWifiStateTracker.getDhcpInfo();
1655 }
1656
1657 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1658 @Override
1659 public void onReceive(Context context, Intent intent) {
1660 String action = intent.getAction();
1661
Doug Zongker43866e02010-01-07 12:09:54 -08001662 long idleMillis =
1663 Settings.Secure.getLong(mContext.getContentResolver(),
1664 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001666 Settings.System.getInt(mContext.getContentResolver(),
1667 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001669 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 mAlarmManager.cancel(mIdleIntent);
1671 mDeviceIdle = false;
1672 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001673 // Once the screen is on, we are not keeping WIFI running
1674 // because of any locks so clear that tracking immediately.
1675 reportStartWorkSource();
Mike Lockwoodf32be162009-07-14 17:44:37 -04001676 mWifiStateTracker.enableRssiPolling(true);
Irfan Sherifffae66c32010-08-16 11:36:41 -07001677 /* DHCP or other temporary failures in the past can prevent
1678 * a disabled network from being connected to, enable on screen on
1679 */
1680 if (mWifiStateTracker.isAnyNetworkDisabled()) {
1681 sendEnableNetworksMessage();
1682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001686 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 /*
1688 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1689 * AND the "stay on while plugged in" setting doesn't match the
1690 * current power conditions (i.e, not plugged in, plugged in to USB,
1691 * or plugged in to AC).
1692 */
1693 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001694 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1695 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001696 // we used to go to sleep immediately, but this caused some race conditions
1697 // we don't have time to track down for this release. Delay instead, but not
1698 // as long as we would if connected (below)
1699 // TODO - fix the race conditions and switch back to the immediate turn-off
1700 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001701 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001702 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1703 // // do not keep Wifi awake when screen is off if Wifi is not associated
1704 // mDeviceIdle = true;
1705 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001706 } else {
1707 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001708 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001709 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
1712 /* we can return now -- there's nothing to do until we get the idle intent back */
1713 return;
1714 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001715 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001717 reportStartWorkSource();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1719 /*
1720 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1721 * AND we are transitioning from a state in which the device was supposed
1722 * to stay awake to a state in which it is not supposed to stay awake.
1723 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1724 * the already-set timer.
1725 */
1726 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001727 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1729 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1730 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001731 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1733 mPluggedType = pluggedType;
1734 return;
1735 }
1736 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001737 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001738 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1739 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1740 boolean isBluetoothPlaying = false;
1741 for (BluetoothDevice sink : sinks) {
1742 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1743 isBluetoothPlaying = true;
1744 }
1745 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001746 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 } else {
1749 return;
1750 }
1751
1752 updateWifiState();
1753 }
1754
1755 /**
1756 * Determines whether the Wi-Fi chipset should stay awake or be put to
1757 * sleep. Looks at the setting for the sleep policy and the current
1758 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001759 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 * @see #shouldDeviceStayAwake(int, int)
1761 */
1762 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1763 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1764 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1765
1766 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1767 // Never sleep
1768 return true;
1769 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1770 (pluggedType != 0)) {
1771 // Never sleep while plugged, and we're plugged
1772 return true;
1773 } else {
1774 // Default
1775 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1776 }
1777 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 /**
1780 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1781 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1782 * of {@code 0} isn't really a plugged type, but rather an indication that the
1783 * device isn't plugged in at all, there is no bit value corresponding to a
1784 * {@code pluggedType} value of {@code 0}. That is why we shift by
1785 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1786 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1787 * keep the device (and hence Wi-Fi) awake.
1788 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1789 * being made
1790 * @return {@code true} if {@code pluggedType} indicates that the device is
1791 * supposed to stay awake, {@code false} otherwise.
1792 */
1793 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1794 return (stayAwakeConditions & pluggedType) != 0;
1795 }
1796 };
1797
Dianne Hackborn617f8772009-03-31 15:04:46 -07001798 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 Message msg = Message.obtain(mWifiHandler,
1800 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001801 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 msg.sendToTarget();
1803 }
1804
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001805 private void sendStartMessage(int lockMode) {
1806 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, lockMode, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001809 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1810 Message.obtain(mWifiHandler,
1811 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001812 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001813 }
1814
Irfan Sherifffae66c32010-08-16 11:36:41 -07001815 private void sendEnableNetworksMessage() {
1816 Message.obtain(mWifiHandler, MESSAGE_ENABLE_NETWORKS).sendToTarget();
1817 }
1818
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001819 private void reportStartWorkSource() {
1820 synchronized (mWifiStateTracker) {
1821 mTmpWorkSource.clear();
1822 if (mDeviceIdle) {
1823 for (int i=0; i<mLocks.mList.size(); i++) {
1824 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
1825 }
1826 }
1827 mWifiStateTracker.updateBatteryWorkSourceLocked(mTmpWorkSource);
1828 }
1829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001832 // send a message so it's all serialized
1833 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1834 }
1835
1836 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001838 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001839
1840 boolean lockHeld;
1841 synchronized (mLocks) {
1842 lockHeld = mLocks.hasLocks();
1843 }
1844
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001845 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1847 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001848
1849 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001851 }
1852 /* If device is not idle, lockmode cannot be scan only */
1853 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1855 }
1856
1857 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001858 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 return;
1860 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001861
1862 /* Disable tethering when airplane mode is enabled */
1863 if (airplaneMode &&
1864 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1865 sWakeLock.acquire();
1866 sendAccessPointMessage(false, null, mLastApEnableUid);
1867 }
1868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 if (wifiShouldBeEnabled) {
1870 if (wifiShouldBeStarted) {
1871 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001872 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 sWakeLock.acquire();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001874 sendStartMessage(strongestLockMode);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001875 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 int wakeLockTimeout =
1877 Settings.Secure.getInt(
1878 mContext.getContentResolver(),
1879 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1880 DEFAULT_WAKELOCK_TIMEOUT);
1881 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001882 * We are assuming that ConnectivityService can make
1883 * a transition to cellular data within wakeLockTimeout time.
1884 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 */
1886 sDriverStopWakeLock.acquire();
1887 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1888 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1889 }
1890 } else {
1891 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001892 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 }
1895 }
1896
1897 private void registerForBroadcasts() {
1898 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1900 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1901 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1902 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001903 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 mContext.registerReceiver(mReceiver, intentFilter);
1905 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 private boolean isAirplaneSensitive() {
1908 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1909 Settings.System.AIRPLANE_MODE_RADIOS);
1910 return airplaneModeRadios == null
1911 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1912 }
1913
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001914 private boolean isAirplaneToggleable() {
1915 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1916 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1917 return toggleableRadios != null
1918 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1919 }
1920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 /**
1922 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1923 * currently on.
1924 * @return {@code true} if airplane mode is on.
1925 */
1926 private boolean isAirplaneModeOn() {
1927 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1928 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1929 }
1930
1931 /**
1932 * Handler that allows posting to the WifiThread.
1933 */
1934 private class WifiHandler extends Handler {
1935 public WifiHandler(Looper looper) {
1936 super(looper);
1937 }
1938
1939 @Override
1940 public void handleMessage(Message msg) {
1941 switch (msg.what) {
1942
1943 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001944 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001945 if (mWifiWatchdogService == null) {
1946 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 sWakeLock.release();
1949 break;
1950
1951 case MESSAGE_START_WIFI:
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001952 reportStartWorkSource();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001953 mWifiStateTracker.setScanOnlyMode(msg.arg1 == WifiManager.WIFI_MODE_SCAN_ONLY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 mWifiStateTracker.restart();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001955 mWifiStateTracker.setHighPerfMode(msg.arg1 ==
1956 WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 sWakeLock.release();
1958 break;
1959
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001960 case MESSAGE_UPDATE_STATE:
1961 doUpdateWifiState();
1962 break;
1963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 case MESSAGE_DISABLE_WIFI:
1965 // a non-zero msg.arg1 value means the "enabled" setting
1966 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001967 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001968 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 sWakeLock.release();
1970 break;
1971
1972 case MESSAGE_STOP_WIFI:
1973 mWifiStateTracker.disconnectAndStop();
1974 // don't release wakelock
1975 break;
1976
1977 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001978 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001980
1981 case MESSAGE_START_ACCESS_POINT:
1982 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001983 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001984 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001985 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001986 break;
1987
1988 case MESSAGE_STOP_ACCESS_POINT:
1989 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001990 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001991 (WifiConfiguration) msg.obj);
1992 sWakeLock.release();
1993 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001994
1995 case MESSAGE_SET_CHANNELS:
1996 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1997 break;
1998
Irfan Sherifffae66c32010-08-16 11:36:41 -07001999 case MESSAGE_ENABLE_NETWORKS:
2000 mWifiStateTracker.enableAllNetworks(getConfiguredNetworks());
2001 break;
2002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004 }
2005 }
2006
2007 @Override
2008 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2009 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2010 != PackageManager.PERMISSION_GRANTED) {
2011 pw.println("Permission Denial: can't dump WifiService from from pid="
2012 + Binder.getCallingPid()
2013 + ", uid=" + Binder.getCallingUid());
2014 return;
2015 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08002016 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 pw.println("Stay-awake conditions: " +
2018 Settings.System.getInt(mContext.getContentResolver(),
2019 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
2020 pw.println();
2021
2022 pw.println("Internal state:");
2023 pw.println(mWifiStateTracker);
2024 pw.println();
2025 pw.println("Latest scan results:");
2026 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
2027 if (scanResults != null && scanResults.size() != 0) {
2028 pw.println(" BSSID Frequency RSSI Flags SSID");
2029 for (ScanResult r : scanResults) {
2030 pw.printf(" %17s %9d %5d %-16s %s%n",
2031 r.BSSID,
2032 r.frequency,
2033 r.level,
2034 r.capabilities,
2035 r.SSID == null ? "" : r.SSID);
2036 }
2037 }
2038 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002039 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002040 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002041 mScanLocksAcquired + " scan");
2042 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002043 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002044 mScanLocksReleased + " scan");
2045 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 pw.println("Locks held:");
2047 mLocks.dump(pw);
2048 }
2049
2050 private static String stateName(int wifiState) {
2051 switch (wifiState) {
2052 case WIFI_STATE_DISABLING:
2053 return "disabling";
2054 case WIFI_STATE_DISABLED:
2055 return "disabled";
2056 case WIFI_STATE_ENABLING:
2057 return "enabling";
2058 case WIFI_STATE_ENABLED:
2059 return "enabled";
2060 case WIFI_STATE_UNKNOWN:
2061 return "unknown state";
2062 default:
2063 return "[invalid state]";
2064 }
2065 }
2066
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002067 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002068 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
2069 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071
2072 public void binderDied() {
2073 synchronized (mLocks) {
2074 releaseWifiLockLocked(mBinder);
2075 }
2076 }
2077
2078 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002079 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 }
2082
2083 private class LockList {
2084 private List<WifiLock> mList;
2085
2086 private LockList() {
2087 mList = new ArrayList<WifiLock>();
2088 }
2089
2090 private synchronized boolean hasLocks() {
2091 return !mList.isEmpty();
2092 }
2093
2094 private synchronized int getStrongestLockMode() {
2095 if (mList.isEmpty()) {
2096 return WifiManager.WIFI_MODE_FULL;
2097 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002098
2099 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
2100 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002102
2103 if (mFullLocksAcquired > mFullLocksReleased) {
2104 return WifiManager.WIFI_MODE_FULL;
2105 }
2106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 return WifiManager.WIFI_MODE_SCAN_ONLY;
2108 }
2109
2110 private void addLock(WifiLock lock) {
2111 if (findLockByBinder(lock.mBinder) < 0) {
2112 mList.add(lock);
2113 }
2114 }
2115
2116 private WifiLock removeLock(IBinder binder) {
2117 int index = findLockByBinder(binder);
2118 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002119 WifiLock ret = mList.remove(index);
2120 ret.unlinkDeathRecipient();
2121 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 } else {
2123 return null;
2124 }
2125 }
2126
2127 private int findLockByBinder(IBinder binder) {
2128 int size = mList.size();
2129 for (int i = size - 1; i >= 0; i--)
2130 if (mList.get(i).mBinder == binder)
2131 return i;
2132 return -1;
2133 }
2134
2135 private void dump(PrintWriter pw) {
2136 for (WifiLock l : mList) {
2137 pw.print(" ");
2138 pw.println(l);
2139 }
2140 }
2141 }
2142
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002143 void enforceWakeSourcePermission(int uid, int pid) {
2144 if (uid == Process.myUid()) {
2145 return;
2146 }
2147 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
2148 pid, uid, null);
2149 }
2150
2151 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002153 if (lockMode != WifiManager.WIFI_MODE_FULL &&
2154 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
2155 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
2156 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
2157 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 return false;
2159 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002160 if (ws != null) {
2161 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
2162 }
2163 if (ws != null && ws.size() == 0) {
2164 ws = null;
2165 }
2166 if (ws == null) {
2167 ws = new WorkSource(Binder.getCallingUid());
2168 }
2169 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 synchronized (mLocks) {
2171 return acquireWifiLockLocked(wifiLock);
2172 }
2173 }
2174
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002175 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
2176 switch(wifiLock.mMode) {
2177 case WifiManager.WIFI_MODE_FULL:
2178 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2179 break;
2180 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2181 /* Treat high power as a full lock for battery stats */
2182 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2183 break;
2184 case WifiManager.WIFI_MODE_SCAN_ONLY:
2185 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2186 break;
2187 }
2188 }
2189
2190 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
2191 switch(wifiLock.mMode) {
2192 case WifiManager.WIFI_MODE_FULL:
2193 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2194 break;
2195 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2196 /* Treat high power as a full lock for battery stats */
2197 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2198 break;
2199 case WifiManager.WIFI_MODE_SCAN_ONLY:
2200 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
2201 break;
2202 }
2203 }
2204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002206 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002209
The Android Open Source Project10592532009-03-18 17:39:46 -07002210 long ident = Binder.clearCallingIdentity();
2211 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002212 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002213 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002214 case WifiManager.WIFI_MODE_FULL:
2215 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002216 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002217 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2218 ++mFullHighPerfLocksAcquired;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002219 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002220 case WifiManager.WIFI_MODE_SCAN_ONLY:
2221 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002222 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002223 }
2224 } catch (RemoteException e) {
2225 } finally {
2226 Binder.restoreCallingIdentity(ident);
2227 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002228
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07002229 // Be aggressive about adding new locks into the accounted state...
2230 // we want to over-report rather than under-report.
2231 reportStartWorkSource();
2232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 updateWifiState();
2234 return true;
2235 }
2236
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002237 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
2238 int uid = Binder.getCallingUid();
2239 int pid = Binder.getCallingPid();
2240 if (ws != null && ws.size() == 0) {
2241 ws = null;
2242 }
2243 if (ws != null) {
2244 enforceWakeSourcePermission(uid, pid);
2245 }
2246 long ident = Binder.clearCallingIdentity();
2247 try {
2248 synchronized (mLocks) {
2249 int index = mLocks.findLockByBinder(lock);
2250 if (index < 0) {
2251 throw new IllegalArgumentException("Wifi lock not active");
2252 }
2253 WifiLock wl = mLocks.mList.get(index);
2254 noteReleaseWifiLock(wl);
2255 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
2256 noteAcquireWifiLock(wl);
2257 }
2258 } catch (RemoteException e) {
2259 } finally {
2260 Binder.restoreCallingIdentity(ident);
2261 }
2262 }
2263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 public boolean releaseWifiLock(IBinder lock) {
2265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2266 synchronized (mLocks) {
2267 return releaseWifiLockLocked(lock);
2268 }
2269 }
2270
2271 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002272 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002273
The Android Open Source Project10592532009-03-18 17:39:46 -07002274 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002275
Joe Onorato8a9b2202010-02-26 18:56:32 -08002276 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002277
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002278 hadLock = (wifiLock != null);
2279
2280 if (hadLock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002281 long ident = Binder.clearCallingIdentity();
2282 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002283 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002284 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002285 case WifiManager.WIFI_MODE_FULL:
2286 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002287 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002288 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2289 ++mFullHighPerfLocksReleased;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002290 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002291 case WifiManager.WIFI_MODE_SCAN_ONLY:
2292 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002293 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002294 }
2295 } catch (RemoteException e) {
2296 } finally {
2297 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002298 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002299 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002300 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002302 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002304
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002305 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002306 implements IBinder.DeathRecipient {
2307 String mTag;
2308 int mMode;
2309 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002310 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002311
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002312 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002313 super();
2314 mTag = tag;
2315 mMode = mode;
2316 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002317 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002318 try {
2319 mBinder.linkToDeath(this, 0);
2320 } catch (RemoteException e) {
2321 binderDied();
2322 }
2323 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002324
2325 void unlinkDeathRecipient() {
2326 mBinder.unlinkToDeath(this, 0);
2327 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002328 }
2329
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002330 private class Multicaster extends DeathRecipient {
2331 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002332 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002333 }
2334
2335 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002336 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002337 synchronized (mMulticasters) {
2338 int i = mMulticasters.indexOf(this);
2339 if (i != -1) {
2340 removeMulticasterLocked(i, mMode);
2341 }
2342 }
2343 }
2344
2345 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002346 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002347 }
2348
2349 public int getUid() {
2350 return mMode;
2351 }
2352 }
2353
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002354 public void initializeMulticastFiltering() {
2355 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002356
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002357 synchronized (mMulticasters) {
2358 // if anybody had requested filters be off, leave off
2359 if (mMulticasters.size() != 0) {
2360 return;
2361 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002362 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002363 }
2364 }
2365 }
2366
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002367 public void acquireMulticastLock(IBinder binder, String tag) {
2368 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002369
2370 synchronized (mMulticasters) {
2371 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002372 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002373 // Note that we could call stopPacketFiltering only when
2374 // our new size == 1 (first call), but this function won't
2375 // be called often and by making the stopPacket call each
2376 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002377 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002378 }
2379
2380 int uid = Binder.getCallingUid();
2381 Long ident = Binder.clearCallingIdentity();
2382 try {
2383 mBatteryStats.noteWifiMulticastEnabled(uid);
2384 } catch (RemoteException e) {
2385 } finally {
2386 Binder.restoreCallingIdentity(ident);
2387 }
2388 }
2389
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002390 public void releaseMulticastLock() {
2391 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002392
2393 int uid = Binder.getCallingUid();
2394 synchronized (mMulticasters) {
2395 mMulticastDisabled++;
2396 int size = mMulticasters.size();
2397 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002398 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002399 if ((m != null) && (m.getUid() == uid)) {
2400 removeMulticasterLocked(i, uid);
2401 }
2402 }
2403 }
2404 }
2405
2406 private void removeMulticasterLocked(int i, int uid)
2407 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002408 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002409
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002410 if (removed != null) {
2411 removed.unlinkDeathRecipient();
2412 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002413 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002414 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002415 }
2416
2417 Long ident = Binder.clearCallingIdentity();
2418 try {
2419 mBatteryStats.noteWifiMulticastDisabled(uid);
2420 } catch (RemoteException e) {
2421 } finally {
2422 Binder.restoreCallingIdentity(ident);
2423 }
2424 }
2425
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002426 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002427 enforceAccessPermission();
2428
2429 synchronized (mMulticasters) {
2430 return (mMulticasters.size() > 0);
2431 }
2432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433}