blob: 248f5798ee167059dae89b4d4b62e9616c0ab30e [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;
127 private String[] mWifiRegexs;
128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800130 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
131 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 * the approximate point at which the battery drain caused by Wi-Fi
133 * being enabled but not active exceeds the battery drain caused by
134 * re-establishing a connection to the mobile data network.
135 */
136 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
137
138 private static final String WAKELOCK_TAG = "WifiService";
139
140 /**
141 * The maximum amount of time to hold the wake lock after a disconnect
142 * caused by stopping the driver. Establishing an EDGE connection has been
143 * observed to take about 5 seconds under normal circumstances. This
144 * provides a bit of extra margin.
145 * <p>
146 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
147 * This is the default value if a Settings.Secure value is not present.
148 */
149 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
150
151 // Wake lock used by driver-stop operation
152 private static PowerManager.WakeLock sDriverStopWakeLock;
153 // Wake lock used by other operations
154 private static PowerManager.WakeLock sWakeLock;
155
156 private static final int MESSAGE_ENABLE_WIFI = 0;
157 private static final int MESSAGE_DISABLE_WIFI = 1;
158 private static final int MESSAGE_STOP_WIFI = 2;
159 private static final int MESSAGE_START_WIFI = 3;
160 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -0700161 private static final int MESSAGE_UPDATE_STATE = 5;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800162 private static final int MESSAGE_START_ACCESS_POINT = 6;
163 private static final int MESSAGE_STOP_ACCESS_POINT = 7;
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
166 private final WifiHandler mWifiHandler;
167
168 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * Cache of scan results objects (size is somewhat arbitrary)
170 */
171 private static final int SCAN_RESULT_CACHE_SIZE = 80;
172 private final LinkedHashMap<String, ScanResult> mScanResultCache;
173
174 /*
175 * Character buffer used to parse scan results (optimization)
176 */
177 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 private boolean mNeedReconfig;
179
Dianne Hackborn617f8772009-03-31 15:04:46 -0700180 /*
181 * Last UID that asked to enable WIFI.
182 */
183 private int mLastEnableUid = Process.myUid();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 /**
186 * Number of allowed radio frequency channels in various regulatory domains.
187 * This list is sufficient for 802.11b/g networks (2.4GHz range).
188 */
189 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
190
191 private static final String ACTION_DEVICE_IDLE =
192 "com.android.server.WifiManager.action.DEVICE_IDLE";
193
194 WifiService(Context context, WifiStateTracker tracker) {
195 mContext = context;
196 mWifiStateTracker = tracker;
Mike Lockwoodf32be162009-07-14 17:44:37 -0400197 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700198 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800199
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800200 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
201 nwService = INetworkManagementService.Stub.asInterface(b);
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 mScanResultCache = new LinkedHashMap<String, ScanResult>(
204 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
205 /*
206 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
207 * elements
208 */
209 public boolean removeEldestEntry(Map.Entry eldest) {
210 return SCAN_RESULT_CACHE_SIZE < this.size();
211 }
212 };
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 HandlerThread wifiThread = new HandlerThread("WifiService");
215 wifiThread.start();
216 mWifiHandler = new WifiHandler(wifiThread.getLooper());
217
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800218 mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800219 mWifiApState = WIFI_AP_STATE_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800221 boolean wifiAPEnabled = wifiEnabled ? false : getPersistedWifiApEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
223 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
224 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
225 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
226
227 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
228 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
229 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
230 mWifiStateTracker.setReleaseWakeLockCallback(
231 new Runnable() {
232 public void run() {
233 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
234 synchronized (sDriverStopWakeLock) {
235 if (sDriverStopWakeLock.isHeld()) {
236 sDriverStopWakeLock.release();
237 }
238 }
239 }
240 }
241 );
242
Joe Onorato8a9b2202010-02-26 18:56:32 -0800243 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 (wifiEnabled ? "enabled" : "disabled"));
245
246 mContext.registerReceiver(
247 new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700250 // clear our flag indicating the user has overwridden airplane mode
251 mAirplaneModeOverwridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 updateWifiState();
253 }
254 },
255 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
256
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800257 mContext.registerReceiver(
258 new BroadcastReceiver() {
259 @Override
260 public void onReceive(Context context, Intent intent) {
261
262 ArrayList<String> available = intent.getStringArrayListExtra(
263 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
264 ArrayList<String> active = intent.getStringArrayListExtra(
265 ConnectivityManager.EXTRA_ACTIVE_TETHER);
266 updateTetherState(available, active);
267
268 }
269 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
270
Dianne Hackborn617f8772009-03-31 15:04:46 -0700271 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800272 setWifiApEnabledBlocking(wifiAPEnabled, true, Process.myUid(), null);
273 }
274
275 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
276
277 boolean wifiTethered = false;
278 boolean wifiAvailable = false;
279
280 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
281 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
282
283 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
284 mWifiRegexs = mCm.getTetherableWifiRegexs();
285
286 for (String intf : available) {
287 for (String regex : mWifiRegexs) {
288 if (intf.matches(regex)) {
289
290 InterfaceConfiguration ifcg = null;
291 try {
292 ifcg = service.getInterfaceConfig(intf);
293 if (ifcg != null) {
294 /* IP/netmask: 169.254.2.1/255.255.255.0 */
295 ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
296 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
297 ifcg.interfaceFlags = "up";
298
299 service.setInterfaceConfig(intf, ifcg);
300 }
301 } catch (Exception e) {
302 /**
303 * TODO: Add broadcast to indicate tether failed
304 */
305 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
306 return;
307 }
308
309 /**
310 * TODO: Add broadcast to indicate tether failed
311 */
312 if(mCm.tether(intf) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
313 Slog.d(TAG, "Tethered "+intf);
314 } else {
315 Slog.e(TAG, "Error tethering "+intf);
316 }
317 break;
318 }
319 }
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 private boolean getPersistedWifiEnabled() {
324 final ContentResolver cr = mContext.getContentResolver();
325 try {
326 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
327 } catch (Settings.SettingNotFoundException e) {
328 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
329 return false;
330 }
331 }
332
333 private void persistWifiEnabled(boolean enabled) {
334 final ContentResolver cr = mContext.getContentResolver();
335 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
336 }
337
338 NetworkStateTracker getNetworkStateTracker() {
339 return mWifiStateTracker;
340 }
341
342 /**
343 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
344 * @return {@code true} if the operation succeeds
345 */
346 public boolean pingSupplicant() {
347 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800348
349 return mWifiStateTracker.ping();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 }
351
352 /**
353 * see {@link android.net.wifi.WifiManager#startScan()}
354 * @return {@code true} if the operation succeeds
355 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400356 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800358
359 switch (mWifiStateTracker.getSupplicantState()) {
360 case DISCONNECTED:
361 case INACTIVE:
362 case SCANNING:
363 case DORMANT:
364 break;
365 default:
366 mWifiStateTracker.setScanResultHandling(
367 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
368 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800370 return mWifiStateTracker.scan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
373 /**
374 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
375 * @param enable {@code true} to enable, {@code false} to disable.
376 * @return {@code true} if the enable/disable operation was
377 * started or is already in the queue.
378 */
379 public boolean setWifiEnabled(boolean enable) {
380 enforceChangePermission();
381 if (mWifiHandler == null) return false;
382
383 synchronized (mWifiHandler) {
Robert Greenwalta99f4612009-09-19 18:14:32 -0700384 // caller may not have WAKE_LOCK permission - it's not required here
385 long ident = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 sWakeLock.acquire();
Robert Greenwalta99f4612009-09-19 18:14:32 -0700387 Binder.restoreCallingIdentity(ident);
388
Dianne Hackborn617f8772009-03-31 15:04:46 -0700389 mLastEnableUid = Binder.getCallingUid();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700390 // set a flag if the user is enabling Wifi while in airplane mode
391 mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700392 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 }
394
395 return true;
396 }
397
398 /**
399 * Enables/disables Wi-Fi synchronously.
400 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
401 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700402 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 * @return {@code true} if the operation succeeds (or if the existing state
404 * is the same as the requested state)
405 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700406 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800408 final int wifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800410 if (wifiState == eventualWifiState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 return true;
412 }
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700413 if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 return false;
415 }
416
Irfan Sheriffcd770372010-01-08 09:36:04 -0800417 /**
418 * Multiple calls to unregisterReceiver() cause exception and a system crash.
419 * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
420 * disable wifi at the same time.
421 * Avoid doing a disable when the current Wifi state is UNKNOWN
422 * TODO: Handle driver load fail and supplicant lost as seperate states
423 */
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800424 if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
Irfan Sheriffcd770372010-01-08 09:36:04 -0800425 return false;
426 }
427
Dianne Hackborn617f8772009-03-31 15:04:46 -0700428 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800430 if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
431 setWifiApEnabledBlocking(false, true, Process.myUid(), null);
432 }
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800435 if (!mWifiStateTracker.loadDriver()) {
436 Slog.e(TAG, "Failed to load Wi-Fi driver.");
437 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
438 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800440 if (!mWifiStateTracker.startSupplicant()) {
441 mWifiStateTracker.unloadDriver();
442 Slog.e(TAG, "Failed to start supplicant daemon.");
443 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
444 return false;
445 }
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 registerForBroadcasts();
448 mWifiStateTracker.startEventLoop();
449 } else {
450
451 mContext.unregisterReceiver(mReceiver);
452 // Remove notification (it will no-op if it isn't visible)
453 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
454
455 boolean failedToStopSupplicantOrUnloadDriver = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800456
457 if (!mWifiStateTracker.stopSupplicant()) {
458 Slog.e(TAG, "Failed to stop supplicant daemon.");
459 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
460 failedToStopSupplicantOrUnloadDriver = true;
461 }
462
463 /**
464 * Reset connections and disable interface
465 * before we unload the driver
466 */
467 mWifiStateTracker.resetConnections(true);
468
469 if (!mWifiStateTracker.unloadDriver()) {
470 Slog.e(TAG, "Failed to unload Wi-Fi driver.");
471 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700472 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 failedToStopSupplicantOrUnloadDriver = true;
474 }
475 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 if (failedToStopSupplicantOrUnloadDriver) {
478 return false;
479 }
480 }
481
482 // Success!
483
484 if (persist) {
485 persistWifiEnabled(enable);
486 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700487 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 return true;
489 }
490
Dianne Hackborn617f8772009-03-31 15:04:46 -0700491 private void setWifiEnabledState(int wifiState, int uid) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800492 final int previousWifiState = mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493
The Android Open Source Project10592532009-03-18 17:39:46 -0700494 long ident = Binder.clearCallingIdentity();
495 try {
496 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700497 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700498 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700499 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700500 }
501 } catch (RemoteException e) {
502 } finally {
503 Binder.restoreCallingIdentity(ident);
504 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 // Update state
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800507 mWifiStateTracker.setWifiState(wifiState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508
509 // Broadcast
510 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
511 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
512 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
513 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
514 mContext.sendStickyBroadcast(intent);
515 }
516
517 private void enforceAccessPermission() {
518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
519 "WifiService");
520 }
521
522 private void enforceChangePermission() {
523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
524 "WifiService");
525
526 }
527
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700528 private void enforceMulticastChangePermission() {
529 mContext.enforceCallingOrSelfPermission(
530 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
531 "WifiService");
532 }
533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 /**
535 * see {@link WifiManager#getWifiState()}
536 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
537 * {@link WifiManager#WIFI_STATE_DISABLING},
538 * {@link WifiManager#WIFI_STATE_ENABLED},
539 * {@link WifiManager#WIFI_STATE_ENABLING},
540 * {@link WifiManager#WIFI_STATE_UNKNOWN}
541 */
542 public int getWifiEnabledState() {
543 enforceAccessPermission();
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800544 return mWifiStateTracker.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
547 /**
548 * see {@link android.net.wifi.WifiManager#disconnect()}
549 * @return {@code true} if the operation succeeds
550 */
551 public boolean disconnect() {
552 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800553
554 return mWifiStateTracker.disconnect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
556
557 /**
558 * see {@link android.net.wifi.WifiManager#reconnect()}
559 * @return {@code true} if the operation succeeds
560 */
561 public boolean reconnect() {
562 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800563
564 return mWifiStateTracker.reconnectCommand();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 }
566
567 /**
568 * see {@link android.net.wifi.WifiManager#reassociate()}
569 * @return {@code true} if the operation succeeds
570 */
571 public boolean reassociate() {
572 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800573
574 return mWifiStateTracker.reassociate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800577 private boolean getPersistedWifiApEnabled() {
578 final ContentResolver cr = mContext.getContentResolver();
579 try {
580 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_ON) == 1;
581 } catch (Settings.SettingNotFoundException e) {
582 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, 0);
583 return false;
584 }
585 }
586
587 private void persistWifiApEnabled(boolean enabled) {
588 final ContentResolver cr = mContext.getContentResolver();
589 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_ON, enabled ? 1 : 0);
590 }
591
592 /**
593 * see {@link android.net.wifi.WifiManager#startAccessPoint(WifiConfiguration)}
594 * @param wifiConfig SSID, security and channel details as
595 * part of WifiConfiguration
596 * @return {@code true} if the start operation was
597 * started or is already in the queue.
598 */
599 public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
600 enforceChangePermission();
601 if (mWifiHandler == null) return false;
602
603 synchronized (mWifiHandler) {
604
605 long ident = Binder.clearCallingIdentity();
606 sWakeLock.acquire();
607 Binder.restoreCallingIdentity(ident);
608
609 mLastEnableUid = Binder.getCallingUid();
610
611 sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
612 }
613
614 return true;
615 }
616
617 /**
618 * Enables/disables Wi-Fi AP synchronously. The driver is loaded
619 * and soft access point configured as a single operation.
620 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
621 * @param persist {@code true} if the setting should be persisted.
622 * @param uid The UID of the process making the request.
623 * @param config The WifiConfiguration for AP
624 * @return {@code true} if the operation succeeds (or if the existing state
625 * is the same as the requested state)
626 */
627 /**
628 * TODO: persist needs to go away in WifiService
629 * This will affect all persist related functions
630 * for Access Point
631 */
632 private boolean setWifiApEnabledBlocking(boolean enable,
633 boolean persist, int uid, WifiConfiguration wifiConfig) {
634 final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
635
636 if (mWifiApState == eventualWifiApState) {
637 return true;
638 }
639
640 setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING : WIFI_AP_STATE_DISABLING, uid);
641
Irfan Sheriff0f344060092010-03-10 10:05:51 -0800642 if (enable && (mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED)) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800643 setWifiEnabledBlocking(false, true, Process.myUid());
644 }
645
646 if (enable) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800647 if (!mWifiStateTracker.loadDriver()) {
648 Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
649 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
650 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800651 }
652
653 try {
654 nwService.startAccessPoint();
655 } catch(Exception e) {
656 Slog.e(TAG, "Exception in startAccessPoint()");
657 }
658
659 } else {
660
661 try {
662 nwService.stopAccessPoint();
663 } catch(Exception e) {
664 Slog.e(TAG, "Exception in stopAccessPoint()");
665 }
666
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800667 if (!mWifiStateTracker.unloadDriver()) {
668 Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
669 setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
670 return false;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800671 }
672 }
673
674 // Success!
675 if (persist) {
676 persistWifiApEnabled(enable);
677 }
678 setWifiApEnabledState(eventualWifiApState, uid);
679 return true;
680 }
681
682 /**
683 * see {@link WifiManager#getWifiApState()}
684 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
685 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
686 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
687 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
688 * {@link WifiManager#WIFI_AP_STATE_FAILED}
689 */
690 public int getWifiApEnabledState() {
691 enforceAccessPermission();
692 return mWifiApState;
693 }
694
695 private void setWifiApEnabledState(int wifiAPState, int uid) {
696 final int previousWifiApState = mWifiApState;
697
698 long ident = Binder.clearCallingIdentity();
699 try {
700 if (wifiAPState == WIFI_AP_STATE_ENABLED) {
701 mBatteryStats.noteWifiOn(uid);
702 } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
703 mBatteryStats.noteWifiOff(uid);
704 }
705 } catch (RemoteException e) {
706 } finally {
707 Binder.restoreCallingIdentity(ident);
708 }
709
710 // Update state
711 mWifiApState = wifiAPState;
712
713 // Broadcast
714 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
715 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
716 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
717 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
718 mContext.sendStickyBroadcast(intent);
719 }
720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 /**
722 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
723 * @return the list of configured networks
724 */
725 public List<WifiConfiguration> getConfiguredNetworks() {
726 enforceAccessPermission();
727 String listStr;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 /*
730 * We don't cache the list, because we want to allow
731 * for the possibility that the configuration file
732 * has been modified through some external means,
733 * such as the wpa_cli command line program.
734 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800735 listStr = mWifiStateTracker.listNetworks();
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 List<WifiConfiguration> networks =
738 new ArrayList<WifiConfiguration>();
739 if (listStr == null)
740 return networks;
741
742 String[] lines = listStr.split("\n");
743 // Skip the first line, which is a header
744 for (int i = 1; i < lines.length; i++) {
745 String[] result = lines[i].split("\t");
746 // network-id | ssid | bssid | flags
747 WifiConfiguration config = new WifiConfiguration();
748 try {
749 config.networkId = Integer.parseInt(result[0]);
750 } catch(NumberFormatException e) {
751 continue;
752 }
753 if (result.length > 3) {
754 if (result[3].indexOf("[CURRENT]") != -1)
755 config.status = WifiConfiguration.Status.CURRENT;
756 else if (result[3].indexOf("[DISABLED]") != -1)
757 config.status = WifiConfiguration.Status.DISABLED;
758 else
759 config.status = WifiConfiguration.Status.ENABLED;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800760 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 config.status = WifiConfiguration.Status.ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800763 readNetworkVariables(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 networks.add(config);
765 }
766
767 return networks;
768 }
769
770 /**
771 * Read the variables from the supplicant daemon that are needed to
772 * fill in the WifiConfiguration object.
773 * <p/>
774 * The caller must hold the synchronization monitor.
775 * @param config the {@link WifiConfiguration} object to be filled in.
776 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800777 private void readNetworkVariables(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778
779 int netId = config.networkId;
780 if (netId < 0)
781 return;
782
783 /*
784 * TODO: maybe should have a native method that takes an array of
785 * variable names and returns an array of values. But we'd still
786 * be doing a round trip to the supplicant daemon for each variable.
787 */
788 String value;
789
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800790 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800792 config.SSID = removeDoubleQuotes(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 } else {
794 config.SSID = null;
795 }
796
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800797 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 if (!TextUtils.isEmpty(value)) {
799 config.BSSID = value;
800 } else {
801 config.BSSID = null;
802 }
803
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800804 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 config.priority = -1;
806 if (!TextUtils.isEmpty(value)) {
807 try {
808 config.priority = Integer.parseInt(value);
809 } catch (NumberFormatException ignore) {
810 }
811 }
812
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800813 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 config.hiddenSSID = false;
815 if (!TextUtils.isEmpty(value)) {
816 try {
817 config.hiddenSSID = Integer.parseInt(value) != 0;
818 } catch (NumberFormatException ignore) {
819 }
820 }
821
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800822 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 config.wepTxKeyIndex = -1;
824 if (!TextUtils.isEmpty(value)) {
825 try {
826 config.wepTxKeyIndex = Integer.parseInt(value);
827 } catch (NumberFormatException ignore) {
828 }
829 }
830
831 /*
832 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
833 * just a "*" if the key is set, or the null string otherwise.
834 */
835 for (int i = 0; i < 4; i++) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800836 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (!TextUtils.isEmpty(value)) {
838 config.wepKeys[i] = value;
839 } else {
840 config.wepKeys[i] = null;
841 }
842 }
843
844 /*
845 * Get the private shared key. Note that the actual keys are not passed back,
846 * just a "*" if the key is set, or the null string otherwise.
847 */
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800848 value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 if (!TextUtils.isEmpty(value)) {
850 config.preSharedKey = value;
851 } else {
852 config.preSharedKey = null;
853 }
854
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800855 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 WifiConfiguration.Protocol.varName);
857 if (!TextUtils.isEmpty(value)) {
858 String vals[] = value.split(" ");
859 for (String val : vals) {
860 int index =
861 lookupString(val, WifiConfiguration.Protocol.strings);
862 if (0 <= index) {
863 config.allowedProtocols.set(index);
864 }
865 }
866 }
867
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800868 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 WifiConfiguration.KeyMgmt.varName);
870 if (!TextUtils.isEmpty(value)) {
871 String vals[] = value.split(" ");
872 for (String val : vals) {
873 int index =
874 lookupString(val, WifiConfiguration.KeyMgmt.strings);
875 if (0 <= index) {
876 config.allowedKeyManagement.set(index);
877 }
878 }
879 }
880
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800881 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 WifiConfiguration.AuthAlgorithm.varName);
883 if (!TextUtils.isEmpty(value)) {
884 String vals[] = value.split(" ");
885 for (String val : vals) {
886 int index =
887 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
888 if (0 <= index) {
889 config.allowedAuthAlgorithms.set(index);
890 }
891 }
892 }
893
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800894 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 WifiConfiguration.PairwiseCipher.varName);
896 if (!TextUtils.isEmpty(value)) {
897 String vals[] = value.split(" ");
898 for (String val : vals) {
899 int index =
900 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
901 if (0 <= index) {
902 config.allowedPairwiseCiphers.set(index);
903 }
904 }
905 }
906
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800907 value = mWifiStateTracker.getNetworkVariable(config.networkId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 WifiConfiguration.GroupCipher.varName);
909 if (!TextUtils.isEmpty(value)) {
910 String vals[] = value.split(" ");
911 for (String val : vals) {
912 int index =
913 lookupString(val, WifiConfiguration.GroupCipher.strings);
914 if (0 <= index) {
915 config.allowedGroupCiphers.set(index);
916 }
917 }
918 }
Chung-yih Wang43374762009-09-16 14:28:42 +0800919
920 for (WifiConfiguration.EnterpriseField field :
921 config.enterpriseFields) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800922 value = mWifiStateTracker.getNetworkVariable(netId,
Chung-yih Wang43374762009-09-16 14:28:42 +0800923 field.varName());
924 if (!TextUtils.isEmpty(value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800925 if (field != config.eap) value = removeDoubleQuotes(value);
Chung-yih Wang43374762009-09-16 14:28:42 +0800926 field.setValue(value);
927 }
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800931 private static String removeDoubleQuotes(String string) {
932 if (string.length() <= 2) return "";
933 return string.substring(1, string.length() - 1);
934 }
935
936 private static String convertToQuotedString(String string) {
937 return "\"" + string + "\"";
938 }
939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 /**
941 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
942 * @return the supplicant-assigned identifier for the new or updated
943 * network if the operation succeeds, or {@code -1} if it fails
944 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800945 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 /*
949 * If the supplied networkId is -1, we create a new empty
950 * network configuration. Otherwise, the networkId should
951 * refer to an existing configuration.
952 */
953 int netId = config.networkId;
954 boolean newNetwork = netId == -1;
955 boolean doReconfig;
956 int currentPriority;
957 // networkId of -1 means we want to create a new network
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800958 synchronized (mWifiStateTracker) {
959 if (newNetwork) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800960 netId = mWifiStateTracker.addNetwork();
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800961 if (netId < 0) {
962 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800963 Slog.d(TAG, "Failed to add a network!");
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800964 }
965 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800967 doReconfig = true;
968 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800969 String priorityVal = mWifiStateTracker.getNetworkVariable(
970 netId, WifiConfiguration.priorityVarName);
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800971 currentPriority = -1;
972 if (!TextUtils.isEmpty(priorityVal)) {
973 try {
974 currentPriority = Integer.parseInt(priorityVal);
975 } catch (NumberFormatException ignore) {
976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800978 doReconfig = currentPriority != config.priority;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800980 mNeedReconfig = mNeedReconfig || doReconfig;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800983 setVariables: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 /*
985 * Note that if a networkId for a non-existent network
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800986 * was supplied, then the first setNetworkVariable()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 * will fail, so we don't bother to make a separate check
988 * for the validity of the ID up front.
989 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 if (config.SSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800991 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800992 netId,
993 WifiConfiguration.ssidVarName,
994 convertToQuotedString(config.SSID))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800996 Slog.d(TAG, "failed to set SSID: "+config.SSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998 break setVariables;
999 }
1000
1001 if (config.BSSID != null &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001002 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001003 netId,
1004 WifiConfiguration.bssidVarName,
1005 config.BSSID)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 break setVariables;
1010 }
1011
1012 String allowedKeyManagementString =
1013 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
1014 if (config.allowedKeyManagement.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001015 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001016 netId,
1017 WifiConfiguration.KeyMgmt.varName,
1018 allowedKeyManagementString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001020 Slog.d(TAG, "failed to set key_mgmt: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001021 allowedKeyManagementString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
1023 break setVariables;
1024 }
1025
1026 String allowedProtocolsString =
1027 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
1028 if (config.allowedProtocols.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001029 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001030 netId,
1031 WifiConfiguration.Protocol.varName,
1032 allowedProtocolsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001034 Slog.d(TAG, "failed to set proto: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001035 allowedProtocolsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037 break setVariables;
1038 }
1039
1040 String allowedAuthAlgorithmsString =
1041 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
1042 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001043 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001044 netId,
1045 WifiConfiguration.AuthAlgorithm.varName,
1046 allowedAuthAlgorithmsString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001048 Slog.d(TAG, "failed to set auth_alg: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001049 allowedAuthAlgorithmsString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 break setVariables;
1052 }
1053
1054 String allowedPairwiseCiphersString =
1055 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
1056 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001057 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001058 netId,
1059 WifiConfiguration.PairwiseCipher.varName,
1060 allowedPairwiseCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001062 Slog.d(TAG, "failed to set pairwise: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001063 allowedPairwiseCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065 break setVariables;
1066 }
1067
1068 String allowedGroupCiphersString =
1069 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
1070 if (config.allowedGroupCiphers.cardinality() != 0 &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001071 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001072 netId,
1073 WifiConfiguration.GroupCipher.varName,
1074 allowedGroupCiphersString)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001076 Slog.d(TAG, "failed to set group: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001077 allowedGroupCiphersString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
1079 break setVariables;
1080 }
1081
1082 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1083 // by preventing "*" as a key.
1084 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001085 !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001086 netId,
1087 WifiConfiguration.pskVarName,
1088 config.preSharedKey)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001090 Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
1092 break setVariables;
1093 }
1094
1095 boolean hasSetKey = false;
1096 if (config.wepKeys != null) {
1097 for (int i = 0; i < config.wepKeys.length; i++) {
1098 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1099 // by preventing "*" as a key.
1100 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001101 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001102 netId,
1103 WifiConfiguration.wepKeyVarNames[i],
1104 config.wepKeys[i])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001106 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001107 "failed to set wep_key"+i+": " +
1108 config.wepKeys[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110 break setVariables;
1111 }
1112 hasSetKey = true;
1113 }
1114 }
1115 }
1116
1117 if (hasSetKey) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001118 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001119 netId,
1120 WifiConfiguration.wepTxKeyIdxVarName,
1121 Integer.toString(config.wepTxKeyIndex))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001123 Slog.d(TAG,
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001124 "failed to set wep_tx_keyidx: "+
1125 config.wepTxKeyIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 break setVariables;
1128 }
1129 }
1130
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001131 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001132 netId,
1133 WifiConfiguration.priorityVarName,
1134 Integer.toString(config.priority))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001136 Slog.d(TAG, config.SSID + ": failed to set priority: "
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001137 +config.priority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 break setVariables;
1140 }
1141
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001142 if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001143 netId,
1144 WifiConfiguration.hiddenSSIDVarName,
1145 Integer.toString(config.hiddenSSID ? 1 : 0))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001147 Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001148 config.hiddenSSID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 break setVariables;
1151 }
1152
Chung-yih Wang43374762009-09-16 14:28:42 +08001153 for (WifiConfiguration.EnterpriseField field
1154 : config.enterpriseFields) {
1155 String varName = field.varName();
1156 String value = field.value();
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001157 if (value != null) {
1158 if (field != config.eap) {
Chia-chi Yeh784d53e2010-01-29 16:26:28 +08001159 value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
Chung-yih Wang43374762009-09-16 14:28:42 +08001160 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001161 if (!mWifiStateTracker.setNetworkVariable(
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001162 netId,
1163 varName,
1164 value)) {
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001165 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001166 Slog.d(TAG, config.SSID + ": failed to set " + varName +
Irfan Sheriff7aac5542009-12-22 21:42:17 -08001167 ": " + value);
Chung-yih Wanga8d15942009-10-09 11:01:49 +08001168 }
1169 break setVariables;
1170 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001171 }
Chung-yih Wang5069cc72009-06-03 17:33:47 +08001172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 return netId;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001176 /*
1177 * For an update, if one of the setNetworkVariable operations fails,
1178 * we might want to roll back all the changes already made. But the
1179 * chances are that if anything is going to go wrong, it'll happen
1180 * the first time we try to set one of the variables.
1181 */
1182 if (newNetwork) {
1183 removeNetwork(netId);
1184 if (DBG) {
1185 Slog.d(TAG,
1186 "Failed to set a network variable, removed network: "
1187 + netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189 }
1190 return -1;
1191 }
1192
1193 private static String makeString(BitSet set, String[] strings) {
1194 StringBuffer buf = new StringBuffer();
1195 int nextSetBit = -1;
1196
1197 /* Make sure all set bits are in [0, strings.length) to avoid
1198 * going out of bounds on strings. (Shouldn't happen, but...) */
1199 set = set.get(0, strings.length);
1200
1201 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1202 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1203 }
1204
1205 // remove trailing space
1206 if (set.cardinality() > 0) {
1207 buf.setLength(buf.length() - 1);
1208 }
1209
1210 return buf.toString();
1211 }
1212
1213 private static int lookupString(String string, String[] strings) {
1214 int size = strings.length;
1215
1216 string = string.replace('-', '_');
1217
1218 for (int i = 0; i < size; i++)
1219 if (string.equals(strings[i]))
1220 return i;
1221
1222 if (DBG) {
1223 // if we ever get here, we should probably add the
1224 // value to WifiConfiguration to reflect that it's
1225 // supported by the WPA supplicant
Joe Onorato8a9b2202010-02-26 18:56:32 -08001226 Slog.w(TAG, "Failed to look-up a string: " + string);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
1228
1229 return -1;
1230 }
1231
1232 /**
1233 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1234 * @param netId the integer that identifies the network configuration
1235 * to the supplicant
1236 * @return {@code true} if the operation succeeded
1237 */
1238 public boolean removeNetwork(int netId) {
1239 enforceChangePermission();
1240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 return mWifiStateTracker.removeNetwork(netId);
1242 }
1243
1244 /**
1245 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1246 * @param netId the integer that identifies the network configuration
1247 * to the supplicant
1248 * @param disableOthers if true, disable all other networks.
1249 * @return {@code true} if the operation succeeded
1250 */
1251 public boolean enableNetwork(int netId, boolean disableOthers) {
1252 enforceChangePermission();
1253
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001254 String ifname = mWifiStateTracker.getInterfaceName();
1255 NetworkUtils.enableInterface(ifname);
1256 boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
1257 if (!result) {
1258 NetworkUtils.disableInterface(ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001260 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262
1263 /**
1264 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1265 * @param netId the integer that identifies the network configuration
1266 * to the supplicant
1267 * @return {@code true} if the operation succeeded
1268 */
1269 public boolean disableNetwork(int netId) {
1270 enforceChangePermission();
1271
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001272 return mWifiStateTracker.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274
1275 /**
1276 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1277 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1278 */
1279 public WifiInfo getConnectionInfo() {
1280 enforceAccessPermission();
1281 /*
1282 * Make sure we have the latest information, by sending
1283 * a status request to the supplicant.
1284 */
1285 return mWifiStateTracker.requestConnectionInfo();
1286 }
1287
1288 /**
1289 * Return the results of the most recent access point scan, in the form of
1290 * a list of {@link ScanResult} objects.
1291 * @return the list of results
1292 */
1293 public List<ScanResult> getScanResults() {
1294 enforceAccessPermission();
1295 String reply;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001296
1297 reply = mWifiStateTracker.scanResults();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 if (reply == null) {
1299 return null;
1300 }
1301
1302 List<ScanResult> scanList = new ArrayList<ScanResult>();
1303
1304 int lineCount = 0;
1305
1306 int replyLen = reply.length();
1307 // Parse the result string, keeping in mind that the last line does
1308 // not end with a newline.
1309 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1310 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1311 ++lineCount;
1312 /*
1313 * Skip the first line, which is a header
1314 */
1315 if (lineCount == 1) {
1316 lineBeg = lineEnd + 1;
1317 continue;
1318 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001319 if (lineEnd > lineBeg) {
1320 String line = reply.substring(lineBeg, lineEnd);
1321 ScanResult scanResult = parseScanResult(line);
1322 if (scanResult != null) {
1323 scanList.add(scanResult);
1324 } else if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001325 Slog.w(TAG, "misformatted scan result for: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
1327 }
1328 lineBeg = lineEnd + 1;
1329 }
1330 }
1331 mWifiStateTracker.setScanResultsList(scanList);
1332 return scanList;
1333 }
1334
1335 /**
1336 * Parse the scan result line passed to us by wpa_supplicant (helper).
1337 * @param line the line to parse
1338 * @return the {@link ScanResult} object
1339 */
1340 private ScanResult parseScanResult(String line) {
1341 ScanResult scanResult = null;
1342 if (line != null) {
1343 /*
1344 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1345 * must synchronized here!
1346 */
1347 synchronized (mScanResultCache) {
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001348 String[] result = scanResultPattern.split(line);
1349 if (3 <= result.length && result.length <= 5) {
1350 String bssid = result[0];
1351 // bssid | frequency | level | flags | ssid
1352 int frequency;
1353 int level;
1354 try {
1355 frequency = Integer.parseInt(result[1]);
1356 level = Integer.parseInt(result[2]);
1357 /* some implementations avoid negative values by adding 256
1358 * so we need to adjust for that here.
1359 */
1360 if (level > 0) level -= 256;
1361 } catch (NumberFormatException e) {
1362 frequency = 0;
1363 level = 0;
1364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365
Mike Lockwood1a645052009-06-25 13:01:12 -04001366 /*
1367 * The formatting of the results returned by
1368 * wpa_supplicant is intended to make the fields
1369 * line up nicely when printed,
1370 * not to make them easy to parse. So we have to
1371 * apply some heuristics to figure out which field
1372 * is the SSID and which field is the flags.
1373 */
1374 String ssid;
1375 String flags;
1376 if (result.length == 4) {
1377 if (result[3].charAt(0) == '[') {
1378 flags = result[3];
1379 ssid = "";
1380 } else {
1381 flags = "";
1382 ssid = result[3];
1383 }
1384 } else if (result.length == 5) {
1385 flags = result[3];
1386 ssid = result[4];
1387 } else {
1388 // Here, we must have 3 fields: no flags and ssid
1389 // set
1390 flags = "";
1391 ssid = "";
1392 }
1393
Mike Lockwood00717e22009-08-17 10:09:36 -04001394 // bssid + ssid is the hash key
1395 String key = bssid + ssid;
1396 scanResult = mScanResultCache.get(key);
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001397 if (scanResult != null) {
1398 scanResult.level = level;
Mike Lockwood1a645052009-06-25 13:01:12 -04001399 scanResult.SSID = ssid;
1400 scanResult.capabilities = flags;
1401 scanResult.frequency = frequency;
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001402 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 // Do not add scan results that have no SSID set
1404 if (0 < ssid.trim().length()) {
1405 scanResult =
1406 new ScanResult(
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001407 ssid, bssid, flags, level, frequency);
Mike Lockwood00717e22009-08-17 10:09:36 -04001408 mScanResultCache.put(key, scanResult);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001411 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001412 Slog.w(TAG, "Misformatted scan result text with " +
Mike Lockwoodb30475e2009-04-21 13:55:07 -07001413 result.length + " fields: " + line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 }
1416 }
1417
1418 return scanResult;
1419 }
1420
1421 /**
1422 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1423 * and construct a {@code WifiConfiguration} that describes the encryption,
1424 * key management, and authenticaion capabilities of the access point.
1425 * @param flags the string returned by wpa_supplicant
1426 * @return the {@link WifiConfiguration} object, filled in
1427 */
1428 WifiConfiguration parseScanFlags(String flags) {
1429 WifiConfiguration config = new WifiConfiguration();
1430
1431 if (flags.length() == 0) {
1432 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1433 }
1434 // ... to be implemented
1435 return config;
1436 }
1437
1438 /**
1439 * Tell the supplicant to persist the current list of configured networks.
1440 * @return {@code true} if the operation succeeded
1441 */
1442 public boolean saveConfiguration() {
1443 boolean result;
1444 enforceChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 synchronized (mWifiStateTracker) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001447 result = mWifiStateTracker.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 if (result && mNeedReconfig) {
1449 mNeedReconfig = false;
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001450 result = mWifiStateTracker.reloadConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451
1452 if (result) {
1453 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1454 mContext.sendBroadcast(intent);
1455 }
1456 }
1457 }
Amith Yamasani47873e52009-07-02 12:05:32 -07001458 // Inform the backup manager about a data change
1459 IBackupManager ibm = IBackupManager.Stub.asInterface(
1460 ServiceManager.getService(Context.BACKUP_SERVICE));
1461 if (ibm != null) {
1462 try {
1463 ibm.dataChanged("com.android.providers.settings");
1464 } catch (Exception e) {
1465 // Try again later
1466 }
1467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 return result;
1469 }
1470
1471 /**
1472 * Set the number of radio frequency channels that are allowed to be used
1473 * in the current regulatory domain. This method should be used only
1474 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001475 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 * persisted as a Secure setting.
1477 * @param numChannels the number of allowed channels. Must be greater than 0
1478 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001479 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1481 * {@code numChannels} is outside the valid range.
1482 */
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001483 public boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001484 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001485 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 enforceChangePermission();
1487 /*
1488 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1489 * but if Wi-Fi isn't currently enabled, that's not possible, and
1490 * we want to persist the setting anyway,so that it will take
1491 * effect when Wi-Fi does become enabled.
1492 */
1493 boolean found = false;
1494 for (int validChan : sValidRegulatoryChannelCounts) {
1495 if (validChan == numChannels) {
1496 found = true;
1497 break;
1498 }
1499 }
1500 if (!found) {
1501 return false;
1502 }
1503
Robert Greenwaltb5010cc2009-05-21 15:11:40 -07001504 if (persist) {
1505 Settings.Secure.putInt(mContext.getContentResolver(),
1506 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1507 numChannels);
1508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 mWifiStateTracker.setNumAllowedChannels(numChannels);
1510 return true;
1511 }
1512
1513 /**
1514 * Return the number of frequency channels that are allowed
1515 * to be used in the current regulatory domain.
1516 * @return the number of allowed channels, or {@code -1} if an error occurs
1517 */
1518 public int getNumAllowedChannels() {
1519 int numChannels;
1520
1521 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001522
1523 /*
1524 * If we can't get the value from the driver (e.g., because
1525 * Wi-Fi is not currently enabled), get the value from
1526 * Settings.
1527 */
1528 numChannels = mWifiStateTracker.getNumAllowedChannels();
1529 if (numChannels < 0) {
1530 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1531 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1532 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 return numChannels;
1535 }
1536
1537 /**
1538 * Return the list of valid values for the number of allowed radio channels
1539 * for various regulatory domains.
1540 * @return the list of channel counts
1541 */
1542 public int[] getValidChannelCounts() {
1543 enforceAccessPermission();
1544 return sValidRegulatoryChannelCounts;
1545 }
1546
1547 /**
1548 * Return the DHCP-assigned addresses from the last successful DHCP request,
1549 * if any.
1550 * @return the DHCP information
1551 */
1552 public DhcpInfo getDhcpInfo() {
1553 enforceAccessPermission();
1554 return mWifiStateTracker.getDhcpInfo();
1555 }
1556
1557 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1558 @Override
1559 public void onReceive(Context context, Intent intent) {
1560 String action = intent.getAction();
1561
Doug Zongker43866e02010-01-07 12:09:54 -08001562 long idleMillis =
1563 Settings.Secure.getLong(mContext.getContentResolver(),
1564 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -08001566 Settings.System.getInt(mContext.getContentResolver(),
1567 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001569 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 mAlarmManager.cancel(mIdleIntent);
1571 mDeviceIdle = false;
1572 mScreenOff = false;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001573 mWifiStateTracker.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001575 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 mScreenOff = true;
Mike Lockwoodf32be162009-07-14 17:44:37 -04001577 mWifiStateTracker.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 /*
1579 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1580 * AND the "stay on while plugged in" setting doesn't match the
1581 * current power conditions (i.e, not plugged in, plugged in to USB,
1582 * or plugged in to AC).
1583 */
1584 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
San Mehatfa6c7112009-07-07 09:34:44 -07001585 WifiInfo info = mWifiStateTracker.requestConnectionInfo();
1586 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001587 // we used to go to sleep immediately, but this caused some race conditions
1588 // we don't have time to track down for this release. Delay instead, but not
1589 // as long as we would if connected (below)
1590 // TODO - fix the race conditions and switch back to the immediate turn-off
1591 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -08001592 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -07001593 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1594 // // do not keep Wifi awake when screen is off if Wifi is not associated
1595 // mDeviceIdle = true;
1596 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001597 } else {
1598 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001599 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001600 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 /* we can return now -- there's nothing to do until we get the idle intent back */
1604 return;
1605 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001606 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 mDeviceIdle = true;
1608 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1609 /*
1610 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1611 * AND we are transitioning from a state in which the device was supposed
1612 * to stay awake to a state in which it is not supposed to stay awake.
1613 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1614 * the already-set timer.
1615 */
1616 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1619 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1620 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1623 mPluggedType = pluggedType;
1624 return;
1625 }
1626 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -07001627 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001628 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
1629 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
1630 boolean isBluetoothPlaying = false;
1631 for (BluetoothDevice sink : sinks) {
1632 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
1633 isBluetoothPlaying = true;
1634 }
1635 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001636 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 } else {
1639 return;
1640 }
1641
1642 updateWifiState();
1643 }
1644
1645 /**
1646 * Determines whether the Wi-Fi chipset should stay awake or be put to
1647 * sleep. Looks at the setting for the sleep policy and the current
1648 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001649 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 * @see #shouldDeviceStayAwake(int, int)
1651 */
1652 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1653 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1654 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1655
1656 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1657 // Never sleep
1658 return true;
1659 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1660 (pluggedType != 0)) {
1661 // Never sleep while plugged, and we're plugged
1662 return true;
1663 } else {
1664 // Default
1665 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1666 }
1667 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 /**
1670 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1671 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1672 * of {@code 0} isn't really a plugged type, but rather an indication that the
1673 * device isn't plugged in at all, there is no bit value corresponding to a
1674 * {@code pluggedType} value of {@code 0}. That is why we shift by
1675 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1676 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1677 * keep the device (and hence Wi-Fi) awake.
1678 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1679 * being made
1680 * @return {@code true} if {@code pluggedType} indicates that the device is
1681 * supposed to stay awake, {@code false} otherwise.
1682 */
1683 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1684 return (stayAwakeConditions & pluggedType) != 0;
1685 }
1686 };
1687
Dianne Hackborn617f8772009-03-31 15:04:46 -07001688 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 Message msg = Message.obtain(mWifiHandler,
1690 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001691 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 msg.sendToTarget();
1693 }
1694
1695 private void sendStartMessage(boolean scanOnlyMode) {
1696 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1697 }
1698
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001699 private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
1700 Message.obtain(mWifiHandler,
1701 (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
1702 0, uid, wifiConfig).sendToTarget();
1703 }
1704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 private void updateWifiState() {
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001706 // send a message so it's all serialized
1707 Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
1708 }
1709
1710 private void doUpdateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 boolean wifiEnabled = getPersistedWifiEnabled();
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001712 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 boolean lockHeld = mLocks.hasLocks();
1714 int strongestLockMode;
1715 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1716 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1717 if (mDeviceIdle && lockHeld) {
1718 strongestLockMode = mLocks.getStrongestLockMode();
1719 } else {
1720 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1721 }
1722
1723 synchronized (mWifiHandler) {
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001724 if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 return;
1726 }
1727 if (wifiShouldBeEnabled) {
1728 if (wifiShouldBeStarted) {
1729 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001730 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 sWakeLock.acquire();
1732 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1733 } else {
1734 int wakeLockTimeout =
1735 Settings.Secure.getInt(
1736 mContext.getContentResolver(),
1737 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1738 DEFAULT_WAKELOCK_TIMEOUT);
1739 /*
1740 * The following wakelock is held in order to ensure
1741 * that the connectivity manager has time to fail over
1742 * to the mobile data network. The connectivity manager
1743 * releases it once mobile data connectivity has been
1744 * established. If connectivity cannot be established,
1745 * the wakelock is released after wakeLockTimeout
1746 * milliseconds have elapsed.
1747 */
1748 sDriverStopWakeLock.acquire();
1749 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1750 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1751 }
1752 } else {
1753 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001754 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756 }
1757 }
1758
1759 private void registerForBroadcasts() {
1760 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1762 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1763 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1764 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001765 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 mContext.registerReceiver(mReceiver, intentFilter);
1767 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 private boolean isAirplaneSensitive() {
1770 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1771 Settings.System.AIRPLANE_MODE_RADIOS);
1772 return airplaneModeRadios == null
1773 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1774 }
1775
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001776 private boolean isAirplaneToggleable() {
1777 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1778 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1779 return toggleableRadios != null
1780 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 /**
1784 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1785 * currently on.
1786 * @return {@code true} if airplane mode is on.
1787 */
1788 private boolean isAirplaneModeOn() {
1789 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1790 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1791 }
1792
1793 /**
1794 * Handler that allows posting to the WifiThread.
1795 */
1796 private class WifiHandler extends Handler {
1797 public WifiHandler(Looper looper) {
1798 super(looper);
1799 }
1800
1801 @Override
1802 public void handleMessage(Message msg) {
1803 switch (msg.what) {
1804
1805 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001806 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 sWakeLock.release();
1808 break;
1809
1810 case MESSAGE_START_WIFI:
1811 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1812 mWifiStateTracker.restart();
1813 sWakeLock.release();
1814 break;
1815
Robert Greenwaltf75aa36fc2009-10-22 17:03:47 -07001816 case MESSAGE_UPDATE_STATE:
1817 doUpdateWifiState();
1818 break;
1819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 case MESSAGE_DISABLE_WIFI:
1821 // a non-zero msg.arg1 value means the "enabled" setting
1822 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001823 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 sWakeLock.release();
1825 break;
1826
1827 case MESSAGE_STOP_WIFI:
1828 mWifiStateTracker.disconnectAndStop();
1829 // don't release wakelock
1830 break;
1831
1832 case MESSAGE_RELEASE_WAKELOCK:
1833 synchronized (sDriverStopWakeLock) {
1834 if (sDriverStopWakeLock.isHeld()) {
1835 sDriverStopWakeLock.release();
1836 }
1837 }
1838 break;
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001839
1840 case MESSAGE_START_ACCESS_POINT:
1841 setWifiApEnabledBlocking(true,
1842 msg.arg1 == 1,
1843 msg.arg2,
1844 (WifiConfiguration) msg.obj);
1845 break;
1846
1847 case MESSAGE_STOP_ACCESS_POINT:
1848 setWifiApEnabledBlocking(false,
1849 msg.arg1 == 1,
1850 msg.arg2,
1851 (WifiConfiguration) msg.obj);
1852 sWakeLock.release();
1853 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
1855 }
1856 }
1857
1858 @Override
1859 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1860 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1861 != PackageManager.PERMISSION_GRANTED) {
1862 pw.println("Permission Denial: can't dump WifiService from from pid="
1863 + Binder.getCallingPid()
1864 + ", uid=" + Binder.getCallingUid());
1865 return;
1866 }
Irfan Sheriff0f344060092010-03-10 10:05:51 -08001867 pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 pw.println("Stay-awake conditions: " +
1869 Settings.System.getInt(mContext.getContentResolver(),
1870 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1871 pw.println();
1872
1873 pw.println("Internal state:");
1874 pw.println(mWifiStateTracker);
1875 pw.println();
1876 pw.println("Latest scan results:");
1877 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1878 if (scanResults != null && scanResults.size() != 0) {
1879 pw.println(" BSSID Frequency RSSI Flags SSID");
1880 for (ScanResult r : scanResults) {
1881 pw.printf(" %17s %9d %5d %-16s %s%n",
1882 r.BSSID,
1883 r.frequency,
1884 r.level,
1885 r.capabilities,
1886 r.SSID == null ? "" : r.SSID);
1887 }
1888 }
1889 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001890 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1891 mScanLocksAcquired + " scan");
1892 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1893 mScanLocksReleased + " scan");
1894 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 pw.println("Locks held:");
1896 mLocks.dump(pw);
1897 }
1898
1899 private static String stateName(int wifiState) {
1900 switch (wifiState) {
1901 case WIFI_STATE_DISABLING:
1902 return "disabling";
1903 case WIFI_STATE_DISABLED:
1904 return "disabled";
1905 case WIFI_STATE_ENABLING:
1906 return "enabling";
1907 case WIFI_STATE_ENABLED:
1908 return "enabled";
1909 case WIFI_STATE_UNKNOWN:
1910 return "unknown state";
1911 default:
1912 return "[invalid state]";
1913 }
1914 }
1915
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001916 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001918 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920
1921 public void binderDied() {
1922 synchronized (mLocks) {
1923 releaseWifiLockLocked(mBinder);
1924 }
1925 }
1926
1927 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001928 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930 }
1931
1932 private class LockList {
1933 private List<WifiLock> mList;
1934
1935 private LockList() {
1936 mList = new ArrayList<WifiLock>();
1937 }
1938
1939 private synchronized boolean hasLocks() {
1940 return !mList.isEmpty();
1941 }
1942
1943 private synchronized int getStrongestLockMode() {
1944 if (mList.isEmpty()) {
1945 return WifiManager.WIFI_MODE_FULL;
1946 }
1947 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001948 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 return WifiManager.WIFI_MODE_FULL;
1950 }
1951 }
1952 return WifiManager.WIFI_MODE_SCAN_ONLY;
1953 }
1954
1955 private void addLock(WifiLock lock) {
1956 if (findLockByBinder(lock.mBinder) < 0) {
1957 mList.add(lock);
1958 }
1959 }
1960
1961 private WifiLock removeLock(IBinder binder) {
1962 int index = findLockByBinder(binder);
1963 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001964 WifiLock ret = mList.remove(index);
1965 ret.unlinkDeathRecipient();
1966 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 } else {
1968 return null;
1969 }
1970 }
1971
1972 private int findLockByBinder(IBinder binder) {
1973 int size = mList.size();
1974 for (int i = size - 1; i >= 0; i--)
1975 if (mList.get(i).mBinder == binder)
1976 return i;
1977 return -1;
1978 }
1979
1980 private void dump(PrintWriter pw) {
1981 for (WifiLock l : mList) {
1982 pw.print(" ");
1983 pw.println(l);
1984 }
1985 }
1986 }
1987
1988 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1990 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1991 return false;
1992 }
1993 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1994 synchronized (mLocks) {
1995 return acquireWifiLockLocked(wifiLock);
1996 }
1997 }
1998
1999 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002000 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002003
The Android Open Source Project10592532009-03-18 17:39:46 -07002004 int uid = Binder.getCallingUid();
2005 long ident = Binder.clearCallingIdentity();
2006 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002007 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002008 case WifiManager.WIFI_MODE_FULL:
2009 ++mFullLocksAcquired;
2010 mBatteryStats.noteFullWifiLockAcquired(uid);
2011 break;
2012 case WifiManager.WIFI_MODE_SCAN_ONLY:
2013 ++mScanLocksAcquired;
2014 mBatteryStats.noteScanWifiLockAcquired(uid);
2015 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002016 }
2017 } catch (RemoteException e) {
2018 } finally {
2019 Binder.restoreCallingIdentity(ident);
2020 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 updateWifiState();
2023 return true;
2024 }
2025
2026 public boolean releaseWifiLock(IBinder lock) {
2027 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2028 synchronized (mLocks) {
2029 return releaseWifiLockLocked(lock);
2030 }
2031 }
2032
2033 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002034 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002035
The Android Open Source Project10592532009-03-18 17:39:46 -07002036 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002037
Joe Onorato8a9b2202010-02-26 18:56:32 -08002038 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002039
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002040 hadLock = (wifiLock != null);
2041
2042 if (hadLock) {
2043 int uid = Binder.getCallingUid();
2044 long ident = Binder.clearCallingIdentity();
2045 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002046 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07002047 case WifiManager.WIFI_MODE_FULL:
2048 ++mFullLocksReleased;
2049 mBatteryStats.noteFullWifiLockReleased(uid);
2050 break;
2051 case WifiManager.WIFI_MODE_SCAN_ONLY:
2052 ++mScanLocksReleased;
2053 mBatteryStats.noteScanWifiLockReleased(uid);
2054 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002055 }
2056 } catch (RemoteException e) {
2057 } finally {
2058 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07002059 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002060 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07002061 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07002063 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002065
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002066 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002067 implements IBinder.DeathRecipient {
2068 String mTag;
2069 int mMode;
2070 IBinder mBinder;
2071
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002072 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002073 super();
2074 mTag = tag;
2075 mMode = mode;
2076 mBinder = binder;
2077 try {
2078 mBinder.linkToDeath(this, 0);
2079 } catch (RemoteException e) {
2080 binderDied();
2081 }
2082 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002083
2084 void unlinkDeathRecipient() {
2085 mBinder.unlinkToDeath(this, 0);
2086 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002087 }
2088
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002089 private class Multicaster extends DeathRecipient {
2090 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002091 super(Binder.getCallingUid(), tag, binder);
2092 }
2093
2094 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002095 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002096 synchronized (mMulticasters) {
2097 int i = mMulticasters.indexOf(this);
2098 if (i != -1) {
2099 removeMulticasterLocked(i, mMode);
2100 }
2101 }
2102 }
2103
2104 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002105 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002106 }
2107
2108 public int getUid() {
2109 return mMode;
2110 }
2111 }
2112
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002113 public void initializeMulticastFiltering() {
2114 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002115
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002116 synchronized (mMulticasters) {
2117 // if anybody had requested filters be off, leave off
2118 if (mMulticasters.size() != 0) {
2119 return;
2120 } else {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002121 mWifiStateTracker.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07002122 }
2123 }
2124 }
2125
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002126 public void acquireMulticastLock(IBinder binder, String tag) {
2127 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002128
2129 synchronized (mMulticasters) {
2130 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002131 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002132 // Note that we could call stopPacketFiltering only when
2133 // our new size == 1 (first call), but this function won't
2134 // be called often and by making the stopPacket call each
2135 // time we're less fragile and self-healing.
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002136 mWifiStateTracker.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002137 }
2138
2139 int uid = Binder.getCallingUid();
2140 Long ident = Binder.clearCallingIdentity();
2141 try {
2142 mBatteryStats.noteWifiMulticastEnabled(uid);
2143 } catch (RemoteException e) {
2144 } finally {
2145 Binder.restoreCallingIdentity(ident);
2146 }
2147 }
2148
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07002149 public void releaseMulticastLock() {
2150 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002151
2152 int uid = Binder.getCallingUid();
2153 synchronized (mMulticasters) {
2154 mMulticastDisabled++;
2155 int size = mMulticasters.size();
2156 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002157 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002158 if ((m != null) && (m.getUid() == uid)) {
2159 removeMulticasterLocked(i, uid);
2160 }
2161 }
2162 }
2163 }
2164
2165 private void removeMulticasterLocked(int i, int uid)
2166 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002167 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002168
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07002169 if (removed != null) {
2170 removed.unlinkDeathRecipient();
2171 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002172 if (mMulticasters.size() == 0) {
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08002173 mWifiStateTracker.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002174 }
2175
2176 Long ident = Binder.clearCallingIdentity();
2177 try {
2178 mBatteryStats.noteWifiMulticastDisabled(uid);
2179 } catch (RemoteException e) {
2180 } finally {
2181 Binder.restoreCallingIdentity(ident);
2182 }
2183 }
2184
Robert Greenwalt58ff0212009-05-19 15:53:54 -07002185 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07002186 enforceAccessPermission();
2187
2188 synchronized (mMulticasters) {
2189 return (mMulticasters.size() > 0);
2190 }
2191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192}