blob: 599eec5c30f4dc76863e43c873f63a7498710468 [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;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080099 private int mWifiApState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
101 private AlarmManager mAlarmManager;
102 private PendingIntent mIdleIntent;
103 private static final int IDLE_REQUEST = 0;
104 private boolean mScreenOff;
105 private boolean mDeviceIdle;
106 private int mPluggedType;
107
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700108 // true if the user enabled Wifi while in airplane mode
109 private boolean mAirplaneModeOverwridden;
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700112 // some wifi lock statistics
113 private int mFullLocksAcquired;
114 private int mFullLocksReleased;
115 private int mScanLocksAcquired;
116 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700117
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700118 private final List<Multicaster> mMulticasters =
119 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700120 private int mMulticastEnabled;
121 private int mMulticastDisabled;
122
The Android Open Source Project10592532009-03-18 17:39:46 -0700123 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800124
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800125 private INetworkManagementService nwService;
126 ConnectivityManager mCm;
Irfan Sheriff7b009782010-03-11 16:37:45 -0800127 private WifiWatchdogService mWifiWatchdogService = null;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800128 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
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800219 mWifiStateTracker.setWifiState(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
222 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
223 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
224 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
225
226 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
227 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
228 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
229 mWifiStateTracker.setReleaseWakeLockCallback(
230 new Runnable() {
231 public void run() {
232 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
233 synchronized (sDriverStopWakeLock) {
234 if (sDriverStopWakeLock.isHeld()) {
235 sDriverStopWakeLock.release();
236 }
237 }
238 }
239 }
240 );
241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 mContext.registerReceiver(
243 new BroadcastReceiver() {
244 @Override
245 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700246 // clear our flag indicating the user has overwridden airplane mode
247 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 updateWifiState();
249 }
250 },
251 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
252
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800253 mContext.registerReceiver(
254 new BroadcastReceiver() {
255 @Override
256 public void onReceive(Context context, Intent intent) {
257
258 ArrayList<String> available = intent.getStringArrayListExtra(
259 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
260 ArrayList<String> active = intent.getStringArrayListExtra(
261 ConnectivityManager.EXTRA_ACTIVE_TETHER);
262 updateTetherState(available, active);
263
264 }
265 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff7b009782010-03-11 16:37:45 -0800266 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800267
Irfan Sheriff7b009782010-03-11 16:37:45 -0800268 /**
269 * Check if Wi-Fi needs to be enabled and start
270 * if needed
271 */
272 public void startWifi() {
273 boolean wifiEnabled = getPersistedWifiEnabled();
274 boolean wifiAPEnabled = wifiEnabled ? false : getPersistedWifiApEnabled();
275 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
276 (wifiEnabled ? "enabled" : "disabled"));
Dianne Hackborn617f8772009-03-31 15:04:46 -0700277 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800278 setWifiApEnabledBlocking(wifiAPEnabled, true, Process.myUid(), null);
279 }
280
281 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
282
283 boolean wifiTethered = false;
284 boolean wifiAvailable = false;
285
286 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
287 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
288
289 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
290 mWifiRegexs = mCm.getTetherableWifiRegexs();
291
292 for (String intf : available) {
293 for (String regex : mWifiRegexs) {
294 if (intf.matches(regex)) {
295
296 InterfaceConfiguration ifcg = null;
297 try {
298 ifcg = service.getInterfaceConfig(intf);
299 if (ifcg != null) {
300 /* IP/netmask: 169.254.2.1/255.255.255.0 */
301 ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
302 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
303 ifcg.interfaceFlags = "up";
304
305 service.setInterfaceConfig(intf, ifcg);
306 }
307 } catch (Exception e) {
308 /**
309 * TODO: Add broadcast to indicate tether failed
310 */
311 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
312 return;
313 }
314
315 /**
316 * TODO: Add broadcast to indicate tether failed
317 */
318 if(mCm.tether(intf) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
319 Slog.d(TAG, "Tethered "+intf);
320 } else {
321 Slog.e(TAG, "Error tethering "+intf);
322 }
323 break;
324 }
325 }
326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 private boolean getPersistedWifiEnabled() {
330 final ContentResolver cr = mContext.getContentResolver();
331 try {
332 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
333 } catch (Settings.SettingNotFoundException e) {
334 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
335 return false;
336 }
337 }
338
339 private void persistWifiEnabled(boolean enabled) {
340 final ContentResolver cr = mContext.getContentResolver();
341 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
342 }
343
344 NetworkStateTracker getNetworkStateTracker() {
345 return mWifiStateTracker;
346 }
347
348 /**
349 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
350 * @return {@code true} if the operation succeeds
351 */
352 public boolean pingSupplicant() {
353 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800354
355 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
357
358 /**
359 * see {@link android.net.wifi.WifiManager#startScan()}
360 * @return {@code true} if the operation succeeds
361 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400362 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800364
365 switch (mWifiStateTracker.getSupplicantState()) {
366 case DISCONNECTED:
367 case INACTIVE:
368 case SCANNING:
369 case DORMANT:
370 break;
371 default:
372 mWifiStateTracker.setScanResultHandling(
373 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
374 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800376 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
378
379 /**
380 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
381 * @param enable {@code true} to enable, {@code false} to disable.
382 * @return {@code true} if the enable/disable operation was
383 * started or is already in the queue.
384 */
385 public boolean setWifiEnabled(boolean enable) {
386 enforceChangePermission();
387 if (mWifiHandler == null) return false;
388
389 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700390 // caller may not have WAKE_LOCK permission - it's not required here
391 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700393 Binder.restoreCallingIdentity(ident);
394
Dianne Hackborn617f8772009-03-31 15:04:46 -0700395 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700396 // set a flag if the user is enabling Wifi while in airplane mode
397 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700398 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 }
400
401 return true;
402 }
403
404 /**
405 * Enables/disables Wi-Fi synchronously.
406 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
407 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700408 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * @return {@code true} if the operation succeeds (or if the existing state
410 * is the same as the requested state)
411 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700412 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800414 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800416 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 return true;
418 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700419 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 return false;
421 }
422
Irfan Sheriffcd770372010-01-08 09:36:04 -0800423 /**
424 * Multiple calls to unregisterReceiver() cause exception and a system crash.
425 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
426 * disable wifi at the same time.
427 * Avoid doing a disable when the current Wifi state is UNKNOWN
428 * TODO: Handle driver load fail and supplicant lost as seperate states
429 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800430 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800431 return false;
432 }
433
Dianne Hackborn617f8772009-03-31 15:04:46 -0700434 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800436 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
437 setWifiApEnabledBlocking(false, true, Process.myUid(), null);
438 }
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800441 if (!mWifiStateTracker.loadDriver()) {
442 Slog.e(TAG, "Failed to load Wi-Fi driver.");
443 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
444 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800446 if (!mWifiStateTracker.startSupplicant()) {
447 mWifiStateTracker.unloadDriver();
448 Slog.e(TAG, "Failed to start supplicant daemon.");
449 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
450 return false;
451 }
452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 registerForBroadcasts();
454 mWifiStateTracker.startEventLoop();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 } else {
457
458 mContext.unregisterReceiver(mReceiver);
459 // Remove notification (it will no-op if it isn't visible)
460 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
461
462 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800463
464 if (!mWifiStateTracker.stopSupplicant()) {
465 Slog.e(TAG, "Failed to stop supplicant daemon.");
466 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
467 failedToStopSupplicantOrUnloadDriver = true;
468 }
469
470 /**
471 * Reset connections and disable interface
472 * before we unload the driver
473 */
474 mWifiStateTracker.resetConnections(true);
475
476 if (!mWifiStateTracker.unloadDriver()) {
477 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
478 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700479 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 failedToStopSupplicantOrUnloadDriver = true;
481 }
482 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 if (failedToStopSupplicantOrUnloadDriver) {
485 return false;
486 }
487 }
488
489 // Success!
490
491 if (persist) {
492 persistWifiEnabled(enable);
493 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700494 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 return true;
496 }
497
Dianne Hackborn617f8772009-03-31 15:04:46 -0700498 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800499 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500
The Android Open Source Project10592532009-03-18 17:39:46 -0700501 long ident = Binder.clearCallingIdentity();
502 try {
503 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700504 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700505 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700506 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700507 }
508 } catch (RemoteException e) {
509 } finally {
510 Binder.restoreCallingIdentity(ident);
511 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800514 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515
516 // Broadcast
517 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
518 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
519 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
520 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
521 mContext.sendStickyBroadcast(intent);
522 }
523
524 private void enforceAccessPermission() {
525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
526 "WifiService");
527 }
528
529 private void enforceChangePermission() {
530 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
531 "WifiService");
532
533 }
534
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700535 private void enforceMulticastChangePermission() {
536 mContext.enforceCallingOrSelfPermission(
537 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
538 "WifiService");
539 }
540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 /**
542 * see {@link WifiManager#getWifiState()}
543 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
544 * {@link WifiManager#WIFI_STATE_DISABLING},
545 * {@link WifiManager#WIFI_STATE_ENABLED},
546 * {@link WifiManager#WIFI_STATE_ENABLING},
547 * {@link WifiManager#WIFI_STATE_UNKNOWN}
548 */
549 public int getWifiEnabledState() {
550 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800551 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 }
553
554 /**
555 * see {@link android.net.wifi.WifiManager#disconnect()}
556 * @return {@code true} if the operation succeeds
557 */
558 public boolean disconnect() {
559 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800560
561 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
563
564 /**
565 * see {@link android.net.wifi.WifiManager#reconnect()}
566 * @return {@code true} if the operation succeeds
567 */
568 public boolean reconnect() {
569 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800570
571 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573
574 /**
575 * see {@link android.net.wifi.WifiManager#reassociate()}
576 * @return {@code true} if the operation succeeds
577 */
578 public boolean reassociate() {
579 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800580
581 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800584 private boolean getPersistedWifiApEnabled() {
585 final ContentResolver cr = mContext.getContentResolver();
586 try {
587 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_ON) == 1;
588 } catch (Settings.SettingNotFoundException e) {
589 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, 0);
590 return false;
591 }
592 }
593
594 private void persistWifiApEnabled(boolean enabled) {
595 final ContentResolver cr = mContext.getContentResolver();
596 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, enabled ? 1 : 0);
597 }
598
599 /**
600 * see {@link android.net.wifi.WifiManager#startAccessPoint(WifiConfiguration)}
601 * @param wifiConfig SSID, security and channel details as
602 * part of WifiConfiguration
603 * @return {@code true} if the start operation was
604 * started or is already in the queue.
605 */
606 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
607 enforceChangePermission();
608 if (mWifiHandler == null) return false;
609
610 synchronized (mWifiHandler) {
611
612 long ident = Binder.clearCallingIdentity();
613 sWakeLock.acquire();
614 Binder.restoreCallingIdentity(ident);
615
616 mLastEnableUid = Binder.getCallingUid();
617
618 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
619 }
620
621 return true;
622 }
623
624 /**
625 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
626 * and soft access point configured as a single operation.
627 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
628 * @param persist {@code true} if the setting should be persisted.
629 * @param uid The UID of the process making the request.
630 * @param config The WifiConfiguration for AP
631 * @return {@code true} if the operation succeeds (or if the existing state
632 * is the same as the requested state)
633 */
634 /**
635 * TODO: persist needs to go away in WifiService
636 * This will affect all persist related functions
637 * for Access Point
638 */
639 private boolean setWifiApEnabledBlocking(boolean enable,
640 boolean persist, int uid, WifiConfiguration wifiConfig) {
641 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
642
643 if (mWifiApState == eventualWifiApState) {
644 return true;
645 }
646
647 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING : WIFI_AP_STATE_DISABLING, uid);
648
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800649 if (enable && (mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED)) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800650 setWifiEnabledBlocking(false, true, Process.myUid());
651 }
652
653 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800654 if (!mWifiStateTracker.loadDriver()) {
655 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
656 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
657 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800658 }
659
660 try {
661 nwService.startAccessPoint();
662 } catch(Exception e) {
663 Slog.e(TAG, "Exception in startAccessPoint()");
664 }
665
666 } else {
667
668 try {
669 nwService.stopAccessPoint();
670 } catch(Exception e) {
671 Slog.e(TAG, "Exception in stopAccessPoint()");
672 }
673
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800674 if (!mWifiStateTracker.unloadDriver()) {
675 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
676 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
677 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800678 }
679 }
680
681 // Success!
682 if (persist) {
683 persistWifiApEnabled(enable);
684 }
685 setWifiApEnabledState(eventualWifiApState, uid);
686 return true;
687 }
688
689 /**
690 * see {@link WifiManager#getWifiApState()}
691 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
692 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
693 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
694 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
695 * {@link WifiManager#WIFI_AP_STATE_FAILED}
696 */
697 public int getWifiApEnabledState() {
698 enforceAccessPermission();
699 return mWifiApState;
700 }
701
702 private void setWifiApEnabledState(int wifiAPState, int uid) {
703 final int previousWifiApState = mWifiApState;
704
705 long ident = Binder.clearCallingIdentity();
706 try {
707 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
708 mBatteryStats.noteWifiOn(uid);
709 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
710 mBatteryStats.noteWifiOff(uid);
711 }
712 } catch (RemoteException e) {
713 } finally {
714 Binder.restoreCallingIdentity(ident);
715 }
716
717 // Update state
718 mWifiApState = wifiAPState;
719
720 // Broadcast
721 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
722 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
723 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
724 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
725 mContext.sendStickyBroadcast(intent);
726 }
727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 /**
729 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
730 * @return the list of configured networks
731 */
732 public List<WifiConfiguration> getConfiguredNetworks() {
733 enforceAccessPermission();
734 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 /*
737 * We don't cache the list, because we want to allow
738 * for the possibility that the configuration file
739 * has been modified through some external means,
740 * such as the wpa_cli command line program.
741 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800742 listStr = mWifiStateTracker.listNetworks();
743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 List<WifiConfiguration> networks =
745 new ArrayList<WifiConfiguration>();
746 if (listStr == null)
747 return networks;
748
749 String[] lines = listStr.split("\n");
750 // Skip the first line, which is a header
751 for (int i = 1; i < lines.length; i++) {
752 String[] result = lines[i].split("\t");
753 // network-id | ssid | bssid | flags
754 WifiConfiguration config = new WifiConfiguration();
755 try {
756 config.networkId = Integer.parseInt(result[0]);
757 } catch(NumberFormatException e) {
758 continue;
759 }
760 if (result.length > 3) {
761 if (result[3].indexOf("[CURRENT]") != -1)
762 config.status = WifiConfiguration.Status.CURRENT;
763 else if (result[3].indexOf("[DISABLED]") != -1)
764 config.status = WifiConfiguration.Status.DISABLED;
765 else
766 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800767 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800770 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 networks.add(config);
772 }
773
774 return networks;
775 }
776
777 /**
778 * Read the variables from the supplicant daemon that are needed to
779 * fill in the WifiConfiguration object.
780 * <p/>
781 * The caller must hold the synchronization monitor.
782 * @param config the {@link WifiConfiguration} object to be filled in.
783 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800784 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785
786 int netId = config.networkId;
787 if (netId < 0)
788 return;
789
790 /*
791 * TODO: maybe should have a native method that takes an array of
792 * variable names and returns an array of values. But we'd still
793 * be doing a round trip to the supplicant daemon for each variable.
794 */
795 String value;
796
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800797 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800799 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 } else {
801 config.SSID = null;
802 }
803
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800804 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 if (!TextUtils.isEmpty(value)) {
806 config.BSSID = value;
807 } else {
808 config.BSSID = null;
809 }
810
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800811 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 config.priority = -1;
813 if (!TextUtils.isEmpty(value)) {
814 try {
815 config.priority = Integer.parseInt(value);
816 } catch (NumberFormatException ignore) {
817 }
818 }
819
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800820 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 config.hiddenSSID = false;
822 if (!TextUtils.isEmpty(value)) {
823 try {
824 config.hiddenSSID = Integer.parseInt(value) != 0;
825 } catch (NumberFormatException ignore) {
826 }
827 }
828
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800829 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 config.wepTxKeyIndex = -1;
831 if (!TextUtils.isEmpty(value)) {
832 try {
833 config.wepTxKeyIndex = Integer.parseInt(value);
834 } catch (NumberFormatException ignore) {
835 }
836 }
837
838 /*
839 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
840 * just a "*" if the key is set, or the null string otherwise.
841 */
842 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800843 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 if (!TextUtils.isEmpty(value)) {
845 config.wepKeys[i] = value;
846 } else {
847 config.wepKeys[i] = null;
848 }
849 }
850
851 /*
852 * Get the private shared key. Note that the actual keys are not passed back,
853 * just a "*" if the key is set, or the null string otherwise.
854 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800855 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 if (!TextUtils.isEmpty(value)) {
857 config.preSharedKey = value;
858 } else {
859 config.preSharedKey = null;
860 }
861
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800862 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 WifiConfiguration.Protocol.varName);
864 if (!TextUtils.isEmpty(value)) {
865 String vals[] = value.split(" ");
866 for (String val : vals) {
867 int index =
868 lookupString(val, WifiConfiguration.Protocol.strings);
869 if (0 <= index) {
870 config.allowedProtocols.set(index);
871 }
872 }
873 }
874
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800875 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 WifiConfiguration.KeyMgmt.varName);
877 if (!TextUtils.isEmpty(value)) {
878 String vals[] = value.split(" ");
879 for (String val : vals) {
880 int index =
881 lookupString(val, WifiConfiguration.KeyMgmt.strings);
882 if (0 <= index) {
883 config.allowedKeyManagement.set(index);
884 }
885 }
886 }
887
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800888 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 WifiConfiguration.AuthAlgorithm.varName);
890 if (!TextUtils.isEmpty(value)) {
891 String vals[] = value.split(" ");
892 for (String val : vals) {
893 int index =
894 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
895 if (0 <= index) {
896 config.allowedAuthAlgorithms.set(index);
897 }
898 }
899 }
900
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800901 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 WifiConfiguration.PairwiseCipher.varName);
903 if (!TextUtils.isEmpty(value)) {
904 String vals[] = value.split(" ");
905 for (String val : vals) {
906 int index =
907 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
908 if (0 <= index) {
909 config.allowedPairwiseCiphers.set(index);
910 }
911 }
912 }
913
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800914 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 WifiConfiguration.GroupCipher.varName);
916 if (!TextUtils.isEmpty(value)) {
917 String vals[] = value.split(" ");
918 for (String val : vals) {
919 int index =
920 lookupString(val, WifiConfiguration.GroupCipher.strings);
921 if (0 <= index) {
922 config.allowedGroupCiphers.set(index);
923 }
924 }
925 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800926
927 for (WifiConfiguration.EnterpriseField field :
928 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800929 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800930 field.varName());
931 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800932 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800933 field.setValue(value);
934 }
935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800938 private static String removeDoubleQuotes(String string) {
939 if (string.length() <= 2) return "";
940 return string.substring(1, string.length() - 1);
941 }
942
943 private static String convertToQuotedString(String string) {
944 return "\"" + string + "\"";
945 }
946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 /**
948 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
949 * @return the supplicant-assigned identifier for the new or updated
950 * network if the operation succeeds, or {@code -1} if it fails
951 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800952 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 /*
956 * If the supplied networkId is -1, we create a new empty
957 * network configuration. Otherwise, the networkId should
958 * refer to an existing configuration.
959 */
960 int netId = config.networkId;
961 boolean newNetwork = netId == -1;
Irfan Sheriff44113ba32010-03-16 14:54:07 -0700962 boolean doReconfig = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800964 synchronized (mWifiStateTracker) {
965 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800966 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800967 if (netId < 0) {
968 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800969 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800970 }
971 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800973 doReconfig = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800975 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800978 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 /*
980 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800981 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 * will fail, so we don't bother to make a separate check
983 * for the validity of the ID up front.
984 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800986 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800987 netId,
988 WifiConfiguration.ssidVarName,
989 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800991 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 break setVariables;
994 }
995
996 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800997 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800998 netId,
999 WifiConfiguration.bssidVarName,
1000 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001002 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004 break setVariables;
1005 }
1006
1007 String allowedKeyManagementString =
1008 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1009 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001010 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001011 netId,
1012 WifiConfiguration.KeyMgmt.varName,
1013 allowedKeyManagementString)) {
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 key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001016 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018 break setVariables;
1019 }
1020
1021 String allowedProtocolsString =
1022 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1023 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001024 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001025 netId,
1026 WifiConfiguration.Protocol.varName,
1027 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001029 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001030 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032 break setVariables;
1033 }
1034
1035 String allowedAuthAlgorithmsString =
1036 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1037 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001038 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001039 netId,
1040 WifiConfiguration.AuthAlgorithm.varName,
1041 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001043 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001044 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 break setVariables;
1047 }
1048
1049 String allowedPairwiseCiphersString =
1050 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1051 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001052 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001053 netId,
1054 WifiConfiguration.PairwiseCipher.varName,
1055 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001057 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001058 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 break setVariables;
1061 }
1062
1063 String allowedGroupCiphersString =
1064 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1065 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001066 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001067 netId,
1068 WifiConfiguration.GroupCipher.varName,
1069 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001071 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001072 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 break setVariables;
1075 }
1076
1077 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1078 // by preventing "*" as a key.
1079 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001080 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001081 netId,
1082 WifiConfiguration.pskVarName,
1083 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001085 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087 break setVariables;
1088 }
1089
1090 boolean hasSetKey = false;
1091 if (config.wepKeys != null) {
1092 for (int i = 0; i < config.wepKeys.length; i++) {
1093 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1094 // by preventing "*" as a key.
1095 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001096 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001097 netId,
1098 WifiConfiguration.wepKeyVarNames[i],
1099 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001101 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001102 "failed to set wep_key"+i+": " +
1103 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105 break setVariables;
1106 }
1107 hasSetKey = true;
1108 }
1109 }
1110 }
1111
1112 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001113 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001114 netId,
1115 WifiConfiguration.wepTxKeyIdxVarName,
1116 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001118 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001119 "failed to set wep_tx_keyidx: "+
1120 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122 break setVariables;
1123 }
1124 }
1125
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001126 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001127 netId,
1128 WifiConfiguration.priorityVarName,
1129 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001131 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001132 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134 break setVariables;
1135 }
1136
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001137 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001138 netId,
1139 WifiConfiguration.hiddenSSIDVarName,
1140 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001142 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001143 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 break setVariables;
1146 }
1147
Chung-yih Wang43374762009-09-16 14:28:42 +08001148 for (WifiConfiguration.EnterpriseField field
1149 : config.enterpriseFields) {
1150 String varName = field.varName();
1151 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001152 if (value != null) {
1153 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001154 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001155 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001156 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001157 netId,
1158 varName,
1159 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001160 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001161 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001162 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001163 }
1164 break setVariables;
1165 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001166 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001171 /*
1172 * For an update, if one of the setNetworkVariable operations fails,
1173 * we might want to roll back all the changes already made. But the
1174 * chances are that if anything is going to go wrong, it'll happen
1175 * the first time we try to set one of the variables.
1176 */
1177 if (newNetwork) {
1178 removeNetwork(netId);
1179 if (DBG) {
1180 Slog.d(TAG,
1181 "Failed to set a network variable, removed network: "
1182 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 }
1185 return -1;
1186 }
1187
1188 private static String makeString(BitSet set, String[] strings) {
1189 StringBuffer buf = new StringBuffer();
1190 int nextSetBit = -1;
1191
1192 /* Make sure all set bits are in [0, strings.length) to avoid
1193 * going out of bounds on strings. (Shouldn't happen, but...) */
1194 set = set.get(0, strings.length);
1195
1196 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1197 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1198 }
1199
1200 // remove trailing space
1201 if (set.cardinality() > 0) {
1202 buf.setLength(buf.length() - 1);
1203 }
1204
1205 return buf.toString();
1206 }
1207
1208 private static int lookupString(String string, String[] strings) {
1209 int size = strings.length;
1210
1211 string = string.replace('-', '_');
1212
1213 for (int i = 0; i < size; i++)
1214 if (string.equals(strings[i]))
1215 return i;
1216
1217 if (DBG) {
1218 // if we ever get here, we should probably add the
1219 // value to WifiConfiguration to reflect that it's
1220 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001221 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
1223
1224 return -1;
1225 }
1226
1227 /**
1228 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1229 * @param netId the integer that identifies the network configuration
1230 * to the supplicant
1231 * @return {@code true} if the operation succeeded
1232 */
1233 public boolean removeNetwork(int netId) {
1234 enforceChangePermission();
1235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 return mWifiStateTracker.removeNetwork(netId);
1237 }
1238
1239 /**
1240 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1241 * @param netId the integer that identifies the network configuration
1242 * to the supplicant
1243 * @param disableOthers if true, disable all other networks.
1244 * @return {@code true} if the operation succeeded
1245 */
1246 public boolean enableNetwork(int netId, boolean disableOthers) {
1247 enforceChangePermission();
1248
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001249 String ifname = mWifiStateTracker.getInterfaceName();
1250 NetworkUtils.enableInterface(ifname);
1251 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1252 if (!result) {
1253 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001255 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257
1258 /**
1259 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1260 * @param netId the integer that identifies the network configuration
1261 * to the supplicant
1262 * @return {@code true} if the operation succeeded
1263 */
1264 public boolean disableNetwork(int netId) {
1265 enforceChangePermission();
1266
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001267 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
1269
1270 /**
1271 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1272 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1273 */
1274 public WifiInfo getConnectionInfo() {
1275 enforceAccessPermission();
1276 /*
1277 * Make sure we have the latest information, by sending
1278 * a status request to the supplicant.
1279 */
1280 return mWifiStateTracker.requestConnectionInfo();
1281 }
1282
1283 /**
1284 * Return the results of the most recent access point scan, in the form of
1285 * a list of {@link ScanResult} objects.
1286 * @return the list of results
1287 */
1288 public List<ScanResult> getScanResults() {
1289 enforceAccessPermission();
1290 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001291
1292 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 if (reply == null) {
1294 return null;
1295 }
1296
1297 List<ScanResult> scanList = new ArrayList<ScanResult>();
1298
1299 int lineCount = 0;
1300
1301 int replyLen = reply.length();
1302 // Parse the result string, keeping in mind that the last line does
1303 // not end with a newline.
1304 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1305 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1306 ++lineCount;
1307 /*
1308 * Skip the first line, which is a header
1309 */
1310 if (lineCount == 1) {
1311 lineBeg = lineEnd + 1;
1312 continue;
1313 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001314 if (lineEnd > lineBeg) {
1315 String line = reply.substring(lineBeg, lineEnd);
1316 ScanResult scanResult = parseScanResult(line);
1317 if (scanResult != null) {
1318 scanList.add(scanResult);
1319 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001320 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322 }
1323 lineBeg = lineEnd + 1;
1324 }
1325 }
1326 mWifiStateTracker.setScanResultsList(scanList);
1327 return scanList;
1328 }
1329
1330 /**
1331 * Parse the scan result line passed to us by wpa_supplicant (helper).
1332 * @param line the line to parse
1333 * @return the {@link ScanResult} object
1334 */
1335 private ScanResult parseScanResult(String line) {
1336 ScanResult scanResult = null;
1337 if (line != null) {
1338 /*
1339 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1340 * must synchronized here!
1341 */
1342 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001343 String[] result = scanResultPattern.split(line);
1344 if (3 <= result.length && result.length <= 5) {
1345 String bssid = result[0];
1346 // bssid | frequency | level | flags | ssid
1347 int frequency;
1348 int level;
1349 try {
1350 frequency = Integer.parseInt(result[1]);
1351 level = Integer.parseInt(result[2]);
1352 /* some implementations avoid negative values by adding 256
1353 * so we need to adjust for that here.
1354 */
1355 if (level > 0) level -= 256;
1356 } catch (NumberFormatException e) {
1357 frequency = 0;
1358 level = 0;
1359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360
Mike Lockwood1a645052009-06-25 13:01:12 -04001361 /*
1362 * The formatting of the results returned by
1363 * wpa_supplicant is intended to make the fields
1364 * line up nicely when printed,
1365 * not to make them easy to parse. So we have to
1366 * apply some heuristics to figure out which field
1367 * is the SSID and which field is the flags.
1368 */
1369 String ssid;
1370 String flags;
1371 if (result.length == 4) {
1372 if (result[3].charAt(0) == '[') {
1373 flags = result[3];
1374 ssid = "";
1375 } else {
1376 flags = "";
1377 ssid = result[3];
1378 }
1379 } else if (result.length == 5) {
1380 flags = result[3];
1381 ssid = result[4];
1382 } else {
1383 // Here, we must have 3 fields: no flags and ssid
1384 // set
1385 flags = "";
1386 ssid = "";
1387 }
1388
Mike Lockwood00717e22009-08-17 10:09:36 -04001389 // bssid + ssid is the hash key
1390 String key = bssid + ssid;
1391 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001392 if (scanResult != null) {
1393 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001394 scanResult.SSID = ssid;
1395 scanResult.capabilities = flags;
1396 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001397 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 // Do not add scan results that have no SSID set
1399 if (0 < ssid.trim().length()) {
1400 scanResult =
1401 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001402 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001403 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001406 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001407 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001408 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
1410 }
1411 }
1412
1413 return scanResult;
1414 }
1415
1416 /**
1417 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1418 * and construct a {@code WifiConfiguration} that describes the encryption,
1419 * key management, and authenticaion capabilities of the access point.
1420 * @param flags the string returned by wpa_supplicant
1421 * @return the {@link WifiConfiguration} object, filled in
1422 */
1423 WifiConfiguration parseScanFlags(String flags) {
1424 WifiConfiguration config = new WifiConfiguration();
1425
1426 if (flags.length() == 0) {
1427 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1428 }
1429 // ... to be implemented
1430 return config;
1431 }
1432
1433 /**
1434 * Tell the supplicant to persist the current list of configured networks.
1435 * @return {@code true} if the operation succeeded
1436 */
1437 public boolean saveConfiguration() {
1438 boolean result;
1439 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001442 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 if (result && mNeedReconfig) {
1444 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001445 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446
1447 if (result) {
1448 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1449 mContext.sendBroadcast(intent);
1450 }
1451 }
1452 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001453 // Inform the backup manager about a data change
1454 IBackupManager ibm = IBackupManager.Stub.asInterface(
1455 ServiceManager.getService(Context.BACKUP_SERVICE));
1456 if (ibm != null) {
1457 try {
1458 ibm.dataChanged("com.android.providers.settings");
1459 } catch (Exception e) {
1460 // Try again later
1461 }
1462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 return result;
1464 }
1465
1466 /**
1467 * Set the number of radio frequency channels that are allowed to be used
1468 * in the current regulatory domain. This method should be used only
1469 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001470 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 * persisted as a Secure setting.
1472 * @param numChannels the number of allowed channels. Must be greater than 0
1473 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001474 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1476 * {@code numChannels} is outside the valid range.
1477 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001478 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001480 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 enforceChangePermission();
1482 /*
1483 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1484 * but if Wi-Fi isn't currently enabled, that's not possible, and
1485 * we want to persist the setting anyway,so that it will take
1486 * effect when Wi-Fi does become enabled.
1487 */
1488 boolean found = false;
1489 for (int validChan : sValidRegulatoryChannelCounts) {
1490 if (validChan == numChannels) {
1491 found = true;
1492 break;
1493 }
1494 }
1495 if (!found) {
1496 return false;
1497 }
1498
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001499 if (persist) {
1500 Settings.Secure.putInt(mContext.getContentResolver(),
1501 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1502 numChannels);
1503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 mWifiStateTracker.setNumAllowedChannels(numChannels);
1505 return true;
1506 }
1507
1508 /**
1509 * Return the number of frequency channels that are allowed
1510 * to be used in the current regulatory domain.
1511 * @return the number of allowed channels, or {@code -1} if an error occurs
1512 */
1513 public int getNumAllowedChannels() {
1514 int numChannels;
1515
1516 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001517
1518 /*
1519 * If we can't get the value from the driver (e.g., because
1520 * Wi-Fi is not currently enabled), get the value from
1521 * Settings.
1522 */
1523 numChannels = mWifiStateTracker.getNumAllowedChannels();
1524 if (numChannels < 0) {
1525 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1526 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1527 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529 return numChannels;
1530 }
1531
1532 /**
1533 * Return the list of valid values for the number of allowed radio channels
1534 * for various regulatory domains.
1535 * @return the list of channel counts
1536 */
1537 public int[] getValidChannelCounts() {
1538 enforceAccessPermission();
1539 return sValidRegulatoryChannelCounts;
1540 }
1541
1542 /**
1543 * Return the DHCP-assigned addresses from the last successful DHCP request,
1544 * if any.
1545 * @return the DHCP information
1546 */
1547 public DhcpInfo getDhcpInfo() {
1548 enforceAccessPermission();
1549 return mWifiStateTracker.getDhcpInfo();
1550 }
1551
1552 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1553 @Override
1554 public void onReceive(Context context, Intent intent) {
1555 String action = intent.getAction();
1556
Doug Zongker43866e02010-01-07 12:09:54 -08001557 long idleMillis =
1558 Settings.Secure.getLong(mContext.getContentResolver(),
1559 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001561 Settings.System.getInt(mContext.getContentResolver(),
1562 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001564 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 mAlarmManager.cancel(mIdleIntent);
1566 mDeviceIdle = false;
1567 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001568 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001570 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001572 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 /*
1574 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1575 * AND the "stay on while plugged in" setting doesn't match the
1576 * current power conditions (i.e, not plugged in, plugged in to USB,
1577 * or plugged in to AC).
1578 */
1579 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001580 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1581 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001582 // we used to go to sleep immediately, but this caused some race conditions
1583 // we don't have time to track down for this release. Delay instead, but not
1584 // as long as we would if connected (below)
1585 // TODO - fix the race conditions and switch back to the immediate turn-off
1586 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001588 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1589 // // do not keep Wifi awake when screen is off if Wifi is not associated
1590 // mDeviceIdle = true;
1591 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001592 } else {
1593 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001595 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 /* we can return now -- there's nothing to do until we get the idle intent back */
1599 return;
1600 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 mDeviceIdle = true;
1603 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1604 /*
1605 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1606 * AND we are transitioning from a state in which the device was supposed
1607 * to stay awake to a state in which it is not supposed to stay awake.
1608 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1609 * the already-set timer.
1610 */
1611 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001612 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1614 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1615 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1618 mPluggedType = pluggedType;
1619 return;
1620 }
1621 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001622 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001623 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1624 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1625 boolean isBluetoothPlaying = false;
1626 for (BluetoothDevice sink : sinks) {
1627 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1628 isBluetoothPlaying = true;
1629 }
1630 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001631 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 } else {
1634 return;
1635 }
1636
1637 updateWifiState();
1638 }
1639
1640 /**
1641 * Determines whether the Wi-Fi chipset should stay awake or be put to
1642 * sleep. Looks at the setting for the sleep policy and the current
1643 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001644 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 * @see #shouldDeviceStayAwake(int, int)
1646 */
1647 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1648 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1649 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1650
1651 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1652 // Never sleep
1653 return true;
1654 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1655 (pluggedType != 0)) {
1656 // Never sleep while plugged, and we're plugged
1657 return true;
1658 } else {
1659 // Default
1660 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1661 }
1662 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 /**
1665 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1666 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1667 * of {@code 0} isn't really a plugged type, but rather an indication that the
1668 * device isn't plugged in at all, there is no bit value corresponding to a
1669 * {@code pluggedType} value of {@code 0}. That is why we shift by
1670 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1671 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1672 * keep the device (and hence Wi-Fi) awake.
1673 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1674 * being made
1675 * @return {@code true} if {@code pluggedType} indicates that the device is
1676 * supposed to stay awake, {@code false} otherwise.
1677 */
1678 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1679 return (stayAwakeConditions & pluggedType) != 0;
1680 }
1681 };
1682
Dianne Hackborn617f8772009-03-31 15:04:46 -07001683 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 Message msg = Message.obtain(mWifiHandler,
1685 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001686 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 msg.sendToTarget();
1688 }
1689
1690 private void sendStartMessage(boolean scanOnlyMode) {
1691 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1692 }
1693
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001694 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1695 Message.obtain(mWifiHandler,
1696 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
1697 0, uid, wifiConfig).sendToTarget();
1698 }
1699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001701 // send a message so it's all serialized
1702 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1703 }
1704
1705 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001707 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 boolean lockHeld = mLocks.hasLocks();
1709 int strongestLockMode;
1710 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1711 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1712 if (mDeviceIdle && lockHeld) {
1713 strongestLockMode = mLocks.getStrongestLockMode();
1714 } else {
1715 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1716 }
1717
1718 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001719 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 return;
1721 }
1722 if (wifiShouldBeEnabled) {
1723 if (wifiShouldBeStarted) {
1724 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001725 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 sWakeLock.acquire();
1727 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1728 } else {
1729 int wakeLockTimeout =
1730 Settings.Secure.getInt(
1731 mContext.getContentResolver(),
1732 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1733 DEFAULT_WAKELOCK_TIMEOUT);
1734 /*
1735 * The following wakelock is held in order to ensure
1736 * that the connectivity manager has time to fail over
1737 * to the mobile data network. The connectivity manager
1738 * releases it once mobile data connectivity has been
1739 * established. If connectivity cannot be established,
1740 * the wakelock is released after wakeLockTimeout
1741 * milliseconds have elapsed.
1742 */
1743 sDriverStopWakeLock.acquire();
1744 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1745 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1746 }
1747 } else {
1748 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001749 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751 }
1752 }
1753
1754 private void registerForBroadcasts() {
1755 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1757 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1758 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1759 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001760 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 mContext.registerReceiver(mReceiver, intentFilter);
1762 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 private boolean isAirplaneSensitive() {
1765 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1766 Settings.System.AIRPLANE_MODE_RADIOS);
1767 return airplaneModeRadios == null
1768 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1769 }
1770
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001771 private boolean isAirplaneToggleable() {
1772 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1773 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1774 return toggleableRadios != null
1775 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1776 }
1777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 /**
1779 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1780 * currently on.
1781 * @return {@code true} if airplane mode is on.
1782 */
1783 private boolean isAirplaneModeOn() {
1784 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1785 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1786 }
1787
1788 /**
1789 * Handler that allows posting to the WifiThread.
1790 */
1791 private class WifiHandler extends Handler {
1792 public WifiHandler(Looper looper) {
1793 super(looper);
1794 }
1795
1796 @Override
1797 public void handleMessage(Message msg) {
1798 switch (msg.what) {
1799
1800 case MESSAGE_ENABLE_WIFI:
Irfan Sheriff7b009782010-03-11 16:37:45 -08001801 if (mWifiWatchdogService == null) {
1802 mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
1803 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001804 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 sWakeLock.release();
1806 break;
1807
1808 case MESSAGE_START_WIFI:
1809 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1810 mWifiStateTracker.restart();
1811 sWakeLock.release();
1812 break;
1813
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001814 case MESSAGE_UPDATE_STATE:
1815 doUpdateWifiState();
1816 break;
1817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 case MESSAGE_DISABLE_WIFI:
1819 // a non-zero msg.arg1 value means the "enabled" setting
1820 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001821 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
Irfan Sheriff7b009782010-03-11 16:37:45 -08001822 if (mWifiWatchdogService != null) {
1823 mWifiWatchdogService.quit();
1824 mWifiWatchdogService = null;
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 sWakeLock.release();
1827 break;
1828
1829 case MESSAGE_STOP_WIFI:
1830 mWifiStateTracker.disconnectAndStop();
1831 // don't release wakelock
1832 break;
1833
1834 case MESSAGE_RELEASE_WAKELOCK:
1835 synchronized (sDriverStopWakeLock) {
1836 if (sDriverStopWakeLock.isHeld()) {
1837 sDriverStopWakeLock.release();
1838 }
1839 }
1840 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001841
1842 case MESSAGE_START_ACCESS_POINT:
1843 setWifiApEnabledBlocking(true,
1844 msg.arg1 == 1,
1845 msg.arg2,
1846 (WifiConfiguration) msg.obj);
1847 break;
1848
1849 case MESSAGE_STOP_ACCESS_POINT:
1850 setWifiApEnabledBlocking(false,
1851 msg.arg1 == 1,
1852 msg.arg2,
1853 (WifiConfiguration) msg.obj);
1854 sWakeLock.release();
1855 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857 }
1858 }
1859
1860 @Override
1861 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1862 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1863 != PackageManager.PERMISSION_GRANTED) {
1864 pw.println("Permission Denial: can't dump WifiService from from pid="
1865 + Binder.getCallingPid()
1866 + ", uid=" + Binder.getCallingUid());
1867 return;
1868 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001869 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 pw.println("Stay-awake conditions: " +
1871 Settings.System.getInt(mContext.getContentResolver(),
1872 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1873 pw.println();
1874
1875 pw.println("Internal state:");
1876 pw.println(mWifiStateTracker);
1877 pw.println();
1878 pw.println("Latest scan results:");
1879 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1880 if (scanResults != null && scanResults.size() != 0) {
1881 pw.println(" BSSID Frequency RSSI Flags SSID");
1882 for (ScanResult r : scanResults) {
1883 pw.printf(" %17s %9d %5d %-16s %s%n",
1884 r.BSSID,
1885 r.frequency,
1886 r.level,
1887 r.capabilities,
1888 r.SSID == null ? "" : r.SSID);
1889 }
1890 }
1891 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001892 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1893 mScanLocksAcquired + " scan");
1894 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1895 mScanLocksReleased + " scan");
1896 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 pw.println("Locks held:");
1898 mLocks.dump(pw);
1899 }
1900
1901 private static String stateName(int wifiState) {
1902 switch (wifiState) {
1903 case WIFI_STATE_DISABLING:
1904 return "disabling";
1905 case WIFI_STATE_DISABLED:
1906 return "disabled";
1907 case WIFI_STATE_ENABLING:
1908 return "enabling";
1909 case WIFI_STATE_ENABLED:
1910 return "enabled";
1911 case WIFI_STATE_UNKNOWN:
1912 return "unknown state";
1913 default:
1914 return "[invalid state]";
1915 }
1916 }
1917
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001918 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001920 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
1922
1923 public void binderDied() {
1924 synchronized (mLocks) {
1925 releaseWifiLockLocked(mBinder);
1926 }
1927 }
1928
1929 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001930 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 }
1933
1934 private class LockList {
1935 private List<WifiLock> mList;
1936
1937 private LockList() {
1938 mList = new ArrayList<WifiLock>();
1939 }
1940
1941 private synchronized boolean hasLocks() {
1942 return !mList.isEmpty();
1943 }
1944
1945 private synchronized int getStrongestLockMode() {
1946 if (mList.isEmpty()) {
1947 return WifiManager.WIFI_MODE_FULL;
1948 }
1949 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001950 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 return WifiManager.WIFI_MODE_FULL;
1952 }
1953 }
1954 return WifiManager.WIFI_MODE_SCAN_ONLY;
1955 }
1956
1957 private void addLock(WifiLock lock) {
1958 if (findLockByBinder(lock.mBinder) < 0) {
1959 mList.add(lock);
1960 }
1961 }
1962
1963 private WifiLock removeLock(IBinder binder) {
1964 int index = findLockByBinder(binder);
1965 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001966 WifiLock ret = mList.remove(index);
1967 ret.unlinkDeathRecipient();
1968 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 } else {
1970 return null;
1971 }
1972 }
1973
1974 private int findLockByBinder(IBinder binder) {
1975 int size = mList.size();
1976 for (int i = size - 1; i >= 0; i--)
1977 if (mList.get(i).mBinder == binder)
1978 return i;
1979 return -1;
1980 }
1981
1982 private void dump(PrintWriter pw) {
1983 for (WifiLock l : mList) {
1984 pw.print(" ");
1985 pw.println(l);
1986 }
1987 }
1988 }
1989
1990 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1991 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1992 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1993 return false;
1994 }
1995 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1996 synchronized (mLocks) {
1997 return acquireWifiLockLocked(wifiLock);
1998 }
1999 }
2000
2001 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002002 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002005
The Android Open Source Project10592532009-03-18 17:39:46 -07002006 int uid = Binder.getCallingUid();
2007 long ident = Binder.clearCallingIdentity();
2008 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002009 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002010 case WifiManager.WIFI_MODE_FULL:
2011 ++mFullLocksAcquired;
2012 mBatteryStats.noteFullWifiLockAcquired(uid);
2013 break;
2014 case WifiManager.WIFI_MODE_SCAN_ONLY:
2015 ++mScanLocksAcquired;
2016 mBatteryStats.noteScanWifiLockAcquired(uid);
2017 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002018 }
2019 } catch (RemoteException e) {
2020 } finally {
2021 Binder.restoreCallingIdentity(ident);
2022 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 updateWifiState();
2025 return true;
2026 }
2027
2028 public boolean releaseWifiLock(IBinder lock) {
2029 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2030 synchronized (mLocks) {
2031 return releaseWifiLockLocked(lock);
2032 }
2033 }
2034
2035 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002036 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002037
The Android Open Source Project10592532009-03-18 17:39:46 -07002038 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002039
Joe Onorato8a9b2202010-02-26 18:56:32 -08002040 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002041
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002042 hadLock = (wifiLock != null);
2043
2044 if (hadLock) {
2045 int uid = Binder.getCallingUid();
2046 long ident = Binder.clearCallingIdentity();
2047 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002048 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002049 case WifiManager.WIFI_MODE_FULL:
2050 ++mFullLocksReleased;
2051 mBatteryStats.noteFullWifiLockReleased(uid);
2052 break;
2053 case WifiManager.WIFI_MODE_SCAN_ONLY:
2054 ++mScanLocksReleased;
2055 mBatteryStats.noteScanWifiLockReleased(uid);
2056 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002057 }
2058 } catch (RemoteException e) {
2059 } finally {
2060 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002061 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002062 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002063 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002065 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002067
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002068 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002069 implements IBinder.DeathRecipient {
2070 String mTag;
2071 int mMode;
2072 IBinder mBinder;
2073
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002074 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002075 super();
2076 mTag = tag;
2077 mMode = mode;
2078 mBinder = binder;
2079 try {
2080 mBinder.linkToDeath(this, 0);
2081 } catch (RemoteException e) {
2082 binderDied();
2083 }
2084 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002085
2086 void unlinkDeathRecipient() {
2087 mBinder.unlinkToDeath(this, 0);
2088 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002089 }
2090
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002091 private class Multicaster extends DeathRecipient {
2092 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002093 super(Binder.getCallingUid(), tag, binder);
2094 }
2095
2096 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002097 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002098 synchronized (mMulticasters) {
2099 int i = mMulticasters.indexOf(this);
2100 if (i != -1) {
2101 removeMulticasterLocked(i, mMode);
2102 }
2103 }
2104 }
2105
2106 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002107 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002108 }
2109
2110 public int getUid() {
2111 return mMode;
2112 }
2113 }
2114
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002115 public void initializeMulticastFiltering() {
2116 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002117
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002118 synchronized (mMulticasters) {
2119 // if anybody had requested filters be off, leave off
2120 if (mMulticasters.size() != 0) {
2121 return;
2122 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002123 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002124 }
2125 }
2126 }
2127
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002128 public void acquireMulticastLock(IBinder binder, String tag) {
2129 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002130
2131 synchronized (mMulticasters) {
2132 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002133 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002134 // Note that we could call stopPacketFiltering only when
2135 // our new size == 1 (first call), but this function won't
2136 // be called often and by making the stopPacket call each
2137 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002138 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002139 }
2140
2141 int uid = Binder.getCallingUid();
2142 Long ident = Binder.clearCallingIdentity();
2143 try {
2144 mBatteryStats.noteWifiMulticastEnabled(uid);
2145 } catch (RemoteException e) {
2146 } finally {
2147 Binder.restoreCallingIdentity(ident);
2148 }
2149 }
2150
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002151 public void releaseMulticastLock() {
2152 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002153
2154 int uid = Binder.getCallingUid();
2155 synchronized (mMulticasters) {
2156 mMulticastDisabled++;
2157 int size = mMulticasters.size();
2158 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002159 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002160 if ((m != null) && (m.getUid() == uid)) {
2161 removeMulticasterLocked(i, uid);
2162 }
2163 }
2164 }
2165 }
2166
2167 private void removeMulticasterLocked(int i, int uid)
2168 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002169 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002170
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002171 if (removed != null) {
2172 removed.unlinkDeathRecipient();
2173 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002174 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002175 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002176 }
2177
2178 Long ident = Binder.clearCallingIdentity();
2179 try {
2180 mBatteryStats.noteWifiMulticastDisabled(uid);
2181 } catch (RemoteException e) {
2182 } finally {
2183 Binder.restoreCallingIdentity(ident);
2184 }
2185 }
2186
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002187 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002188 enforceAccessPermission();
2189
2190 synchronized (mMulticasters) {
2191 return (mMulticasters.size() > 0);
2192 }
2193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194}