blob: a63b3d8d45f88778d46d3a9f613e3e3dfa999da2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
Irfan Sheriff5321aef2010-02-12 12:35:59 -080025import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
26import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
27import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
28import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
29import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.AlarmManager;
32import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070033import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080034import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.BroadcastReceiver;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.pm.PackageManager;
41import android.net.wifi.IWifiManager;
42import android.net.wifi.WifiInfo;
43import android.net.wifi.WifiManager;
44import android.net.wifi.WifiNative;
45import android.net.wifi.WifiStateTracker;
46import android.net.wifi.ScanResult;
47import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070048import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080049import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080050import android.net.ConnectivityManager;
51import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.NetworkStateTracker;
53import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040054import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
56import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080059import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.Looper;
61import android.os.Message;
62import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070063import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070065import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070066import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080068import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.text.TextUtils;
70
71import java.util.ArrayList;
72import java.util.BitSet;
73import java.util.HashMap;
74import java.util.LinkedHashMap;
75import java.util.List;
76import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080077import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.util.regex.Pattern;
79import java.io.FileDescriptor;
80import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080081import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
The Android Open Source Project10592532009-03-18 17:39:46 -070083import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080084import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070085import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080086import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088/**
89 * WifiService handles remote WiFi operation requests by implementing
90 * the IWifiManager interface. It also creates a WifiMonitor to listen
91 * for Wifi-related events.
92 *
93 * @hide
94 */
95public class WifiService extends IWifiManager.Stub {
96 private static final String TAG = "WifiService";
97 private static final boolean DBG = false;
98 private static final Pattern scanResultPattern = Pattern.compile("\t+");
99 private final WifiStateTracker mWifiStateTracker;
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700100 /* TODO: fetch a configurable interface */
101 private static final String SOFTAP_IFACE = "wl0.1";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103 private Context mContext;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800104 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
106 private AlarmManager mAlarmManager;
107 private PendingIntent mIdleIntent;
108 private static final int IDLE_REQUEST = 0;
109 private boolean mScreenOff;
110 private boolean mDeviceIdle;
111 private int mPluggedType;
112
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800113 private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
114
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700115 // true if the user enabled Wifi while in airplane mode
116 private boolean mAirplaneModeOverwridden;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700119 // some wifi lock statistics
Irfan Sheriff8c11e952010-08-12 20:26:23 -0700120 private int mFullHighPerfLocksAcquired;
121 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700122 private int mFullLocksAcquired;
123 private int mFullLocksReleased;
124 private int mScanLocksAcquired;
125 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700126
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700127 private final List<Multicaster> mMulticasters =
128 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700129 private int mMulticastEnabled;
130 private int mMulticastDisabled;
131
The Android Open Source Project10592532009-03-18 17:39:46 -0700132 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800133
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800134 private INetworkManagementService nwService;
135 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800136 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800137 private String[] mWifiRegexs;
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800140 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
141 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 * the approximate point at which the battery drain caused by Wi-Fi
143 * being enabled but not active exceeds the battery drain caused by
144 * re-establishing a connection to the mobile data network.
145 */
146 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
147
Dianne Hackbornc8314b02010-09-20 11:34:11 -0700148 private static final String WAKELOCK_TAG = "*wifi*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 /**
151 * The maximum amount of time to hold the wake lock after a disconnect
152 * caused by stopping the driver. Establishing an EDGE connection has been
153 * observed to take about 5 seconds under normal circumstances. This
154 * provides a bit of extra margin.
155 * <p>
156 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
157 * This is the default value if a Settings.Secure value is not present.
158 */
159 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
160
161 // Wake lock used by driver-stop operation
162 private static PowerManager.WakeLock sDriverStopWakeLock;
163 // Wake lock used by other operations
164 private static PowerManager.WakeLock sWakeLock;
165
Irfan Sheriff59610c02010-03-30 11:00:41 -0700166 private static final int MESSAGE_ENABLE_WIFI = 0;
167 private static final int MESSAGE_DISABLE_WIFI = 1;
168 private static final int MESSAGE_STOP_WIFI = 2;
169 private static final int MESSAGE_START_WIFI = 3;
170 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
171 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800172 private static final int MESSAGE_START_ACCESS_POINT = 6;
173 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
Irfan Sheriff59610c02010-03-30 11:00:41 -0700174 private static final int MESSAGE_SET_CHANNELS = 8;
Irfan Sherifffae66c32010-08-16 11:36:41 -0700175 private static final int MESSAGE_ENABLE_NETWORKS = 9;
Irfan Sheriff0859b762010-09-06 15:34:50 -0700176 private static final int MESSAGE_START_SCAN = 10;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179 private final WifiHandler mWifiHandler;
180
181 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 * Cache of scan results objects (size is somewhat arbitrary)
183 */
184 private static final int SCAN_RESULT_CACHE_SIZE = 80;
185 private final LinkedHashMap<String, ScanResult> mScanResultCache;
186
187 /*
188 * Character buffer used to parse scan results (optimization)
189 */
190 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private boolean mNeedReconfig;
192
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700193 /**
194 * Temporary for computing UIDS that are responsible for starting WIFI.
195 * Protected by mWifiStateTracker lock.
196 */
197 private final WorkSource mTmpWorkSource = new WorkSource();
198
Dianne Hackborn617f8772009-03-31 15:04:46 -0700199 /*
200 * Last UID that asked to enable WIFI.
201 */
202 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800203
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700204 /*
205 * Last UID that asked to enable WIFI AP.
206 */
207 private int mLastApEnableUid = Process.myUid();
208
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 /**
211 * Number of allowed radio frequency channels in various regulatory domains.
212 * This list is sufficient for 802.11b/g networks (2.4GHz range).
213 */
214 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
215
216 private static final String ACTION_DEVICE_IDLE =
217 "com.android.server.WifiManager.action.DEVICE_IDLE";
218
219 WifiService(Context context, WifiStateTracker tracker) {
220 mContext = context;
221 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400222 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700223 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800224
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800225 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
226 nwService = INetworkManagementService.Stub.asInterface(b);
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 mScanResultCache = new LinkedHashMap<String, ScanResult>(
229 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
230 /*
231 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
232 * elements
233 */
234 public boolean removeEldestEntry(Map.Entry eldest) {
235 return SCAN_RESULT_CACHE_SIZE < this.size();
236 }
237 };
238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 HandlerThread wifiThread = new HandlerThread("WifiService");
240 wifiThread.start();
241 mWifiHandler = new WifiHandler(wifiThread.getLooper());
242
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800243 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800244 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
246 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
247 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
248 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
249
250 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
251 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
252 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 mContext.registerReceiver(
255 new BroadcastReceiver() {
256 @Override
257 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700258 // clear our flag indicating the user has overwridden airplane mode
259 mAirplaneModeOverwridden = false;
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700260 // on airplane disable, restore Wifi if the saved state indicates so
261 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
262 persistWifiEnabled(true);
263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 updateWifiState();
265 }
266 },
267 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
268
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800269 mContext.registerReceiver(
270 new BroadcastReceiver() {
271 @Override
272 public void onReceive(Context context, Intent intent) {
273
274 ArrayList<String> available = intent.getStringArrayListExtra(
275 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
276 ArrayList<String> active = intent.getStringArrayListExtra(
277 ConnectivityManager.EXTRA_ACTIVE_TETHER);
278 updateTetherState(available, active);
279
280 }
281 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800282 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800283
Irfan Sheriff7b009782010-03-11 16:37:45 -0800284 /**
285 * Check if Wi-Fi needs to be enabled and start
286 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700287 *
288 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800289 */
290 public void startWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700291 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700292 boolean wifiEnabled = !isAirplaneModeOn()
293 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800294 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
295 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700296 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800297 }
298
299 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
300
301 boolean wifiTethered = false;
302 boolean wifiAvailable = false;
303
304 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
305 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
306
307 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
308 mWifiRegexs = mCm.getTetherableWifiRegexs();
309
310 for (String intf : available) {
311 for (String regex : mWifiRegexs) {
312 if (intf.matches(regex)) {
313
314 InterfaceConfiguration ifcg = null;
315 try {
316 ifcg = service.getInterfaceConfig(intf);
317 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700318 /* IP/netmask: 192.168.43.1/255.255.255.0 */
319 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800320 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
321 ifcg.interfaceFlags = "up";
322
323 service.setInterfaceConfig(intf, ifcg);
324 }
325 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800326 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriff1a543012010-03-17 19:46:32 -0700327 try {
328 nwService.stopAccessPoint();
329 } catch (Exception ee) {
330 Slog.e(TAG, "Could not stop AP, :" + ee);
331 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800332 setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800333 return;
334 }
335
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800336 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800337 Slog.e(TAG, "Error tethering "+intf);
338 }
339 break;
340 }
341 }
342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700345 private boolean testAndClearWifiSavedState() {
346 final ContentResolver cr = mContext.getContentResolver();
347 int wifiSavedState = 0;
348 try {
349 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
350 if(wifiSavedState == 1)
351 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
352 } catch (Settings.SettingNotFoundException e) {
353 ;
354 }
355 return (wifiSavedState == 1);
356 }
357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 private boolean getPersistedWifiEnabled() {
359 final ContentResolver cr = mContext.getContentResolver();
360 try {
361 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
362 } catch (Settings.SettingNotFoundException e) {
363 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
364 return false;
365 }
366 }
367
368 private void persistWifiEnabled(boolean enabled) {
369 final ContentResolver cr = mContext.getContentResolver();
370 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
371 }
372
373 NetworkStateTracker getNetworkStateTracker() {
374 return mWifiStateTracker;
375 }
376
377 /**
378 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
379 * @return {@code true} if the operation succeeds
380 */
381 public boolean pingSupplicant() {
382 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800383
384 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386
387 /**
388 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 */
Irfan Sheriff0859b762010-09-06 15:34:50 -0700390 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 enforceChangePermission();
Irfan Sheriff0859b762010-09-06 15:34:50 -0700392 if (mWifiHandler == null) return;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800393
Irfan Sheriff0859b762010-09-06 15:34:50 -0700394 Message.obtain(mWifiHandler, MESSAGE_START_SCAN, forceActive ? 1 : 0, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
396
397 /**
398 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
399 * @param enable {@code true} to enable, {@code false} to disable.
400 * @return {@code true} if the enable/disable operation was
401 * started or is already in the queue.
402 */
403 public boolean setWifiEnabled(boolean enable) {
404 enforceChangePermission();
405 if (mWifiHandler == null) return false;
406
407 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700408 // caller may not have WAKE_LOCK permission - it's not required here
409 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700411 Binder.restoreCallingIdentity(ident);
412
Dianne Hackborn617f8772009-03-31 15:04:46 -0700413 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700414 // set a flag if the user is enabling Wifi while in airplane mode
415 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700416 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
418
419 return true;
420 }
421
422 /**
423 * Enables/disables Wi-Fi synchronously.
424 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
425 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700426 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 * @return {@code true} if the operation succeeds (or if the existing state
428 * is the same as the requested state)
429 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700430 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800432 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800434 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 return true;
436 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700437 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 return false;
439 }
440
Irfan Sheriffcd770372010-01-08 09:36:04 -0800441 /**
442 * Multiple calls to unregisterReceiver() cause exception and a system crash.
443 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
444 * disable wifi at the same time.
445 * Avoid doing a disable when the current Wifi state is UNKNOWN
446 * TODO: Handle driver load fail and supplicant lost as seperate states
447 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800448 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800449 return false;
450 }
451
Irfan Sherifff91444c2010-03-24 12:11:00 -0700452 /**
453 * Fail Wifi if AP is enabled
454 * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
455 * WIFI_STATE_FAILED
456 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800457 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
Irfan Sherifff91444c2010-03-24 12:11:00 -0700458 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
459 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800460 }
461
Irfan Sherifff91444c2010-03-24 12:11:00 -0700462 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800465 if (!mWifiStateTracker.loadDriver()) {
466 Slog.e(TAG, "Failed to load Wi-Fi driver.");
467 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
468 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800470 if (!mWifiStateTracker.startSupplicant()) {
471 mWifiStateTracker.unloadDriver();
472 Slog.e(TAG, "Failed to start supplicant daemon.");
473 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
474 return false;
475 }
476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 registerForBroadcasts();
478 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 } else {
481
482 mContext.unregisterReceiver(mReceiver);
483 // Remove notification (it will no-op if it isn't visible)
484 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
485
486 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800487
488 if (!mWifiStateTracker.stopSupplicant()) {
489 Slog.e(TAG, "Failed to stop supplicant daemon.");
490 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
491 failedToStopSupplicantOrUnloadDriver = true;
492 }
493
494 /**
495 * Reset connections and disable interface
496 * before we unload the driver
497 */
498 mWifiStateTracker.resetConnections(true);
499
500 if (!mWifiStateTracker.unloadDriver()) {
501 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
502 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700503 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 failedToStopSupplicantOrUnloadDriver = true;
505 }
506 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 if (failedToStopSupplicantOrUnloadDriver) {
509 return false;
510 }
511 }
512
513 // Success!
514
515 if (persist) {
516 persistWifiEnabled(enable);
517 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700518 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 return true;
520 }
521
Dianne Hackborn617f8772009-03-31 15:04:46 -0700522 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800523 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
The Android Open Source Project10592532009-03-18 17:39:46 -0700525 long ident = Binder.clearCallingIdentity();
526 try {
527 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700528 mBatteryStats.noteWifiOn();
The Android Open Source Project10592532009-03-18 17:39:46 -0700529 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700530 mBatteryStats.noteWifiOff();
The Android Open Source Project10592532009-03-18 17:39:46 -0700531 }
532 } catch (RemoteException e) {
533 } finally {
534 Binder.restoreCallingIdentity(ident);
535 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800538 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539
540 // Broadcast
541 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
542 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
543 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
544 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
545 mContext.sendStickyBroadcast(intent);
546 }
547
548 private void enforceAccessPermission() {
549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
550 "WifiService");
551 }
552
553 private void enforceChangePermission() {
554 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
555 "WifiService");
556
557 }
558
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700559 private void enforceMulticastChangePermission() {
560 mContext.enforceCallingOrSelfPermission(
561 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
562 "WifiService");
563 }
564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 /**
566 * see {@link WifiManager#getWifiState()}
567 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
568 * {@link WifiManager#WIFI_STATE_DISABLING},
569 * {@link WifiManager#WIFI_STATE_ENABLED},
570 * {@link WifiManager#WIFI_STATE_ENABLING},
571 * {@link WifiManager#WIFI_STATE_UNKNOWN}
572 */
573 public int getWifiEnabledState() {
574 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800575 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577
578 /**
579 * see {@link android.net.wifi.WifiManager#disconnect()}
580 * @return {@code true} if the operation succeeds
581 */
582 public boolean disconnect() {
583 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800584
585 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
587
588 /**
589 * see {@link android.net.wifi.WifiManager#reconnect()}
590 * @return {@code true} if the operation succeeds
591 */
592 public boolean reconnect() {
593 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800594
595 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597
598 /**
599 * see {@link android.net.wifi.WifiManager#reassociate()}
600 * @return {@code true} if the operation succeeds
601 */
602 public boolean reassociate() {
603 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800604
605 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800608 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700609 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800610 * @param wifiConfig SSID, security and channel details as
611 * part of WifiConfiguration
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700612 * @param enabled, true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800613 * @return {@code true} if the start operation was
614 * started or is already in the queue.
615 */
616 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
617 enforceChangePermission();
618 if (mWifiHandler == null) return false;
619
620 synchronized (mWifiHandler) {
621
622 long ident = Binder.clearCallingIdentity();
623 sWakeLock.acquire();
624 Binder.restoreCallingIdentity(ident);
625
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700626 mLastApEnableUid = Binder.getCallingUid();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800627 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
628 }
629
630 return true;
631 }
632
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800633 public WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700634 enforceAccessPermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800635 final ContentResolver cr = mContext.getContentResolver();
636 WifiConfiguration wifiConfig = new WifiConfiguration();
637 int authType;
638 try {
639 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
640 if (wifiConfig.SSID == null)
641 return null;
642 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
643 wifiConfig.allowedKeyManagement.set(authType);
644 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
645 return wifiConfig;
646 } catch (Settings.SettingNotFoundException e) {
647 Slog.e(TAG,"AP settings not found, returning");
648 return null;
649 }
650 }
651
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700652 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
653 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800654 final ContentResolver cr = mContext.getContentResolver();
655 boolean isWpa;
656 if (wifiConfig == null)
657 return;
658 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
659 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
660 Settings.Secure.putInt(cr,
661 Settings.Secure.WIFI_AP_SECURITY,
662 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
663 if (isWpa)
664 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
665 }
666
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800667 /**
668 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
669 * and soft access point configured as a single operation.
670 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800671 * @param uid The UID of the process making the request.
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800672 * @param wifiConfig The WifiConfiguration for AP
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800673 * @return {@code true} if the operation succeeds (or if the existing state
674 * is the same as the requested state)
675 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800676 private boolean setWifiApEnabledBlocking(boolean enable,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800677 int uid, WifiConfiguration wifiConfig) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800678 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
679
680 if (mWifiApState == eventualWifiApState) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800681 /* Configuration changed on a running access point */
682 if(enable && (wifiConfig != null)) {
683 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700684 nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
685 SOFTAP_IFACE);
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700686 setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800687 return true;
688 } catch(Exception e) {
689 Slog.e(TAG, "Exception in nwService during AP restart");
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700690 try {
691 nwService.stopAccessPoint();
692 } catch (Exception ee) {
693 Slog.e(TAG, "Could not stop AP, :" + ee);
694 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800695 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
696 return false;
697 }
698 } else {
699 return true;
700 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800701 }
702
Irfan Sherifff91444c2010-03-24 12:11:00 -0700703 /**
704 * Fail AP if Wifi is enabled
705 */
706 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
707 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
708 return false;
709 }
710
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800711 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
712 WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800713
714 if (enable) {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800715
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800716 /* Use default config if there is no existing config */
717 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
718 wifiConfig = new WifiConfiguration();
719 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
720 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
721 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800722
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800723 if (!mWifiStateTracker.loadDriver()) {
724 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800725 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800726 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800727 }
728
729 try {
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700730 nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
731 SOFTAP_IFACE);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800732 } catch(Exception e) {
733 Slog.e(TAG, "Exception in startAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800734 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
735 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800736 }
737
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700738 setWifiApConfiguration(wifiConfig);
Irfan Sheriffafadc8b2010-06-11 14:43:14 -0700739
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800740 } else {
741
742 try {
743 nwService.stopAccessPoint();
744 } catch(Exception e) {
745 Slog.e(TAG, "Exception in stopAccessPoint()");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800746 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
747 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800748 }
749
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800750 if (!mWifiStateTracker.unloadDriver()) {
751 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800752 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800753 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800754 }
755 }
756
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800757 setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800758 return true;
759 }
760
761 /**
762 * see {@link WifiManager#getWifiApState()}
763 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
764 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
765 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
766 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
767 * {@link WifiManager#WIFI_AP_STATE_FAILED}
768 */
769 public int getWifiApEnabledState() {
770 enforceAccessPermission();
771 return mWifiApState;
772 }
773
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800774 private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800775 final int previousWifiApState = mWifiApState;
776
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800777 /**
778 * Unload the driver if going to a failed state
779 */
780 if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
781 mWifiStateTracker.unloadDriver();
782 }
783
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800784 long ident = Binder.clearCallingIdentity();
785 try {
786 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700787 mBatteryStats.noteWifiOn();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800788 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700789 mBatteryStats.noteWifiOff();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800790 }
791 } catch (RemoteException e) {
792 } finally {
793 Binder.restoreCallingIdentity(ident);
794 }
795
796 // Update state
797 mWifiApState = wifiAPState;
798
799 // Broadcast
800 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
801 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
802 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
803 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
804 mContext.sendStickyBroadcast(intent);
805 }
806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 /**
808 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
809 * @return the list of configured networks
810 */
811 public List<WifiConfiguration> getConfiguredNetworks() {
812 enforceAccessPermission();
813 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 /*
816 * We don't cache the list, because we want to allow
817 * for the possibility that the configuration file
818 * has been modified through some external means,
819 * such as the wpa_cli command line program.
820 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800821 listStr = mWifiStateTracker.listNetworks();
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 List<WifiConfiguration> networks =
824 new ArrayList<WifiConfiguration>();
825 if (listStr == null)
826 return networks;
827
828 String[] lines = listStr.split("\n");
829 // Skip the first line, which is a header
830 for (int i = 1; i < lines.length; i++) {
831 String[] result = lines[i].split("\t");
832 // network-id | ssid | bssid | flags
833 WifiConfiguration config = new WifiConfiguration();
834 try {
835 config.networkId = Integer.parseInt(result[0]);
836 } catch(NumberFormatException e) {
837 continue;
838 }
839 if (result.length > 3) {
840 if (result[3].indexOf("[CURRENT]") != -1)
841 config.status = WifiConfiguration.Status.CURRENT;
842 else if (result[3].indexOf("[DISABLED]") != -1)
843 config.status = WifiConfiguration.Status.DISABLED;
844 else
845 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800846 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800849 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 networks.add(config);
851 }
852
853 return networks;
854 }
855
856 /**
857 * Read the variables from the supplicant daemon that are needed to
858 * fill in the WifiConfiguration object.
859 * <p/>
860 * The caller must hold the synchronization monitor.
861 * @param config the {@link WifiConfiguration} object to be filled in.
862 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800863 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864
865 int netId = config.networkId;
866 if (netId < 0)
867 return;
868
869 /*
870 * TODO: maybe should have a native method that takes an array of
871 * variable names and returns an array of values. But we'd still
872 * be doing a round trip to the supplicant daemon for each variable.
873 */
874 String value;
875
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800876 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 if (!TextUtils.isEmpty(value)) {
Chung-yih Wang047076d2010-05-15 11:03:30 +0800878 config.SSID = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 } else {
880 config.SSID = null;
881 }
882
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800883 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (!TextUtils.isEmpty(value)) {
885 config.BSSID = value;
886 } else {
887 config.BSSID = null;
888 }
889
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800890 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 config.priority = -1;
892 if (!TextUtils.isEmpty(value)) {
893 try {
894 config.priority = Integer.parseInt(value);
895 } catch (NumberFormatException ignore) {
896 }
897 }
898
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800899 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 config.hiddenSSID = false;
901 if (!TextUtils.isEmpty(value)) {
902 try {
903 config.hiddenSSID = Integer.parseInt(value) != 0;
904 } catch (NumberFormatException ignore) {
905 }
906 }
907
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800908 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 config.wepTxKeyIndex = -1;
910 if (!TextUtils.isEmpty(value)) {
911 try {
912 config.wepTxKeyIndex = Integer.parseInt(value);
913 } catch (NumberFormatException ignore) {
914 }
915 }
916
917 /*
918 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
919 * just a "*" if the key is set, or the null string otherwise.
920 */
921 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800922 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 if (!TextUtils.isEmpty(value)) {
924 config.wepKeys[i] = value;
925 } else {
926 config.wepKeys[i] = null;
927 }
928 }
929
930 /*
931 * Get the private shared key. Note that the actual keys are not passed back,
932 * just a "*" if the key is set, or the null string otherwise.
933 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800934 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 if (!TextUtils.isEmpty(value)) {
936 config.preSharedKey = value;
937 } else {
938 config.preSharedKey = null;
939 }
940
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800941 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 WifiConfiguration.Protocol.varName);
943 if (!TextUtils.isEmpty(value)) {
944 String vals[] = value.split(" ");
945 for (String val : vals) {
946 int index =
947 lookupString(val, WifiConfiguration.Protocol.strings);
948 if (0 <= index) {
949 config.allowedProtocols.set(index);
950 }
951 }
952 }
953
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800954 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 WifiConfiguration.KeyMgmt.varName);
956 if (!TextUtils.isEmpty(value)) {
957 String vals[] = value.split(" ");
958 for (String val : vals) {
959 int index =
960 lookupString(val, WifiConfiguration.KeyMgmt.strings);
961 if (0 <= index) {
962 config.allowedKeyManagement.set(index);
963 }
964 }
965 }
966
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800967 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 WifiConfiguration.AuthAlgorithm.varName);
969 if (!TextUtils.isEmpty(value)) {
970 String vals[] = value.split(" ");
971 for (String val : vals) {
972 int index =
973 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
974 if (0 <= index) {
975 config.allowedAuthAlgorithms.set(index);
976 }
977 }
978 }
979
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800980 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 WifiConfiguration.PairwiseCipher.varName);
982 if (!TextUtils.isEmpty(value)) {
983 String vals[] = value.split(" ");
984 for (String val : vals) {
985 int index =
986 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
987 if (0 <= index) {
988 config.allowedPairwiseCiphers.set(index);
989 }
990 }
991 }
992
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800993 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 WifiConfiguration.GroupCipher.varName);
995 if (!TextUtils.isEmpty(value)) {
996 String vals[] = value.split(" ");
997 for (String val : vals) {
998 int index =
999 lookupString(val, WifiConfiguration.GroupCipher.strings);
1000 if (0 <= index) {
1001 config.allowedGroupCiphers.set(index);
1002 }
1003 }
1004 }
Chung-yih Wang43374762009-09-16 14:28:42 +08001005
1006 for (WifiConfiguration.EnterpriseField field :
1007 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001008 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +08001009 field.varName());
1010 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001011 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001012 field.setValue(value);
1013 }
1014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001017 private static String removeDoubleQuotes(String string) {
1018 if (string.length() <= 2) return "";
1019 return string.substring(1, string.length() - 1);
1020 }
1021
1022 private static String convertToQuotedString(String string) {
1023 return "\"" + string + "\"";
1024 }
1025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 /**
1027 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1028 * @return the supplicant-assigned identifier for the new or updated
1029 * network if the operation succeeds, or {@code -1} if it fails
1030 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001031 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 /*
1035 * If the supplied networkId is -1, we create a new empty
1036 * network configuration. Otherwise, the networkId should
1037 * refer to an existing configuration.
1038 */
1039 int netId = config.networkId;
1040 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -07001041 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001043 synchronized (mWifiStateTracker) {
1044 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001045 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001046 if (netId < 0) {
1047 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001048 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001049 }
1050 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001052 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001054 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001057 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 /*
1059 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001060 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 * will fail, so we don't bother to make a separate check
1062 * for the validity of the ID up front.
1063 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001065 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001066 netId,
1067 WifiConfiguration.ssidVarName,
Chung-yih Wang047076d2010-05-15 11:03:30 +08001068 config.SSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001070 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072 break setVariables;
1073 }
1074
1075 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001076 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001077 netId,
1078 WifiConfiguration.bssidVarName,
1079 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001081 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
1083 break setVariables;
1084 }
1085
1086 String allowedKeyManagementString =
1087 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1088 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001089 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001090 netId,
1091 WifiConfiguration.KeyMgmt.varName,
1092 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001094 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001095 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
1097 break setVariables;
1098 }
1099
1100 String allowedProtocolsString =
1101 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1102 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001103 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001104 netId,
1105 WifiConfiguration.Protocol.varName,
1106 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001109 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
1111 break setVariables;
1112 }
1113
1114 String allowedAuthAlgorithmsString =
1115 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1116 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001117 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001118 netId,
1119 WifiConfiguration.AuthAlgorithm.varName,
1120 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001122 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001123 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125 break setVariables;
1126 }
1127
1128 String allowedPairwiseCiphersString =
1129 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1130 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001131 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001132 netId,
1133 WifiConfiguration.PairwiseCipher.varName,
1134 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001136 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001137 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 break setVariables;
1140 }
1141
1142 String allowedGroupCiphersString =
1143 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1144 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001145 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001146 netId,
1147 WifiConfiguration.GroupCipher.varName,
1148 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001150 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001151 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153 break setVariables;
1154 }
1155
1156 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1157 // by preventing "*" as a key.
1158 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001159 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001160 netId,
1161 WifiConfiguration.pskVarName,
1162 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001164 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166 break setVariables;
1167 }
1168
1169 boolean hasSetKey = false;
1170 if (config.wepKeys != null) {
1171 for (int i = 0; i < config.wepKeys.length; i++) {
1172 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1173 // by preventing "*" as a key.
1174 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001175 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001176 netId,
1177 WifiConfiguration.wepKeyVarNames[i],
1178 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001180 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001181 "failed to set wep_key"+i+": " +
1182 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 break setVariables;
1185 }
1186 hasSetKey = true;
1187 }
1188 }
1189 }
1190
1191 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001192 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001193 netId,
1194 WifiConfiguration.wepTxKeyIdxVarName,
1195 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001197 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001198 "failed to set wep_tx_keyidx: "+
1199 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201 break setVariables;
1202 }
1203 }
1204
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001205 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001206 netId,
1207 WifiConfiguration.priorityVarName,
1208 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001210 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001211 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
1213 break setVariables;
1214 }
1215
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001216 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001217 netId,
1218 WifiConfiguration.hiddenSSIDVarName,
1219 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001221 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001222 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224 break setVariables;
1225 }
1226
Chung-yih Wang43374762009-09-16 14:28:42 +08001227 for (WifiConfiguration.EnterpriseField field
1228 : config.enterpriseFields) {
1229 String varName = field.varName();
1230 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001231 if (value != null) {
1232 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001233 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001234 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001235 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001236 netId,
1237 varName,
1238 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001239 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001240 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001241 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001242 }
1243 break setVariables;
1244 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001245 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001250 /*
1251 * For an update, if one of the setNetworkVariable operations fails,
1252 * we might want to roll back all the changes already made. But the
1253 * chances are that if anything is going to go wrong, it'll happen
1254 * the first time we try to set one of the variables.
1255 */
1256 if (newNetwork) {
1257 removeNetwork(netId);
1258 if (DBG) {
1259 Slog.d(TAG,
1260 "Failed to set a network variable, removed network: "
1261 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
1263 }
1264 return -1;
1265 }
1266
1267 private static String makeString(BitSet set, String[] strings) {
1268 StringBuffer buf = new StringBuffer();
1269 int nextSetBit = -1;
1270
1271 /* Make sure all set bits are in [0, strings.length) to avoid
1272 * going out of bounds on strings. (Shouldn't happen, but...) */
1273 set = set.get(0, strings.length);
1274
1275 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1276 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1277 }
1278
1279 // remove trailing space
1280 if (set.cardinality() > 0) {
1281 buf.setLength(buf.length() - 1);
1282 }
1283
1284 return buf.toString();
1285 }
1286
1287 private static int lookupString(String string, String[] strings) {
1288 int size = strings.length;
1289
1290 string = string.replace('-', '_');
1291
1292 for (int i = 0; i < size; i++)
1293 if (string.equals(strings[i]))
1294 return i;
1295
1296 if (DBG) {
1297 // if we ever get here, we should probably add the
1298 // value to WifiConfiguration to reflect that it's
1299 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302
1303 return -1;
1304 }
1305
1306 /**
1307 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1308 * @param netId the integer that identifies the network configuration
1309 * to the supplicant
1310 * @return {@code true} if the operation succeeded
1311 */
1312 public boolean removeNetwork(int netId) {
1313 enforceChangePermission();
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 return mWifiStateTracker.removeNetwork(netId);
1316 }
1317
1318 /**
1319 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1320 * @param netId the integer that identifies the network configuration
1321 * to the supplicant
1322 * @param disableOthers if true, disable all other networks.
1323 * @return {@code true} if the operation succeeded
1324 */
1325 public boolean enableNetwork(int netId, boolean disableOthers) {
1326 enforceChangePermission();
1327
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001328 String ifname = mWifiStateTracker.getInterfaceName();
1329 NetworkUtils.enableInterface(ifname);
1330 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1331 if (!result) {
1332 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001334 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336
1337 /**
1338 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1339 * @param netId the integer that identifies the network configuration
1340 * to the supplicant
1341 * @return {@code true} if the operation succeeded
1342 */
1343 public boolean disableNetwork(int netId) {
1344 enforceChangePermission();
1345
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001346 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348
1349 /**
1350 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1351 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1352 */
1353 public WifiInfo getConnectionInfo() {
1354 enforceAccessPermission();
1355 /*
1356 * Make sure we have the latest information, by sending
1357 * a status request to the supplicant.
1358 */
1359 return mWifiStateTracker.requestConnectionInfo();
1360 }
1361
1362 /**
1363 * Return the results of the most recent access point scan, in the form of
1364 * a list of {@link ScanResult} objects.
1365 * @return the list of results
1366 */
1367 public List<ScanResult> getScanResults() {
1368 enforceAccessPermission();
1369 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001370
1371 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (reply == null) {
1373 return null;
1374 }
1375
1376 List<ScanResult> scanList = new ArrayList<ScanResult>();
1377
1378 int lineCount = 0;
1379
1380 int replyLen = reply.length();
1381 // Parse the result string, keeping in mind that the last line does
1382 // not end with a newline.
1383 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1384 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1385 ++lineCount;
1386 /*
1387 * Skip the first line, which is a header
1388 */
1389 if (lineCount == 1) {
1390 lineBeg = lineEnd + 1;
1391 continue;
1392 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001393 if (lineEnd > lineBeg) {
1394 String line = reply.substring(lineBeg, lineEnd);
1395 ScanResult scanResult = parseScanResult(line);
1396 if (scanResult != null) {
1397 scanList.add(scanResult);
1398 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001399 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 }
1402 lineBeg = lineEnd + 1;
1403 }
1404 }
1405 mWifiStateTracker.setScanResultsList(scanList);
1406 return scanList;
1407 }
1408
1409 /**
1410 * Parse the scan result line passed to us by wpa_supplicant (helper).
1411 * @param line the line to parse
1412 * @return the {@link ScanResult} object
1413 */
1414 private ScanResult parseScanResult(String line) {
1415 ScanResult scanResult = null;
1416 if (line != null) {
1417 /*
1418 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1419 * must synchronized here!
1420 */
1421 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001422 String[] result = scanResultPattern.split(line);
1423 if (3 <= result.length && result.length <= 5) {
1424 String bssid = result[0];
1425 // bssid | frequency | level | flags | ssid
1426 int frequency;
1427 int level;
1428 try {
1429 frequency = Integer.parseInt(result[1]);
1430 level = Integer.parseInt(result[2]);
1431 /* some implementations avoid negative values by adding 256
1432 * so we need to adjust for that here.
1433 */
1434 if (level > 0) level -= 256;
1435 } catch (NumberFormatException e) {
1436 frequency = 0;
1437 level = 0;
1438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439
Mike Lockwood1a645052009-06-25 13:01:12 -04001440 /*
1441 * The formatting of the results returned by
1442 * wpa_supplicant is intended to make the fields
1443 * line up nicely when printed,
1444 * not to make them easy to parse. So we have to
1445 * apply some heuristics to figure out which field
1446 * is the SSID and which field is the flags.
1447 */
1448 String ssid;
1449 String flags;
1450 if (result.length == 4) {
1451 if (result[3].charAt(0) == '[') {
1452 flags = result[3];
1453 ssid = "";
1454 } else {
1455 flags = "";
1456 ssid = result[3];
1457 }
1458 } else if (result.length == 5) {
1459 flags = result[3];
1460 ssid = result[4];
1461 } else {
1462 // Here, we must have 3 fields: no flags and ssid
1463 // set
1464 flags = "";
1465 ssid = "";
1466 }
1467
Mike Lockwood00717e22009-08-17 10:09:36 -04001468 // bssid + ssid is the hash key
1469 String key = bssid + ssid;
1470 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001471 if (scanResult != null) {
1472 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001473 scanResult.SSID = ssid;
1474 scanResult.capabilities = flags;
1475 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001476 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 // Do not add scan results that have no SSID set
1478 if (0 < ssid.trim().length()) {
1479 scanResult =
1480 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001481 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001482 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001485 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001486 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001487 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489 }
1490 }
1491
1492 return scanResult;
1493 }
1494
1495 /**
1496 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1497 * and construct a {@code WifiConfiguration} that describes the encryption,
1498 * key management, and authenticaion capabilities of the access point.
1499 * @param flags the string returned by wpa_supplicant
1500 * @return the {@link WifiConfiguration} object, filled in
1501 */
1502 WifiConfiguration parseScanFlags(String flags) {
1503 WifiConfiguration config = new WifiConfiguration();
1504
1505 if (flags.length() == 0) {
1506 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1507 }
1508 // ... to be implemented
1509 return config;
1510 }
1511
1512 /**
1513 * Tell the supplicant to persist the current list of configured networks.
1514 * @return {@code true} if the operation succeeded
1515 */
1516 public boolean saveConfiguration() {
1517 boolean result;
1518 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001521 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 if (result && mNeedReconfig) {
1523 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001524 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525
1526 if (result) {
1527 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1528 mContext.sendBroadcast(intent);
1529 }
1530 }
1531 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001532 // Inform the backup manager about a data change
1533 IBackupManager ibm = IBackupManager.Stub.asInterface(
1534 ServiceManager.getService(Context.BACKUP_SERVICE));
1535 if (ibm != null) {
1536 try {
1537 ibm.dataChanged("com.android.providers.settings");
1538 } catch (Exception e) {
1539 // Try again later
1540 }
1541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 return result;
1543 }
1544
1545 /**
1546 * Set the number of radio frequency channels that are allowed to be used
1547 * in the current regulatory domain. This method should be used only
1548 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001549 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 * persisted as a Secure setting.
1551 * @param numChannels the number of allowed channels. Must be greater than 0
1552 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001553 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1555 * {@code numChannels} is outside the valid range.
1556 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001557 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001558 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001559 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 /*
1563 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1564 * but if Wi-Fi isn't currently enabled, that's not possible, and
1565 * we want to persist the setting anyway,so that it will take
1566 * effect when Wi-Fi does become enabled.
1567 */
1568 boolean found = false;
1569 for (int validChan : sValidRegulatoryChannelCounts) {
1570 if (validChan == numChannels) {
1571 found = true;
1572 break;
1573 }
1574 }
1575 if (!found) {
1576 return false;
1577 }
1578
Irfan Sheriff59610c02010-03-30 11:00:41 -07001579 if (mWifiHandler == null) return false;
1580
1581 Message.obtain(mWifiHandler,
1582 MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
1583
1584 return true;
1585 }
1586
1587 /**
1588 * sets the number of allowed radio frequency channels synchronously
1589 * @param numChannels the number of allowed channels. Must be greater than 0
1590 * and less than or equal to 16.
1591 * @param persist {@code true} if the setting should be remembered.
1592 * @return {@code true} if the operation succeeds, {@code false} otherwise
1593 */
1594 private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001595 if (persist) {
1596 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -07001597 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1598 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001599 }
Irfan Sheriff59610c02010-03-30 11:00:41 -07001600 return mWifiStateTracker.setNumAllowedChannels(numChannels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602
1603 /**
1604 * Return the number of frequency channels that are allowed
1605 * to be used in the current regulatory domain.
1606 * @return the number of allowed channels, or {@code -1} if an error occurs
1607 */
1608 public int getNumAllowedChannels() {
1609 int numChannels;
1610
1611 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001612
1613 /*
1614 * If we can't get the value from the driver (e.g., because
1615 * Wi-Fi is not currently enabled), get the value from
1616 * Settings.
1617 */
1618 numChannels = mWifiStateTracker.getNumAllowedChannels();
1619 if (numChannels < 0) {
1620 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1621 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1622 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 return numChannels;
1625 }
1626
1627 /**
1628 * Return the list of valid values for the number of allowed radio channels
1629 * for various regulatory domains.
1630 * @return the list of channel counts
1631 */
1632 public int[] getValidChannelCounts() {
1633 enforceAccessPermission();
1634 return sValidRegulatoryChannelCounts;
1635 }
1636
1637 /**
1638 * Return the DHCP-assigned addresses from the last successful DHCP request,
1639 * if any.
1640 * @return the DHCP information
1641 */
1642 public DhcpInfo getDhcpInfo() {
1643 enforceAccessPermission();
1644 return mWifiStateTracker.getDhcpInfo();
1645 }
1646
1647 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1648 @Override
1649 public void onReceive(Context context, Intent intent) {
1650 String action = intent.getAction();
1651
Doug Zongker43866e02010-01-07 12:09:54 -08001652 long idleMillis =
1653 Settings.Secure.getLong(mContext.getContentResolver(),
1654 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001656 Settings.System.getInt(mContext.getContentResolver(),
1657 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001659 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 mAlarmManager.cancel(mIdleIntent);
1661 mDeviceIdle = false;
1662 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001663 // Once the screen is on, we are not keeping WIFI running
1664 // because of any locks so clear that tracking immediately.
1665 reportStartWorkSource();
Mike Lockwoodf32be162009-07-14 17:44:37 -04001666 mWifiStateTracker.enableRssiPolling(true);
Irfan Sherifffae66c32010-08-16 11:36:41 -07001667 /* DHCP or other temporary failures in the past can prevent
1668 * a disabled network from being connected to, enable on screen on
1669 */
1670 if (mWifiStateTracker.isAnyNetworkDisabled()) {
1671 sendEnableNetworksMessage();
1672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001676 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /*
1678 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1679 * AND the "stay on while plugged in" setting doesn't match the
1680 * current power conditions (i.e, not plugged in, plugged in to USB,
1681 * or plugged in to AC).
1682 */
1683 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001684 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1685 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001686 // we used to go to sleep immediately, but this caused some race conditions
1687 // we don't have time to track down for this release. Delay instead, but not
1688 // as long as we would if connected (below)
1689 // TODO - fix the race conditions and switch back to the immediate turn-off
1690 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001691 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001692 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1693 // // do not keep Wifi awake when screen is off if Wifi is not associated
1694 // mDeviceIdle = true;
1695 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001696 } else {
1697 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001698 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001699 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 /* we can return now -- there's nothing to do until we get the idle intent back */
1703 return;
1704 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001707 reportStartWorkSource();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1709 /*
1710 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1711 * AND we are transitioning from a state in which the device was supposed
1712 * to stay awake to a state in which it is not supposed to stay awake.
1713 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1714 * the already-set timer.
1715 */
1716 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001717 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1719 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1720 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001721 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1723 mPluggedType = pluggedType;
1724 return;
1725 }
1726 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001727 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001728 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1729 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1730 boolean isBluetoothPlaying = false;
1731 for (BluetoothDevice sink : sinks) {
1732 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1733 isBluetoothPlaying = true;
1734 }
1735 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001736 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 } else {
1739 return;
1740 }
1741
1742 updateWifiState();
1743 }
1744
1745 /**
1746 * Determines whether the Wi-Fi chipset should stay awake or be put to
1747 * sleep. Looks at the setting for the sleep policy and the current
1748 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001749 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 * @see #shouldDeviceStayAwake(int, int)
1751 */
1752 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1753 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1754 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1755
1756 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1757 // Never sleep
1758 return true;
1759 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1760 (pluggedType != 0)) {
1761 // Never sleep while plugged, and we're plugged
1762 return true;
1763 } else {
1764 // Default
1765 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1766 }
1767 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 /**
1770 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1771 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1772 * of {@code 0} isn't really a plugged type, but rather an indication that the
1773 * device isn't plugged in at all, there is no bit value corresponding to a
1774 * {@code pluggedType} value of {@code 0}. That is why we shift by
1775 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1776 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1777 * keep the device (and hence Wi-Fi) awake.
1778 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1779 * being made
1780 * @return {@code true} if {@code pluggedType} indicates that the device is
1781 * supposed to stay awake, {@code false} otherwise.
1782 */
1783 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1784 return (stayAwakeConditions & pluggedType) != 0;
1785 }
1786 };
1787
Dianne Hackborn617f8772009-03-31 15:04:46 -07001788 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 Message msg = Message.obtain(mWifiHandler,
1790 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001791 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 msg.sendToTarget();
1793 }
1794
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001795 private void sendStartMessage(int lockMode) {
1796 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, lockMode, 0).sendToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001799 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1800 Message.obtain(mWifiHandler,
1801 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001802 uid, 0, wifiConfig).sendToTarget();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001803 }
1804
Irfan Sherifffae66c32010-08-16 11:36:41 -07001805 private void sendEnableNetworksMessage() {
1806 Message.obtain(mWifiHandler, MESSAGE_ENABLE_NETWORKS).sendToTarget();
1807 }
1808
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001809 private void reportStartWorkSource() {
1810 synchronized (mWifiStateTracker) {
1811 mTmpWorkSource.clear();
1812 if (mDeviceIdle) {
1813 for (int i=0; i<mLocks.mList.size(); i++) {
1814 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
1815 }
1816 }
1817 mWifiStateTracker.updateBatteryWorkSourceLocked(mTmpWorkSource);
Dianne Hackbornc8314b02010-09-20 11:34:11 -07001818 sWakeLock.setWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001819 }
1820 }
1821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001823 // send a message so it's all serialized
1824 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1825 }
1826
1827 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001829 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001830
1831 boolean lockHeld;
1832 synchronized (mLocks) {
1833 lockHeld = mLocks.hasLocks();
1834 }
1835
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001836 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1838 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001839
1840 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001842 }
1843 /* If device is not idle, lockmode cannot be scan only */
1844 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1846 }
1847
1848 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001849 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 return;
1851 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001852
1853 /* Disable tethering when airplane mode is enabled */
1854 if (airplaneMode &&
1855 (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
1856 sWakeLock.acquire();
1857 sendAccessPointMessage(false, null, mLastApEnableUid);
1858 }
1859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 if (wifiShouldBeEnabled) {
1861 if (wifiShouldBeStarted) {
1862 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001863 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 sWakeLock.acquire();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001865 sendStartMessage(strongestLockMode);
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001866 } else if (!mWifiStateTracker.isDriverStopped()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 int wakeLockTimeout =
1868 Settings.Secure.getInt(
1869 mContext.getContentResolver(),
1870 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1871 DEFAULT_WAKELOCK_TIMEOUT);
1872 /*
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001873 * We are assuming that ConnectivityService can make
1874 * a transition to cellular data within wakeLockTimeout time.
1875 * The wakelock is released by the delayed message.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 */
1877 sDriverStopWakeLock.acquire();
1878 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1879 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1880 }
1881 } else {
1882 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001883 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 }
1886 }
1887
1888 private void registerForBroadcasts() {
1889 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1891 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1892 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1893 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001894 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 mContext.registerReceiver(mReceiver, intentFilter);
1896 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 private boolean isAirplaneSensitive() {
1899 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1900 Settings.System.AIRPLANE_MODE_RADIOS);
1901 return airplaneModeRadios == null
1902 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1903 }
1904
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001905 private boolean isAirplaneToggleable() {
1906 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1907 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1908 return toggleableRadios != null
1909 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1910 }
1911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 /**
1913 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1914 * currently on.
1915 * @return {@code true} if airplane mode is on.
1916 */
1917 private boolean isAirplaneModeOn() {
1918 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1919 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1920 }
1921
1922 /**
1923 * Handler that allows posting to the WifiThread.
1924 */
1925 private class WifiHandler extends Handler {
1926 public WifiHandler(Looper looper) {
1927 super(looper);
1928 }
1929
1930 @Override
1931 public void handleMessage(Message msg) {
1932 switch (msg.what) {
1933
1934 case MESSAGE_ENABLE_WIFI:
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001935 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001936 if (mWifiWatchdogService == null) {
1937 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 sWakeLock.release();
1940 break;
1941
1942 case MESSAGE_START_WIFI:
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001943 reportStartWorkSource();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001944 mWifiStateTracker.setScanOnlyMode(msg.arg1 == WifiManager.WIFI_MODE_SCAN_ONLY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 mWifiStateTracker.restart();
Irfan Sheriff8c11e952010-08-12 20:26:23 -07001946 mWifiStateTracker.setHighPerfMode(msg.arg1 ==
1947 WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 sWakeLock.release();
1949 break;
1950
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001951 case MESSAGE_UPDATE_STATE:
1952 doUpdateWifiState();
1953 break;
1954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 case MESSAGE_DISABLE_WIFI:
1956 // a non-zero msg.arg1 value means the "enabled" setting
1957 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001958 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -07001959 mWifiWatchdogService = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 sWakeLock.release();
1961 break;
1962
1963 case MESSAGE_STOP_WIFI:
1964 mWifiStateTracker.disconnectAndStop();
1965 // don't release wakelock
1966 break;
1967
1968 case MESSAGE_RELEASE_WAKELOCK:
Irfan Sheriff3bf504d2010-03-23 12:24:33 -07001969 sDriverStopWakeLock.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001971
1972 case MESSAGE_START_ACCESS_POINT:
1973 setWifiApEnabledBlocking(true,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001974 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001975 (WifiConfiguration) msg.obj);
Irfan Sheriff80cb5982010-03-19 10:40:18 -07001976 sWakeLock.release();
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001977 break;
1978
1979 case MESSAGE_STOP_ACCESS_POINT:
1980 setWifiApEnabledBlocking(false,
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -08001981 msg.arg1,
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001982 (WifiConfiguration) msg.obj);
1983 sWakeLock.release();
1984 break;
Irfan Sheriff59610c02010-03-30 11:00:41 -07001985
1986 case MESSAGE_SET_CHANNELS:
1987 setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
1988 break;
1989
Irfan Sherifffae66c32010-08-16 11:36:41 -07001990 case MESSAGE_ENABLE_NETWORKS:
1991 mWifiStateTracker.enableAllNetworks(getConfiguredNetworks());
1992 break;
1993
Irfan Sheriff0859b762010-09-06 15:34:50 -07001994 case MESSAGE_START_SCAN:
1995 boolean forceActive = (msg.arg1 == 1);
1996 switch (mWifiStateTracker.getSupplicantState()) {
1997 case DISCONNECTED:
1998 case INACTIVE:
1999 case SCANNING:
2000 case DORMANT:
2001 break;
2002 default:
2003 mWifiStateTracker.setScanResultHandling(
2004 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
2005 break;
2006 }
2007 mWifiStateTracker.scan(forceActive);
2008 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010 }
2011 }
2012
2013 @Override
2014 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2015 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2016 != PackageManager.PERMISSION_GRANTED) {
2017 pw.println("Permission Denial: can't dump WifiService from from pid="
2018 + Binder.getCallingPid()
2019 + ", uid=" + Binder.getCallingUid());
2020 return;
2021 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08002022 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 pw.println("Stay-awake conditions: " +
2024 Settings.System.getInt(mContext.getContentResolver(),
2025 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
2026 pw.println();
2027
2028 pw.println("Internal state:");
2029 pw.println(mWifiStateTracker);
2030 pw.println();
2031 pw.println("Latest scan results:");
2032 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
2033 if (scanResults != null && scanResults.size() != 0) {
2034 pw.println(" BSSID Frequency RSSI Flags SSID");
2035 for (ScanResult r : scanResults) {
2036 pw.printf(" %17s %9d %5d %-16s %s%n",
2037 r.BSSID,
2038 r.frequency,
2039 r.level,
2040 r.capabilities,
2041 r.SSID == null ? "" : r.SSID);
2042 }
2043 }
2044 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002045 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002046 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002047 mScanLocksAcquired + " scan");
2048 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002049 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002050 mScanLocksReleased + " scan");
2051 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 pw.println("Locks held:");
2053 mLocks.dump(pw);
2054 }
2055
2056 private static String stateName(int wifiState) {
2057 switch (wifiState) {
2058 case WIFI_STATE_DISABLING:
2059 return "disabling";
2060 case WIFI_STATE_DISABLED:
2061 return "disabled";
2062 case WIFI_STATE_ENABLING:
2063 return "enabling";
2064 case WIFI_STATE_ENABLED:
2065 return "enabled";
2066 case WIFI_STATE_UNKNOWN:
2067 return "unknown state";
2068 default:
2069 return "[invalid state]";
2070 }
2071 }
2072
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002073 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002074 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
2075 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077
2078 public void binderDied() {
2079 synchronized (mLocks) {
2080 releaseWifiLockLocked(mBinder);
2081 }
2082 }
2083
2084 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002085 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087 }
2088
2089 private class LockList {
2090 private List<WifiLock> mList;
2091
2092 private LockList() {
2093 mList = new ArrayList<WifiLock>();
2094 }
2095
2096 private synchronized boolean hasLocks() {
2097 return !mList.isEmpty();
2098 }
2099
2100 private synchronized int getStrongestLockMode() {
2101 if (mList.isEmpty()) {
2102 return WifiManager.WIFI_MODE_FULL;
2103 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002104
2105 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
2106 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002108
2109 if (mFullLocksAcquired > mFullLocksReleased) {
2110 return WifiManager.WIFI_MODE_FULL;
2111 }
2112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 return WifiManager.WIFI_MODE_SCAN_ONLY;
2114 }
2115
2116 private void addLock(WifiLock lock) {
2117 if (findLockByBinder(lock.mBinder) < 0) {
2118 mList.add(lock);
2119 }
2120 }
2121
2122 private WifiLock removeLock(IBinder binder) {
2123 int index = findLockByBinder(binder);
2124 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002125 WifiLock ret = mList.remove(index);
2126 ret.unlinkDeathRecipient();
2127 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 } else {
2129 return null;
2130 }
2131 }
2132
2133 private int findLockByBinder(IBinder binder) {
2134 int size = mList.size();
2135 for (int i = size - 1; i >= 0; i--)
2136 if (mList.get(i).mBinder == binder)
2137 return i;
2138 return -1;
2139 }
2140
2141 private void dump(PrintWriter pw) {
2142 for (WifiLock l : mList) {
2143 pw.print(" ");
2144 pw.println(l);
2145 }
2146 }
2147 }
2148
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002149 void enforceWakeSourcePermission(int uid, int pid) {
2150 if (uid == Process.myUid()) {
2151 return;
2152 }
2153 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
2154 pid, uid, null);
2155 }
2156
2157 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002159 if (lockMode != WifiManager.WIFI_MODE_FULL &&
2160 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
2161 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
2162 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
2163 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 return false;
2165 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002166 if (ws != null && ws.size() == 0) {
2167 ws = null;
2168 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002169 if (ws != null) {
2170 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
2171 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002172 if (ws == null) {
2173 ws = new WorkSource(Binder.getCallingUid());
2174 }
2175 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 synchronized (mLocks) {
2177 return acquireWifiLockLocked(wifiLock);
2178 }
2179 }
2180
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002181 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
2182 switch(wifiLock.mMode) {
2183 case WifiManager.WIFI_MODE_FULL:
2184 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2185 break;
2186 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2187 /* Treat high power as a full lock for battery stats */
2188 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2189 break;
2190 case WifiManager.WIFI_MODE_SCAN_ONLY:
2191 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
2192 break;
2193 }
2194 }
2195
2196 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
2197 switch(wifiLock.mMode) {
2198 case WifiManager.WIFI_MODE_FULL:
2199 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2200 break;
2201 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2202 /* Treat high power as a full lock for battery stats */
2203 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
2204 break;
2205 case WifiManager.WIFI_MODE_SCAN_ONLY:
2206 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
2207 break;
2208 }
2209 }
2210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07002212 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002215
The Android Open Source Project10592532009-03-18 17:39:46 -07002216 long ident = Binder.clearCallingIdentity();
2217 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002218 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002219 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002220 case WifiManager.WIFI_MODE_FULL:
2221 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002222 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002223 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2224 ++mFullHighPerfLocksAcquired;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002225 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002226 case WifiManager.WIFI_MODE_SCAN_ONLY:
2227 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002228 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002229 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002230
2231 // Be aggressive about adding new locks into the accounted state...
2232 // we want to over-report rather than under-report.
2233 reportStartWorkSource();
2234
2235 updateWifiState();
2236 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07002237 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002238 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07002239 } finally {
2240 Binder.restoreCallingIdentity(ident);
2241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
2243
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002244 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
2245 int uid = Binder.getCallingUid();
2246 int pid = Binder.getCallingPid();
2247 if (ws != null && ws.size() == 0) {
2248 ws = null;
2249 }
2250 if (ws != null) {
2251 enforceWakeSourcePermission(uid, pid);
2252 }
2253 long ident = Binder.clearCallingIdentity();
2254 try {
2255 synchronized (mLocks) {
2256 int index = mLocks.findLockByBinder(lock);
2257 if (index < 0) {
2258 throw new IllegalArgumentException("Wifi lock not active");
2259 }
2260 WifiLock wl = mLocks.mList.get(index);
2261 noteReleaseWifiLock(wl);
2262 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
2263 noteAcquireWifiLock(wl);
2264 }
2265 } catch (RemoteException e) {
2266 } finally {
2267 Binder.restoreCallingIdentity(ident);
2268 }
2269 }
2270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 public boolean releaseWifiLock(IBinder lock) {
2272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2273 synchronized (mLocks) {
2274 return releaseWifiLockLocked(lock);
2275 }
2276 }
2277
2278 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002279 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002280
The Android Open Source Project10592532009-03-18 17:39:46 -07002281 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002282
Irfan Sheriffc89dd542010-09-28 08:40:54 -07002283 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002284
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002285 hadLock = (wifiLock != null);
2286
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002287 long ident = Binder.clearCallingIdentity();
2288 try {
2289 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002290 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002291 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002292 case WifiManager.WIFI_MODE_FULL:
2293 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002294 break;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002295 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
2296 ++mFullHighPerfLocksReleased;
Irfan Sheriff8c11e952010-08-12 20:26:23 -07002297 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002298 case WifiManager.WIFI_MODE_SCAN_ONLY:
2299 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002300 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002301 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002302 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002303
2304 // TODO - should this only happen if you hadLock?
2305 updateWifiState();
2306
2307 } catch (RemoteException e) {
2308 } finally {
2309 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002310 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07002311
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002312 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002314
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002315 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002316 implements IBinder.DeathRecipient {
2317 String mTag;
2318 int mMode;
2319 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002320 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002321
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002322 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002323 super();
2324 mTag = tag;
2325 mMode = mode;
2326 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002327 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002328 try {
2329 mBinder.linkToDeath(this, 0);
2330 } catch (RemoteException e) {
2331 binderDied();
2332 }
2333 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002334
2335 void unlinkDeathRecipient() {
2336 mBinder.unlinkToDeath(this, 0);
2337 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002338 }
2339
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002340 private class Multicaster extends DeathRecipient {
2341 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07002342 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002343 }
2344
2345 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002346 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002347 synchronized (mMulticasters) {
2348 int i = mMulticasters.indexOf(this);
2349 if (i != -1) {
2350 removeMulticasterLocked(i, mMode);
2351 }
2352 }
2353 }
2354
2355 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002356 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002357 }
2358
2359 public int getUid() {
2360 return mMode;
2361 }
2362 }
2363
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002364 public void initializeMulticastFiltering() {
2365 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002366
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002367 synchronized (mMulticasters) {
2368 // if anybody had requested filters be off, leave off
2369 if (mMulticasters.size() != 0) {
2370 return;
2371 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002372 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002373 }
2374 }
2375 }
2376
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002377 public void acquireMulticastLock(IBinder binder, String tag) {
2378 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002379
2380 synchronized (mMulticasters) {
2381 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002382 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002383 // Note that we could call stopPacketFiltering only when
2384 // our new size == 1 (first call), but this function won't
2385 // be called often and by making the stopPacket call each
2386 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002387 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002388 }
2389
2390 int uid = Binder.getCallingUid();
2391 Long ident = Binder.clearCallingIdentity();
2392 try {
2393 mBatteryStats.noteWifiMulticastEnabled(uid);
2394 } catch (RemoteException e) {
2395 } finally {
2396 Binder.restoreCallingIdentity(ident);
2397 }
2398 }
2399
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002400 public void releaseMulticastLock() {
2401 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002402
2403 int uid = Binder.getCallingUid();
2404 synchronized (mMulticasters) {
2405 mMulticastDisabled++;
2406 int size = mMulticasters.size();
2407 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002408 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002409 if ((m != null) && (m.getUid() == uid)) {
2410 removeMulticasterLocked(i, uid);
2411 }
2412 }
2413 }
2414 }
2415
2416 private void removeMulticasterLocked(int i, int uid)
2417 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002418 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002419
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002420 if (removed != null) {
2421 removed.unlinkDeathRecipient();
2422 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002423 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002424 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002425 }
2426
2427 Long ident = Binder.clearCallingIdentity();
2428 try {
2429 mBatteryStats.noteWifiMulticastDisabled(uid);
2430 } catch (RemoteException e) {
2431 } finally {
2432 Binder.restoreCallingIdentity(ident);
2433 }
2434 }
2435
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002436 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002437 enforceAccessPermission();
2438
2439 synchronized (mMulticasters) {
2440 return (mMulticasters.size() > 0);
2441 }
2442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443}