blob: 8fa862dea6c905834b44d3c8fce148734a51248d [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 Sheriff5321aef2010-02-12 12:35:59 -080049import android.net.ConnectivityManager;
50import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.NetworkStateTracker;
52import android.net.DhcpInfo;
Mike Lockwood0900f362009-07-10 17:24:07 -040053import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Binder;
55import android.os.Handler;
56import android.os.HandlerThread;
57import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080058import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Looper;
60import android.os.Message;
61import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070062import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070064import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.provider.Settings;
Joe Onorato8a9b2202010-02-26 18:56:32 -080066import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.text.TextUtils;
68
69import java.util.ArrayList;
70import java.util.BitSet;
71import java.util.HashMap;
72import java.util.LinkedHashMap;
73import java.util.List;
74import java.util.Map;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080075import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.regex.Pattern;
77import java.io.FileDescriptor;
78import java.io.PrintWriter;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080079import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
The Android Open Source Project10592532009-03-18 17:39:46 -070081import com.android.internal.app.IBatteryStats;
Christopher Tate45281862010-03-05 15:46:30 -080082import android.app.backup.IBackupManager;
The Android Open Source Project10592532009-03-18 17:39:46 -070083import com.android.server.am.BatteryStatsService;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085/**
86 * WifiService handles remote WiFi operation requests by implementing
87 * the IWifiManager interface. It also creates a WifiMonitor to listen
88 * for Wifi-related events.
89 *
90 * @hide
91 */
92public class WifiService extends IWifiManager.Stub {
93 private static final String TAG = "WifiService";
94 private static final boolean DBG = false;
95 private static final Pattern scanResultPattern = Pattern.compile("\t+");
96 private final WifiStateTracker mWifiStateTracker;
97
98 private Context mContext;
99 private int mWifiState;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800100 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102 private AlarmManager mAlarmManager;
103 private PendingIntent mIdleIntent;
104 private static final int IDLE_REQUEST = 0;
105 private boolean mScreenOff;
106 private boolean mDeviceIdle;
107 private int mPluggedType;
108
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700109 // true if the user enabled Wifi while in airplane mode
110 private boolean mAirplaneModeOverwridden;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700113 // some wifi lock statistics
114 private int mFullLocksAcquired;
115 private int mFullLocksReleased;
116 private int mScanLocksAcquired;
117 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700118
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700119 private final List<Multicaster> mMulticasters =
120 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700121 private int mMulticastEnabled;
122 private int mMulticastDisabled;
123
The Android Open Source Project10592532009-03-18 17:39:46 -0700124 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800125
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800126 private INetworkManagementService nwService;
127 ConnectivityManager mCm;
128 private String[] mWifiRegexs;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800131 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
132 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 * the approximate point at which the battery drain caused by Wi-Fi
134 * being enabled but not active exceeds the battery drain caused by
135 * re-establishing a connection to the mobile data network.
136 */
137 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
138
139 private static final String WAKELOCK_TAG = "WifiService";
140
141 /**
142 * The maximum amount of time to hold the wake lock after a disconnect
143 * caused by stopping the driver. Establishing an EDGE connection has been
144 * observed to take about 5 seconds under normal circumstances. This
145 * provides a bit of extra margin.
146 * <p>
147 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
148 * This is the default value if a Settings.Secure value is not present.
149 */
150 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
151
152 // Wake lock used by driver-stop operation
153 private static PowerManager.WakeLock sDriverStopWakeLock;
154 // Wake lock used by other operations
155 private static PowerManager.WakeLock sWakeLock;
156
157 private static final int MESSAGE_ENABLE_WIFI = 0;
158 private static final int MESSAGE_DISABLE_WIFI = 1;
159 private static final int MESSAGE_STOP_WIFI = 2;
160 private static final int MESSAGE_START_WIFI = 3;
161 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -0700162 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800163 private static final int MESSAGE_START_ACCESS_POINT = 6;
164 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
167 private final WifiHandler mWifiHandler;
168
169 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 * Cache of scan results objects (size is somewhat arbitrary)
171 */
172 private static final int SCAN_RESULT_CACHE_SIZE = 80;
173 private final LinkedHashMap<String, ScanResult> mScanResultCache;
174
175 /*
176 * Character buffer used to parse scan results (optimization)
177 */
178 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 private boolean mNeedReconfig;
180
Dianne Hackborn617f8772009-03-31 15:04:46 -0700181 /*
182 * Last UID that asked to enable WIFI.
183 */
184 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 /**
187 * Number of allowed radio frequency channels in various regulatory domains.
188 * This list is sufficient for 802.11b/g networks (2.4GHz range).
189 */
190 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
191
192 private static final String ACTION_DEVICE_IDLE =
193 "com.android.server.WifiManager.action.DEVICE_IDLE";
194
195 WifiService(Context context, WifiStateTracker tracker) {
196 mContext = context;
197 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400198 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700199 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800200
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800201 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
202 nwService = INetworkManagementService.Stub.asInterface(b);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 mScanResultCache = new LinkedHashMap<String, ScanResult>(
205 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
206 /*
207 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
208 * elements
209 */
210 public boolean removeEldestEntry(Map.Entry eldest) {
211 return SCAN_RESULT_CACHE_SIZE < this.size();
212 }
213 };
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 HandlerThread wifiThread = new HandlerThread("WifiService");
216 wifiThread.start();
217 mWifiHandler = new WifiHandler(wifiThread.getLooper());
218
219 mWifiState = WIFI_STATE_DISABLED;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800220 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800222 boolean wifiAPEnabled = wifiEnabled ? false : getPersistedWifiApEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223
224 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
225 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
226 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
227
228 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
229 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
230 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
231 mWifiStateTracker.setReleaseWakeLockCallback(
232 new Runnable() {
233 public void run() {
234 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
235 synchronized (sDriverStopWakeLock) {
236 if (sDriverStopWakeLock.isHeld()) {
237 sDriverStopWakeLock.release();
238 }
239 }
240 }
241 }
242 );
243
Joe Onorato8a9b2202010-02-26 18:56:32 -0800244 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 (wifiEnabled ? "enabled" : "disabled"));
246
247 mContext.registerReceiver(
248 new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700251 // clear our flag indicating the user has overwridden airplane mode
252 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 updateWifiState();
254 }
255 },
256 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
257
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800258 mContext.registerReceiver(
259 new BroadcastReceiver() {
260 @Override
261 public void onReceive(Context context, Intent intent) {
262
263 ArrayList<String> available = intent.getStringArrayListExtra(
264 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
265 ArrayList<String> active = intent.getStringArrayListExtra(
266 ConnectivityManager.EXTRA_ACTIVE_TETHER);
267 updateTetherState(available, active);
268
269 }
270 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
271
Dianne Hackborn617f8772009-03-31 15:04:46 -0700272 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800273 setWifiApEnabledBlocking(wifiAPEnabled, true, Process.myUid(), null);
274 }
275
276 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
277
278 boolean wifiTethered = false;
279 boolean wifiAvailable = false;
280
281 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
282 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
283
284 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
285 mWifiRegexs = mCm.getTetherableWifiRegexs();
286
287 for (String intf : available) {
288 for (String regex : mWifiRegexs) {
289 if (intf.matches(regex)) {
290
291 InterfaceConfiguration ifcg = null;
292 try {
293 ifcg = service.getInterfaceConfig(intf);
294 if (ifcg != null) {
295 /* IP/netmask: 169.254.2.1/255.255.255.0 */
296 ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
297 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
298 ifcg.interfaceFlags = "up";
299
300 service.setInterfaceConfig(intf, ifcg);
301 }
302 } catch (Exception e) {
303 /**
304 * TODO: Add broadcast to indicate tether failed
305 */
306 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
307 return;
308 }
309
310 /**
311 * TODO: Add broadcast to indicate tether failed
312 */
313 if(mCm.tether(intf) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
314 Slog.d(TAG, "Tethered "+intf);
315 } else {
316 Slog.e(TAG, "Error tethering "+intf);
317 }
318 break;
319 }
320 }
321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 }
323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 private boolean getPersistedWifiEnabled() {
325 final ContentResolver cr = mContext.getContentResolver();
326 try {
327 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
328 } catch (Settings.SettingNotFoundException e) {
329 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
330 return false;
331 }
332 }
333
334 private void persistWifiEnabled(boolean enabled) {
335 final ContentResolver cr = mContext.getContentResolver();
336 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
337 }
338
339 NetworkStateTracker getNetworkStateTracker() {
340 return mWifiStateTracker;
341 }
342
343 /**
344 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
345 * @return {@code true} if the operation succeeds
346 */
347 public boolean pingSupplicant() {
348 enforceChangePermission();
349 synchronized (mWifiStateTracker) {
350 return WifiNative.pingCommand();
351 }
352 }
353
354 /**
355 * see {@link android.net.wifi.WifiManager#startScan()}
356 * @return {@code true} if the operation succeeds
357 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400358 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 enforceChangePermission();
360 synchronized (mWifiStateTracker) {
361 switch (mWifiStateTracker.getSupplicantState()) {
362 case DISCONNECTED:
363 case INACTIVE:
364 case SCANNING:
365 case DORMANT:
366 break;
367 default:
368 WifiNative.setScanResultHandlingCommand(
369 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
370 break;
371 }
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400372 return WifiNative.scanCommand(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 }
374 }
375
376 /**
377 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
378 * @param enable {@code true} to enable, {@code false} to disable.
379 * @return {@code true} if the enable/disable operation was
380 * started or is already in the queue.
381 */
382 public boolean setWifiEnabled(boolean enable) {
383 enforceChangePermission();
384 if (mWifiHandler == null) return false;
385
386 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700387 // caller may not have WAKE_LOCK permission - it's not required here
388 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700390 Binder.restoreCallingIdentity(ident);
391
Dianne Hackborn617f8772009-03-31 15:04:46 -0700392 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700393 // set a flag if the user is enabling Wifi while in airplane mode
394 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700395 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397
398 return true;
399 }
400
401 /**
402 * Enables/disables Wi-Fi synchronously.
403 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
404 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700405 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 * @return {@code true} if the operation succeeds (or if the existing state
407 * is the same as the requested state)
408 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700409 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
411
412 if (mWifiState == eventualWifiState) {
413 return true;
414 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700415 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 return false;
417 }
418
Irfan Sheriffcd770372010-01-08 09:36:04 -0800419 /**
420 * Multiple calls to unregisterReceiver() cause exception and a system crash.
421 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
422 * disable wifi at the same time.
423 * Avoid doing a disable when the current Wifi state is UNKNOWN
424 * TODO: Handle driver load fail and supplicant lost as seperate states
425 */
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800426 if ((mWifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800427 return false;
428 }
429
Dianne Hackborn617f8772009-03-31 15:04:46 -0700430 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800432 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
433 setWifiApEnabledBlocking(false, true, Process.myUid(), null);
434 }
435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 if (enable) {
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800437 synchronized (mWifiStateTracker) {
438 if (!WifiNative.loadDriver()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800439 Slog.e(TAG, "Failed to load Wi-Fi driver.");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800440 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
441 return false;
442 }
443 if (!WifiNative.startSupplicant()) {
444 WifiNative.unloadDriver();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800445 Slog.e(TAG, "Failed to start supplicant daemon.");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800446 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
447 return false;
448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450 registerForBroadcasts();
451 mWifiStateTracker.startEventLoop();
452 } else {
453
454 mContext.unregisterReceiver(mReceiver);
455 // Remove notification (it will no-op if it isn't visible)
456 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
457
458 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800459 synchronized (mWifiStateTracker) {
460 if (!WifiNative.stopSupplicant()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800461 Slog.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700462 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 failedToStopSupplicantOrUnloadDriver = true;
464 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800465
Irfan Sheriff102d05f2010-02-05 14:47:27 -0800466 /**
467 * Reset connections and disable interface
468 * before we unload the driver
469 */
470 mWifiStateTracker.resetConnections(true);
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800471
472 if (!WifiNative.unloadDriver()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800473 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800474 if (!failedToStopSupplicantOrUnloadDriver) {
475 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
476 failedToStopSupplicantOrUnloadDriver = true;
477 }
478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
480 if (failedToStopSupplicantOrUnloadDriver) {
481 return false;
482 }
483 }
484
485 // Success!
486
487 if (persist) {
488 persistWifiEnabled(enable);
489 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700490 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 return true;
492 }
493
Dianne Hackborn617f8772009-03-31 15:04:46 -0700494 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 final int previousWifiState = mWifiState;
496
The Android Open Source Project10592532009-03-18 17:39:46 -0700497 long ident = Binder.clearCallingIdentity();
498 try {
499 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700500 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700501 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700502 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700503 }
504 } catch (RemoteException e) {
505 } finally {
506 Binder.restoreCallingIdentity(ident);
507 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 // Update state
510 mWifiState = wifiState;
511
512 // Broadcast
513 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
514 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
515 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
516 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
517 mContext.sendStickyBroadcast(intent);
518 }
519
520 private void enforceAccessPermission() {
521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
522 "WifiService");
523 }
524
525 private void enforceChangePermission() {
526 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
527 "WifiService");
528
529 }
530
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700531 private void enforceMulticastChangePermission() {
532 mContext.enforceCallingOrSelfPermission(
533 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
534 "WifiService");
535 }
536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 /**
538 * see {@link WifiManager#getWifiState()}
539 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
540 * {@link WifiManager#WIFI_STATE_DISABLING},
541 * {@link WifiManager#WIFI_STATE_ENABLED},
542 * {@link WifiManager#WIFI_STATE_ENABLING},
543 * {@link WifiManager#WIFI_STATE_UNKNOWN}
544 */
545 public int getWifiEnabledState() {
546 enforceAccessPermission();
547 return mWifiState;
548 }
549
550 /**
551 * see {@link android.net.wifi.WifiManager#disconnect()}
552 * @return {@code true} if the operation succeeds
553 */
554 public boolean disconnect() {
555 enforceChangePermission();
556 synchronized (mWifiStateTracker) {
557 return WifiNative.disconnectCommand();
558 }
559 }
560
561 /**
562 * see {@link android.net.wifi.WifiManager#reconnect()}
563 * @return {@code true} if the operation succeeds
564 */
565 public boolean reconnect() {
566 enforceChangePermission();
567 synchronized (mWifiStateTracker) {
568 return WifiNative.reconnectCommand();
569 }
570 }
571
572 /**
573 * see {@link android.net.wifi.WifiManager#reassociate()}
574 * @return {@code true} if the operation succeeds
575 */
576 public boolean reassociate() {
577 enforceChangePermission();
578 synchronized (mWifiStateTracker) {
579 return WifiNative.reassociateCommand();
580 }
581 }
582
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800583 private boolean getPersistedWifiApEnabled() {
584 final ContentResolver cr = mContext.getContentResolver();
585 try {
586 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_ON) == 1;
587 } catch (Settings.SettingNotFoundException e) {
588 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, 0);
589 return false;
590 }
591 }
592
593 private void persistWifiApEnabled(boolean enabled) {
594 final ContentResolver cr = mContext.getContentResolver();
595 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, enabled ? 1 : 0);
596 }
597
598 /**
599 * see {@link android.net.wifi.WifiManager#startAccessPoint(WifiConfiguration)}
600 * @param wifiConfig SSID, security and channel details as
601 * part of WifiConfiguration
602 * @return {@code true} if the start operation was
603 * started or is already in the queue.
604 */
605 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
606 enforceChangePermission();
607 if (mWifiHandler == null) return false;
608
609 synchronized (mWifiHandler) {
610
611 long ident = Binder.clearCallingIdentity();
612 sWakeLock.acquire();
613 Binder.restoreCallingIdentity(ident);
614
615 mLastEnableUid = Binder.getCallingUid();
616
617 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
618 }
619
620 return true;
621 }
622
623 /**
624 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
625 * and soft access point configured as a single operation.
626 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
627 * @param persist {@code true} if the setting should be persisted.
628 * @param uid The UID of the process making the request.
629 * @param config The WifiConfiguration for AP
630 * @return {@code true} if the operation succeeds (or if the existing state
631 * is the same as the requested state)
632 */
633 /**
634 * TODO: persist needs to go away in WifiService
635 * This will affect all persist related functions
636 * for Access Point
637 */
638 private boolean setWifiApEnabledBlocking(boolean enable,
639 boolean persist, int uid, WifiConfiguration wifiConfig) {
640 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
641
642 if (mWifiApState == eventualWifiApState) {
643 return true;
644 }
645
646 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING : WIFI_AP_STATE_DISABLING, uid);
647
648 if (enable && (mWifiState == WIFI_STATE_ENABLED)) {
649 setWifiEnabledBlocking(false, true, Process.myUid());
650 }
651
652 if (enable) {
653 synchronized (mWifiStateTracker) {
654 if (!WifiNative.loadDriver()) {
655 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
656 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
657 return false;
658 }
659 }
660
661 try {
662 nwService.startAccessPoint();
663 } catch(Exception e) {
664 Slog.e(TAG, "Exception in startAccessPoint()");
665 }
666
667 } else {
668
669 try {
670 nwService.stopAccessPoint();
671 } catch(Exception e) {
672 Slog.e(TAG, "Exception in stopAccessPoint()");
673 }
674
675 synchronized (mWifiStateTracker) {
676 if (!WifiNative.unloadDriver()) {
677 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
678 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
679 return false;
680 }
681 }
682 }
683
684 // Success!
685 if (persist) {
686 persistWifiApEnabled(enable);
687 }
688 setWifiApEnabledState(eventualWifiApState, uid);
689 return true;
690 }
691
692 /**
693 * see {@link WifiManager#getWifiApState()}
694 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
695 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
696 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
697 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
698 * {@link WifiManager#WIFI_AP_STATE_FAILED}
699 */
700 public int getWifiApEnabledState() {
701 enforceAccessPermission();
702 return mWifiApState;
703 }
704
705 private void setWifiApEnabledState(int wifiAPState, int uid) {
706 final int previousWifiApState = mWifiApState;
707
708 long ident = Binder.clearCallingIdentity();
709 try {
710 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
711 mBatteryStats.noteWifiOn(uid);
712 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
713 mBatteryStats.noteWifiOff(uid);
714 }
715 } catch (RemoteException e) {
716 } finally {
717 Binder.restoreCallingIdentity(ident);
718 }
719
720 // Update state
721 mWifiApState = wifiAPState;
722
723 // Broadcast
724 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
725 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
726 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
727 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
728 mContext.sendStickyBroadcast(intent);
729 }
730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 /**
732 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
733 * @return the list of configured networks
734 */
735 public List<WifiConfiguration> getConfiguredNetworks() {
736 enforceAccessPermission();
737 String listStr;
738 /*
739 * We don't cache the list, because we want to allow
740 * for the possibility that the configuration file
741 * has been modified through some external means,
742 * such as the wpa_cli command line program.
743 */
744 synchronized (mWifiStateTracker) {
745 listStr = WifiNative.listNetworksCommand();
746 }
747 List<WifiConfiguration> networks =
748 new ArrayList<WifiConfiguration>();
749 if (listStr == null)
750 return networks;
751
752 String[] lines = listStr.split("\n");
753 // Skip the first line, which is a header
754 for (int i = 1; i < lines.length; i++) {
755 String[] result = lines[i].split("\t");
756 // network-id | ssid | bssid | flags
757 WifiConfiguration config = new WifiConfiguration();
758 try {
759 config.networkId = Integer.parseInt(result[0]);
760 } catch(NumberFormatException e) {
761 continue;
762 }
763 if (result.length > 3) {
764 if (result[3].indexOf("[CURRENT]") != -1)
765 config.status = WifiConfiguration.Status.CURRENT;
766 else if (result[3].indexOf("[DISABLED]") != -1)
767 config.status = WifiConfiguration.Status.DISABLED;
768 else
769 config.status = WifiConfiguration.Status.ENABLED;
770 } else
771 config.status = WifiConfiguration.Status.ENABLED;
772 synchronized (mWifiStateTracker) {
773 readNetworkVariables(config);
774 }
775 networks.add(config);
776 }
777
778 return networks;
779 }
780
781 /**
782 * Read the variables from the supplicant daemon that are needed to
783 * fill in the WifiConfiguration object.
784 * <p/>
785 * The caller must hold the synchronization monitor.
786 * @param config the {@link WifiConfiguration} object to be filled in.
787 */
788 private static void readNetworkVariables(WifiConfiguration config) {
789
790 int netId = config.networkId;
791 if (netId < 0)
792 return;
793
794 /*
795 * TODO: maybe should have a native method that takes an array of
796 * variable names and returns an array of values. But we'd still
797 * be doing a round trip to the supplicant daemon for each variable.
798 */
799 String value;
800
801 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
802 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800803 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 } else {
805 config.SSID = null;
806 }
807
808 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
809 if (!TextUtils.isEmpty(value)) {
810 config.BSSID = value;
811 } else {
812 config.BSSID = null;
813 }
814
815 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
816 config.priority = -1;
817 if (!TextUtils.isEmpty(value)) {
818 try {
819 config.priority = Integer.parseInt(value);
820 } catch (NumberFormatException ignore) {
821 }
822 }
823
824 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
825 config.hiddenSSID = false;
826 if (!TextUtils.isEmpty(value)) {
827 try {
828 config.hiddenSSID = Integer.parseInt(value) != 0;
829 } catch (NumberFormatException ignore) {
830 }
831 }
832
833 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
834 config.wepTxKeyIndex = -1;
835 if (!TextUtils.isEmpty(value)) {
836 try {
837 config.wepTxKeyIndex = Integer.parseInt(value);
838 } catch (NumberFormatException ignore) {
839 }
840 }
841
842 /*
843 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
844 * just a "*" if the key is set, or the null string otherwise.
845 */
846 for (int i = 0; i < 4; i++) {
847 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
848 if (!TextUtils.isEmpty(value)) {
849 config.wepKeys[i] = value;
850 } else {
851 config.wepKeys[i] = null;
852 }
853 }
854
855 /*
856 * Get the private shared key. Note that the actual keys are not passed back,
857 * just a "*" if the key is set, or the null string otherwise.
858 */
859 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
860 if (!TextUtils.isEmpty(value)) {
861 config.preSharedKey = value;
862 } else {
863 config.preSharedKey = null;
864 }
865
866 value = WifiNative.getNetworkVariableCommand(config.networkId,
867 WifiConfiguration.Protocol.varName);
868 if (!TextUtils.isEmpty(value)) {
869 String vals[] = value.split(" ");
870 for (String val : vals) {
871 int index =
872 lookupString(val, WifiConfiguration.Protocol.strings);
873 if (0 <= index) {
874 config.allowedProtocols.set(index);
875 }
876 }
877 }
878
879 value = WifiNative.getNetworkVariableCommand(config.networkId,
880 WifiConfiguration.KeyMgmt.varName);
881 if (!TextUtils.isEmpty(value)) {
882 String vals[] = value.split(" ");
883 for (String val : vals) {
884 int index =
885 lookupString(val, WifiConfiguration.KeyMgmt.strings);
886 if (0 <= index) {
887 config.allowedKeyManagement.set(index);
888 }
889 }
890 }
891
892 value = WifiNative.getNetworkVariableCommand(config.networkId,
893 WifiConfiguration.AuthAlgorithm.varName);
894 if (!TextUtils.isEmpty(value)) {
895 String vals[] = value.split(" ");
896 for (String val : vals) {
897 int index =
898 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
899 if (0 <= index) {
900 config.allowedAuthAlgorithms.set(index);
901 }
902 }
903 }
904
905 value = WifiNative.getNetworkVariableCommand(config.networkId,
906 WifiConfiguration.PairwiseCipher.varName);
907 if (!TextUtils.isEmpty(value)) {
908 String vals[] = value.split(" ");
909 for (String val : vals) {
910 int index =
911 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
912 if (0 <= index) {
913 config.allowedPairwiseCiphers.set(index);
914 }
915 }
916 }
917
918 value = WifiNative.getNetworkVariableCommand(config.networkId,
919 WifiConfiguration.GroupCipher.varName);
920 if (!TextUtils.isEmpty(value)) {
921 String vals[] = value.split(" ");
922 for (String val : vals) {
923 int index =
924 lookupString(val, WifiConfiguration.GroupCipher.strings);
925 if (0 <= index) {
926 config.allowedGroupCiphers.set(index);
927 }
928 }
929 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800930
931 for (WifiConfiguration.EnterpriseField field :
932 config.enterpriseFields) {
933 value = WifiNative.getNetworkVariableCommand(netId,
934 field.varName());
935 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800936 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800937 field.setValue(value);
938 }
939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800942 private static String removeDoubleQuotes(String string) {
943 if (string.length() <= 2) return "";
944 return string.substring(1, string.length() - 1);
945 }
946
947 private static String convertToQuotedString(String string) {
948 return "\"" + string + "\"";
949 }
950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 /**
952 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
953 * @return the supplicant-assigned identifier for the new or updated
954 * network if the operation succeeds, or {@code -1} if it fails
955 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800956 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 enforceChangePermission();
958 /*
959 * If the supplied networkId is -1, we create a new empty
960 * network configuration. Otherwise, the networkId should
961 * refer to an existing configuration.
962 */
963 int netId = config.networkId;
964 boolean newNetwork = netId == -1;
965 boolean doReconfig;
966 int currentPriority;
967 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800968 synchronized (mWifiStateTracker) {
969 if (newNetwork) {
970 netId = WifiNative.addNetworkCommand();
971 if (netId < 0) {
972 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800973 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800974 }
975 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800977 doReconfig = true;
978 } else {
979 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
980 currentPriority = -1;
981 if (!TextUtils.isEmpty(priorityVal)) {
982 try {
983 currentPriority = Integer.parseInt(priorityVal);
984 } catch (NumberFormatException ignore) {
985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800987 doReconfig = currentPriority != config.priority;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800989 mNeedReconfig = mNeedReconfig || doReconfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800991 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 /*
993 * Note that if a networkId for a non-existent network
994 * was supplied, then the first setNetworkVariableCommand()
995 * will fail, so we don't bother to make a separate check
996 * for the validity of the ID up front.
997 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 if (config.SSID != null &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800999 !WifiNative.setNetworkVariableCommand(
1000 netId,
1001 WifiConfiguration.ssidVarName,
1002 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001004 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006 break setVariables;
1007 }
1008
1009 if (config.BSSID != null &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001010 !WifiNative.setNetworkVariableCommand(
1011 netId,
1012 WifiConfiguration.bssidVarName,
1013 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001015 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
1017 break setVariables;
1018 }
1019
1020 String allowedKeyManagementString =
1021 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1022 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001023 !WifiNative.setNetworkVariableCommand(
1024 netId,
1025 WifiConfiguration.KeyMgmt.varName,
1026 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001028 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001029 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031 break setVariables;
1032 }
1033
1034 String allowedProtocolsString =
1035 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1036 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001037 !WifiNative.setNetworkVariableCommand(
1038 netId,
1039 WifiConfiguration.Protocol.varName,
1040 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001042 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001043 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045 break setVariables;
1046 }
1047
1048 String allowedAuthAlgorithmsString =
1049 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1050 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001051 !WifiNative.setNetworkVariableCommand(
1052 netId,
1053 WifiConfiguration.AuthAlgorithm.varName,
1054 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001056 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001057 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059 break setVariables;
1060 }
1061
1062 String allowedPairwiseCiphersString =
1063 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1064 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001065 !WifiNative.setNetworkVariableCommand(
1066 netId,
1067 WifiConfiguration.PairwiseCipher.varName,
1068 allowedPairwiseCiphersString)) {
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 pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001071 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073 break setVariables;
1074 }
1075
1076 String allowedGroupCiphersString =
1077 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1078 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001079 !WifiNative.setNetworkVariableCommand(
1080 netId,
1081 WifiConfiguration.GroupCipher.varName,
1082 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001084 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001085 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087 break setVariables;
1088 }
1089
1090 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1091 // by preventing "*" as a key.
1092 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001093 !WifiNative.setNetworkVariableCommand(
1094 netId,
1095 WifiConfiguration.pskVarName,
1096 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001098 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100 break setVariables;
1101 }
1102
1103 boolean hasSetKey = false;
1104 if (config.wepKeys != null) {
1105 for (int i = 0; i < config.wepKeys.length; i++) {
1106 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1107 // by preventing "*" as a key.
1108 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
1109 if (!WifiNative.setNetworkVariableCommand(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001110 netId,
1111 WifiConfiguration.wepKeyVarNames[i],
1112 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001114 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001115 "failed to set wep_key"+i+": " +
1116 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118 break setVariables;
1119 }
1120 hasSetKey = true;
1121 }
1122 }
1123 }
1124
1125 if (hasSetKey) {
1126 if (!WifiNative.setNetworkVariableCommand(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001127 netId,
1128 WifiConfiguration.wepTxKeyIdxVarName,
1129 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001131 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001132 "failed to set wep_tx_keyidx: "+
1133 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 break setVariables;
1136 }
1137 }
1138
1139 if (!WifiNative.setNetworkVariableCommand(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001140 netId,
1141 WifiConfiguration.priorityVarName,
1142 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001144 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001145 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 break setVariables;
1148 }
1149
1150 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001151 netId,
1152 WifiConfiguration.hiddenSSIDVarName,
1153 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001155 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001156 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158 break setVariables;
1159 }
1160
Chung-yih Wang43374762009-09-16 14:28:42 +08001161 for (WifiConfiguration.EnterpriseField field
1162 : config.enterpriseFields) {
1163 String varName = field.varName();
1164 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001165 if (value != null) {
1166 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001167 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001168 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001169 if (!WifiNative.setNetworkVariableCommand(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001170 netId,
1171 varName,
1172 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001173 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001174 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001175 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001176 }
1177 break setVariables;
1178 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001179 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 return netId;
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001184 /*
1185 * For an update, if one of the setNetworkVariable operations fails,
1186 * we might want to roll back all the changes already made. But the
1187 * chances are that if anything is going to go wrong, it'll happen
1188 * the first time we try to set one of the variables.
1189 */
1190 if (newNetwork) {
1191 removeNetwork(netId);
1192 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001193 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001194 "Failed to set a network variable, removed network: "
1195 + netId);
1196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198 }
1199 return -1;
1200 }
1201
1202 private static String makeString(BitSet set, String[] strings) {
1203 StringBuffer buf = new StringBuffer();
1204 int nextSetBit = -1;
1205
1206 /* Make sure all set bits are in [0, strings.length) to avoid
1207 * going out of bounds on strings. (Shouldn't happen, but...) */
1208 set = set.get(0, strings.length);
1209
1210 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1211 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1212 }
1213
1214 // remove trailing space
1215 if (set.cardinality() > 0) {
1216 buf.setLength(buf.length() - 1);
1217 }
1218
1219 return buf.toString();
1220 }
1221
1222 private static int lookupString(String string, String[] strings) {
1223 int size = strings.length;
1224
1225 string = string.replace('-', '_');
1226
1227 for (int i = 0; i < size; i++)
1228 if (string.equals(strings[i]))
1229 return i;
1230
1231 if (DBG) {
1232 // if we ever get here, we should probably add the
1233 // value to WifiConfiguration to reflect that it's
1234 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001235 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237
1238 return -1;
1239 }
1240
1241 /**
1242 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1243 * @param netId the integer that identifies the network configuration
1244 * to the supplicant
1245 * @return {@code true} if the operation succeeded
1246 */
1247 public boolean removeNetwork(int netId) {
1248 enforceChangePermission();
1249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 return mWifiStateTracker.removeNetwork(netId);
1251 }
1252
1253 /**
1254 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1255 * @param netId the integer that identifies the network configuration
1256 * to the supplicant
1257 * @param disableOthers if true, disable all other networks.
1258 * @return {@code true} if the operation succeeded
1259 */
1260 public boolean enableNetwork(int netId, boolean disableOthers) {
1261 enforceChangePermission();
1262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 synchronized (mWifiStateTracker) {
Mike Lockwood0900f362009-07-10 17:24:07 -04001264 String ifname = mWifiStateTracker.getInterfaceName();
1265 NetworkUtils.enableInterface(ifname);
1266 boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
1267 if (!result) {
1268 NetworkUtils.disableInterface(ifname);
1269 }
1270 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 }
1273
1274 /**
1275 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1276 * @param netId the integer that identifies the network configuration
1277 * to the supplicant
1278 * @return {@code true} if the operation succeeded
1279 */
1280 public boolean disableNetwork(int netId) {
1281 enforceChangePermission();
1282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 synchronized (mWifiStateTracker) {
1284 return WifiNative.disableNetworkCommand(netId);
1285 }
1286 }
1287
1288 /**
1289 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1290 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1291 */
1292 public WifiInfo getConnectionInfo() {
1293 enforceAccessPermission();
1294 /*
1295 * Make sure we have the latest information, by sending
1296 * a status request to the supplicant.
1297 */
1298 return mWifiStateTracker.requestConnectionInfo();
1299 }
1300
1301 /**
1302 * Return the results of the most recent access point scan, in the form of
1303 * a list of {@link ScanResult} objects.
1304 * @return the list of results
1305 */
1306 public List<ScanResult> getScanResults() {
1307 enforceAccessPermission();
1308 String reply;
1309 synchronized (mWifiStateTracker) {
1310 reply = WifiNative.scanResultsCommand();
1311 }
1312 if (reply == null) {
1313 return null;
1314 }
1315
1316 List<ScanResult> scanList = new ArrayList<ScanResult>();
1317
1318 int lineCount = 0;
1319
1320 int replyLen = reply.length();
1321 // Parse the result string, keeping in mind that the last line does
1322 // not end with a newline.
1323 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1324 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1325 ++lineCount;
1326 /*
1327 * Skip the first line, which is a header
1328 */
1329 if (lineCount == 1) {
1330 lineBeg = lineEnd + 1;
1331 continue;
1332 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001333 if (lineEnd > lineBeg) {
1334 String line = reply.substring(lineBeg, lineEnd);
1335 ScanResult scanResult = parseScanResult(line);
1336 if (scanResult != null) {
1337 scanList.add(scanResult);
1338 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001339 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341 }
1342 lineBeg = lineEnd + 1;
1343 }
1344 }
1345 mWifiStateTracker.setScanResultsList(scanList);
1346 return scanList;
1347 }
1348
1349 /**
1350 * Parse the scan result line passed to us by wpa_supplicant (helper).
1351 * @param line the line to parse
1352 * @return the {@link ScanResult} object
1353 */
1354 private ScanResult parseScanResult(String line) {
1355 ScanResult scanResult = null;
1356 if (line != null) {
1357 /*
1358 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1359 * must synchronized here!
1360 */
1361 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001362 String[] result = scanResultPattern.split(line);
1363 if (3 <= result.length && result.length <= 5) {
1364 String bssid = result[0];
1365 // bssid | frequency | level | flags | ssid
1366 int frequency;
1367 int level;
1368 try {
1369 frequency = Integer.parseInt(result[1]);
1370 level = Integer.parseInt(result[2]);
1371 /* some implementations avoid negative values by adding 256
1372 * so we need to adjust for that here.
1373 */
1374 if (level > 0) level -= 256;
1375 } catch (NumberFormatException e) {
1376 frequency = 0;
1377 level = 0;
1378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
Mike Lockwood1a645052009-06-25 13:01:12 -04001380 /*
1381 * The formatting of the results returned by
1382 * wpa_supplicant is intended to make the fields
1383 * line up nicely when printed,
1384 * not to make them easy to parse. So we have to
1385 * apply some heuristics to figure out which field
1386 * is the SSID and which field is the flags.
1387 */
1388 String ssid;
1389 String flags;
1390 if (result.length == 4) {
1391 if (result[3].charAt(0) == '[') {
1392 flags = result[3];
1393 ssid = "";
1394 } else {
1395 flags = "";
1396 ssid = result[3];
1397 }
1398 } else if (result.length == 5) {
1399 flags = result[3];
1400 ssid = result[4];
1401 } else {
1402 // Here, we must have 3 fields: no flags and ssid
1403 // set
1404 flags = "";
1405 ssid = "";
1406 }
1407
Mike Lockwood00717e22009-08-17 10:09:36 -04001408 // bssid + ssid is the hash key
1409 String key = bssid + ssid;
1410 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001411 if (scanResult != null) {
1412 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001413 scanResult.SSID = ssid;
1414 scanResult.capabilities = flags;
1415 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001416 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 // Do not add scan results that have no SSID set
1418 if (0 < ssid.trim().length()) {
1419 scanResult =
1420 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001421 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001422 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001425 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001426 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001427 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 }
1430 }
1431
1432 return scanResult;
1433 }
1434
1435 /**
1436 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1437 * and construct a {@code WifiConfiguration} that describes the encryption,
1438 * key management, and authenticaion capabilities of the access point.
1439 * @param flags the string returned by wpa_supplicant
1440 * @return the {@link WifiConfiguration} object, filled in
1441 */
1442 WifiConfiguration parseScanFlags(String flags) {
1443 WifiConfiguration config = new WifiConfiguration();
1444
1445 if (flags.length() == 0) {
1446 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1447 }
1448 // ... to be implemented
1449 return config;
1450 }
1451
1452 /**
1453 * Tell the supplicant to persist the current list of configured networks.
1454 * @return {@code true} if the operation succeeded
1455 */
1456 public boolean saveConfiguration() {
1457 boolean result;
1458 enforceChangePermission();
1459 synchronized (mWifiStateTracker) {
1460 result = WifiNative.saveConfigCommand();
1461 if (result && mNeedReconfig) {
1462 mNeedReconfig = false;
1463 result = WifiNative.reloadConfigCommand();
1464
1465 if (result) {
1466 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1467 mContext.sendBroadcast(intent);
1468 }
1469 }
1470 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001471 // Inform the backup manager about a data change
1472 IBackupManager ibm = IBackupManager.Stub.asInterface(
1473 ServiceManager.getService(Context.BACKUP_SERVICE));
1474 if (ibm != null) {
1475 try {
1476 ibm.dataChanged("com.android.providers.settings");
1477 } catch (Exception e) {
1478 // Try again later
1479 }
1480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 return result;
1482 }
1483
1484 /**
1485 * Set the number of radio frequency channels that are allowed to be used
1486 * in the current regulatory domain. This method should be used only
1487 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001488 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 * persisted as a Secure setting.
1490 * @param numChannels the number of allowed channels. Must be greater than 0
1491 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001492 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1494 * {@code numChannels} is outside the valid range.
1495 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001496 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001497 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001498 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 enforceChangePermission();
1500 /*
1501 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1502 * but if Wi-Fi isn't currently enabled, that's not possible, and
1503 * we want to persist the setting anyway,so that it will take
1504 * effect when Wi-Fi does become enabled.
1505 */
1506 boolean found = false;
1507 for (int validChan : sValidRegulatoryChannelCounts) {
1508 if (validChan == numChannels) {
1509 found = true;
1510 break;
1511 }
1512 }
1513 if (!found) {
1514 return false;
1515 }
1516
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001517 if (persist) {
1518 Settings.Secure.putInt(mContext.getContentResolver(),
1519 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1520 numChannels);
1521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 mWifiStateTracker.setNumAllowedChannels(numChannels);
1523 return true;
1524 }
1525
1526 /**
1527 * Return the number of frequency channels that are allowed
1528 * to be used in the current regulatory domain.
1529 * @return the number of allowed channels, or {@code -1} if an error occurs
1530 */
1531 public int getNumAllowedChannels() {
1532 int numChannels;
1533
1534 enforceAccessPermission();
1535 synchronized (mWifiStateTracker) {
1536 /*
1537 * If we can't get the value from the driver (e.g., because
1538 * Wi-Fi is not currently enabled), get the value from
1539 * Settings.
1540 */
1541 numChannels = WifiNative.getNumAllowedChannelsCommand();
1542 if (numChannels < 0) {
1543 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1544 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1545 -1);
1546 }
1547 }
1548 return numChannels;
1549 }
1550
1551 /**
1552 * Return the list of valid values for the number of allowed radio channels
1553 * for various regulatory domains.
1554 * @return the list of channel counts
1555 */
1556 public int[] getValidChannelCounts() {
1557 enforceAccessPermission();
1558 return sValidRegulatoryChannelCounts;
1559 }
1560
1561 /**
1562 * Return the DHCP-assigned addresses from the last successful DHCP request,
1563 * if any.
1564 * @return the DHCP information
1565 */
1566 public DhcpInfo getDhcpInfo() {
1567 enforceAccessPermission();
1568 return mWifiStateTracker.getDhcpInfo();
1569 }
1570
1571 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1572 @Override
1573 public void onReceive(Context context, Intent intent) {
1574 String action = intent.getAction();
1575
Doug Zongker43866e02010-01-07 12:09:54 -08001576 long idleMillis =
1577 Settings.Secure.getLong(mContext.getContentResolver(),
1578 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001580 Settings.System.getInt(mContext.getContentResolver(),
1581 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001583 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mAlarmManager.cancel(mIdleIntent);
1585 mDeviceIdle = false;
1586 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001587 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001591 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 /*
1593 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1594 * AND the "stay on while plugged in" setting doesn't match the
1595 * current power conditions (i.e, not plugged in, plugged in to USB,
1596 * or plugged in to AC).
1597 */
1598 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001599 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1600 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001601 // we used to go to sleep immediately, but this caused some race conditions
1602 // we don't have time to track down for this release. Delay instead, but not
1603 // as long as we would if connected (below)
1604 // TODO - fix the race conditions and switch back to the immediate turn-off
1605 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001606 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001607 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1608 // // do not keep Wifi awake when screen is off if Wifi is not associated
1609 // mDeviceIdle = true;
1610 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001611 } else {
1612 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001613 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001614 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617 /* we can return now -- there's nothing to do until we get the idle intent back */
1618 return;
1619 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 mDeviceIdle = true;
1622 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1623 /*
1624 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1625 * AND we are transitioning from a state in which the device was supposed
1626 * to stay awake to a state in which it is not supposed to stay awake.
1627 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1628 * the already-set timer.
1629 */
1630 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001631 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1633 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1634 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001635 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1637 mPluggedType = pluggedType;
1638 return;
1639 }
1640 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001641 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001642 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1643 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1644 boolean isBluetoothPlaying = false;
1645 for (BluetoothDevice sink : sinks) {
1646 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1647 isBluetoothPlaying = true;
1648 }
1649 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001650 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 } else {
1653 return;
1654 }
1655
1656 updateWifiState();
1657 }
1658
1659 /**
1660 * Determines whether the Wi-Fi chipset should stay awake or be put to
1661 * sleep. Looks at the setting for the sleep policy and the current
1662 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001663 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * @see #shouldDeviceStayAwake(int, int)
1665 */
1666 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1667 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1668 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1669
1670 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1671 // Never sleep
1672 return true;
1673 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1674 (pluggedType != 0)) {
1675 // Never sleep while plugged, and we're plugged
1676 return true;
1677 } else {
1678 // Default
1679 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1680 }
1681 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /**
1684 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1685 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1686 * of {@code 0} isn't really a plugged type, but rather an indication that the
1687 * device isn't plugged in at all, there is no bit value corresponding to a
1688 * {@code pluggedType} value of {@code 0}. That is why we shift by
1689 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1690 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1691 * keep the device (and hence Wi-Fi) awake.
1692 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1693 * being made
1694 * @return {@code true} if {@code pluggedType} indicates that the device is
1695 * supposed to stay awake, {@code false} otherwise.
1696 */
1697 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1698 return (stayAwakeConditions & pluggedType) != 0;
1699 }
1700 };
1701
Dianne Hackborn617f8772009-03-31 15:04:46 -07001702 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 Message msg = Message.obtain(mWifiHandler,
1704 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001705 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 msg.sendToTarget();
1707 }
1708
1709 private void sendStartMessage(boolean scanOnlyMode) {
1710 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1711 }
1712
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001713 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1714 Message.obtain(mWifiHandler,
1715 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
1716 0, uid, wifiConfig).sendToTarget();
1717 }
1718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001720 // send a message so it's all serialized
1721 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1722 }
1723
1724 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001726 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 boolean lockHeld = mLocks.hasLocks();
1728 int strongestLockMode;
1729 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1730 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1731 if (mDeviceIdle && lockHeld) {
1732 strongestLockMode = mLocks.getStrongestLockMode();
1733 } else {
1734 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1735 }
1736
1737 synchronized (mWifiHandler) {
1738 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1739 return;
1740 }
1741 if (wifiShouldBeEnabled) {
1742 if (wifiShouldBeStarted) {
1743 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001744 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 sWakeLock.acquire();
1746 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1747 } else {
1748 int wakeLockTimeout =
1749 Settings.Secure.getInt(
1750 mContext.getContentResolver(),
1751 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1752 DEFAULT_WAKELOCK_TIMEOUT);
1753 /*
1754 * The following wakelock is held in order to ensure
1755 * that the connectivity manager has time to fail over
1756 * to the mobile data network. The connectivity manager
1757 * releases it once mobile data connectivity has been
1758 * established. If connectivity cannot be established,
1759 * the wakelock is released after wakeLockTimeout
1760 * milliseconds have elapsed.
1761 */
1762 sDriverStopWakeLock.acquire();
1763 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1764 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1765 }
1766 } else {
1767 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001768 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 }
1771 }
1772
1773 private void registerForBroadcasts() {
1774 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1776 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1777 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1778 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001779 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 mContext.registerReceiver(mReceiver, intentFilter);
1781 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 private boolean isAirplaneSensitive() {
1784 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1785 Settings.System.AIRPLANE_MODE_RADIOS);
1786 return airplaneModeRadios == null
1787 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1788 }
1789
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001790 private boolean isAirplaneToggleable() {
1791 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1792 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1793 return toggleableRadios != null
1794 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1795 }
1796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 /**
1798 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1799 * currently on.
1800 * @return {@code true} if airplane mode is on.
1801 */
1802 private boolean isAirplaneModeOn() {
1803 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1804 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1805 }
1806
1807 /**
1808 * Handler that allows posting to the WifiThread.
1809 */
1810 private class WifiHandler extends Handler {
1811 public WifiHandler(Looper looper) {
1812 super(looper);
1813 }
1814
1815 @Override
1816 public void handleMessage(Message msg) {
1817 switch (msg.what) {
1818
1819 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001820 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 sWakeLock.release();
1822 break;
1823
1824 case MESSAGE_START_WIFI:
1825 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1826 mWifiStateTracker.restart();
1827 sWakeLock.release();
1828 break;
1829
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001830 case MESSAGE_UPDATE_STATE:
1831 doUpdateWifiState();
1832 break;
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 case MESSAGE_DISABLE_WIFI:
1835 // a non-zero msg.arg1 value means the "enabled" setting
1836 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001837 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 sWakeLock.release();
1839 break;
1840
1841 case MESSAGE_STOP_WIFI:
1842 mWifiStateTracker.disconnectAndStop();
1843 // don't release wakelock
1844 break;
1845
1846 case MESSAGE_RELEASE_WAKELOCK:
1847 synchronized (sDriverStopWakeLock) {
1848 if (sDriverStopWakeLock.isHeld()) {
1849 sDriverStopWakeLock.release();
1850 }
1851 }
1852 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001853
1854 case MESSAGE_START_ACCESS_POINT:
1855 setWifiApEnabledBlocking(true,
1856 msg.arg1 == 1,
1857 msg.arg2,
1858 (WifiConfiguration) msg.obj);
1859 break;
1860
1861 case MESSAGE_STOP_ACCESS_POINT:
1862 setWifiApEnabledBlocking(false,
1863 msg.arg1 == 1,
1864 msg.arg2,
1865 (WifiConfiguration) msg.obj);
1866 sWakeLock.release();
1867 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 }
1869 }
1870 }
1871
1872 @Override
1873 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1874 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1875 != PackageManager.PERMISSION_GRANTED) {
1876 pw.println("Permission Denial: can't dump WifiService from from pid="
1877 + Binder.getCallingPid()
1878 + ", uid=" + Binder.getCallingUid());
1879 return;
1880 }
1881 pw.println("Wi-Fi is " + stateName(mWifiState));
1882 pw.println("Stay-awake conditions: " +
1883 Settings.System.getInt(mContext.getContentResolver(),
1884 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1885 pw.println();
1886
1887 pw.println("Internal state:");
1888 pw.println(mWifiStateTracker);
1889 pw.println();
1890 pw.println("Latest scan results:");
1891 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1892 if (scanResults != null && scanResults.size() != 0) {
1893 pw.println(" BSSID Frequency RSSI Flags SSID");
1894 for (ScanResult r : scanResults) {
1895 pw.printf(" %17s %9d %5d %-16s %s%n",
1896 r.BSSID,
1897 r.frequency,
1898 r.level,
1899 r.capabilities,
1900 r.SSID == null ? "" : r.SSID);
1901 }
1902 }
1903 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001904 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1905 mScanLocksAcquired + " scan");
1906 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1907 mScanLocksReleased + " scan");
1908 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 pw.println("Locks held:");
1910 mLocks.dump(pw);
1911 }
1912
1913 private static String stateName(int wifiState) {
1914 switch (wifiState) {
1915 case WIFI_STATE_DISABLING:
1916 return "disabling";
1917 case WIFI_STATE_DISABLED:
1918 return "disabled";
1919 case WIFI_STATE_ENABLING:
1920 return "enabling";
1921 case WIFI_STATE_ENABLED:
1922 return "enabled";
1923 case WIFI_STATE_UNKNOWN:
1924 return "unknown state";
1925 default:
1926 return "[invalid state]";
1927 }
1928 }
1929
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001930 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001932 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
1935 public void binderDied() {
1936 synchronized (mLocks) {
1937 releaseWifiLockLocked(mBinder);
1938 }
1939 }
1940
1941 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001942 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944 }
1945
1946 private class LockList {
1947 private List<WifiLock> mList;
1948
1949 private LockList() {
1950 mList = new ArrayList<WifiLock>();
1951 }
1952
1953 private synchronized boolean hasLocks() {
1954 return !mList.isEmpty();
1955 }
1956
1957 private synchronized int getStrongestLockMode() {
1958 if (mList.isEmpty()) {
1959 return WifiManager.WIFI_MODE_FULL;
1960 }
1961 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001962 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 return WifiManager.WIFI_MODE_FULL;
1964 }
1965 }
1966 return WifiManager.WIFI_MODE_SCAN_ONLY;
1967 }
1968
1969 private void addLock(WifiLock lock) {
1970 if (findLockByBinder(lock.mBinder) < 0) {
1971 mList.add(lock);
1972 }
1973 }
1974
1975 private WifiLock removeLock(IBinder binder) {
1976 int index = findLockByBinder(binder);
1977 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001978 WifiLock ret = mList.remove(index);
1979 ret.unlinkDeathRecipient();
1980 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 } else {
1982 return null;
1983 }
1984 }
1985
1986 private int findLockByBinder(IBinder binder) {
1987 int size = mList.size();
1988 for (int i = size - 1; i >= 0; i--)
1989 if (mList.get(i).mBinder == binder)
1990 return i;
1991 return -1;
1992 }
1993
1994 private void dump(PrintWriter pw) {
1995 for (WifiLock l : mList) {
1996 pw.print(" ");
1997 pw.println(l);
1998 }
1999 }
2000 }
2001
2002 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
2003 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2004 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
2005 return false;
2006 }
2007 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
2008 synchronized (mLocks) {
2009 return acquireWifiLockLocked(wifiLock);
2010 }
2011 }
2012
2013 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002014 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002017
The Android Open Source Project10592532009-03-18 17:39:46 -07002018 int uid = Binder.getCallingUid();
2019 long ident = Binder.clearCallingIdentity();
2020 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002021 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002022 case WifiManager.WIFI_MODE_FULL:
2023 ++mFullLocksAcquired;
2024 mBatteryStats.noteFullWifiLockAcquired(uid);
2025 break;
2026 case WifiManager.WIFI_MODE_SCAN_ONLY:
2027 ++mScanLocksAcquired;
2028 mBatteryStats.noteScanWifiLockAcquired(uid);
2029 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002030 }
2031 } catch (RemoteException e) {
2032 } finally {
2033 Binder.restoreCallingIdentity(ident);
2034 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 updateWifiState();
2037 return true;
2038 }
2039
2040 public boolean releaseWifiLock(IBinder lock) {
2041 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2042 synchronized (mLocks) {
2043 return releaseWifiLockLocked(lock);
2044 }
2045 }
2046
2047 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002048 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002049
The Android Open Source Project10592532009-03-18 17:39:46 -07002050 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002051
Joe Onorato8a9b2202010-02-26 18:56:32 -08002052 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002053
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002054 hadLock = (wifiLock != null);
2055
2056 if (hadLock) {
2057 int uid = Binder.getCallingUid();
2058 long ident = Binder.clearCallingIdentity();
2059 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002060 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002061 case WifiManager.WIFI_MODE_FULL:
2062 ++mFullLocksReleased;
2063 mBatteryStats.noteFullWifiLockReleased(uid);
2064 break;
2065 case WifiManager.WIFI_MODE_SCAN_ONLY:
2066 ++mScanLocksReleased;
2067 mBatteryStats.noteScanWifiLockReleased(uid);
2068 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002069 }
2070 } catch (RemoteException e) {
2071 } finally {
2072 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002073 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002074 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002075 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002077 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002079
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002080 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002081 implements IBinder.DeathRecipient {
2082 String mTag;
2083 int mMode;
2084 IBinder mBinder;
2085
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002086 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002087 super();
2088 mTag = tag;
2089 mMode = mode;
2090 mBinder = binder;
2091 try {
2092 mBinder.linkToDeath(this, 0);
2093 } catch (RemoteException e) {
2094 binderDied();
2095 }
2096 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002097
2098 void unlinkDeathRecipient() {
2099 mBinder.unlinkToDeath(this, 0);
2100 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002101 }
2102
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002103 private class Multicaster extends DeathRecipient {
2104 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002105 super(Binder.getCallingUid(), tag, binder);
2106 }
2107
2108 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002109 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002110 synchronized (mMulticasters) {
2111 int i = mMulticasters.indexOf(this);
2112 if (i != -1) {
2113 removeMulticasterLocked(i, mMode);
2114 }
2115 }
2116 }
2117
2118 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002119 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002120 }
2121
2122 public int getUid() {
2123 return mMode;
2124 }
2125 }
2126
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002127 public void initializeMulticastFiltering() {
2128 enforceMulticastChangePermission();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002129 synchronized (mMulticasters) {
2130 // if anybody had requested filters be off, leave off
2131 if (mMulticasters.size() != 0) {
2132 return;
2133 } else {
Irfan Sheriff7aac5542009-12-22 21:42:17 -08002134 synchronized (mWifiStateTracker) {
2135 WifiNative.startPacketFiltering();
2136 }
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002137 }
2138 }
2139 }
2140
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002141 public void acquireMulticastLock(IBinder binder, String tag) {
2142 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002143
2144 synchronized (mMulticasters) {
2145 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002146 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002147 // Note that we could call stopPacketFiltering only when
2148 // our new size == 1 (first call), but this function won't
2149 // be called often and by making the stopPacket call each
2150 // time we're less fragile and self-healing.
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04002151 synchronized (mWifiStateTracker) {
2152 WifiNative.stopPacketFiltering();
2153 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002154 }
2155
2156 int uid = Binder.getCallingUid();
2157 Long ident = Binder.clearCallingIdentity();
2158 try {
2159 mBatteryStats.noteWifiMulticastEnabled(uid);
2160 } catch (RemoteException e) {
2161 } finally {
2162 Binder.restoreCallingIdentity(ident);
2163 }
2164 }
2165
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002166 public void releaseMulticastLock() {
2167 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002168
2169 int uid = Binder.getCallingUid();
2170 synchronized (mMulticasters) {
2171 mMulticastDisabled++;
2172 int size = mMulticasters.size();
2173 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002174 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002175 if ((m != null) && (m.getUid() == uid)) {
2176 removeMulticasterLocked(i, uid);
2177 }
2178 }
2179 }
2180 }
2181
2182 private void removeMulticasterLocked(int i, int uid)
2183 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002184 Multicaster removed = mMulticasters.remove(i);
2185 if (removed != null) {
2186 removed.unlinkDeathRecipient();
2187 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002188 if (mMulticasters.size() == 0) {
Zheng BaoZhong8d1668d2009-08-05 08:57:49 -04002189 synchronized (mWifiStateTracker) {
2190 WifiNative.startPacketFiltering();
2191 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002192 }
2193
2194 Long ident = Binder.clearCallingIdentity();
2195 try {
2196 mBatteryStats.noteWifiMulticastDisabled(uid);
2197 } catch (RemoteException e) {
2198 } finally {
2199 Binder.restoreCallingIdentity(ident);
2200 }
2201 }
2202
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002203 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002204 enforceAccessPermission();
2205
2206 synchronized (mMulticasters) {
2207 return (mMulticasters.size() > 0);
2208 }
2209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210}