WifiServiceImpl.java revision 8be2ac8cec40a2000715849b627642bdc87c10b3
1/*
2 * Copyright (C) 2010 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.wifi;
18
19import android.Manifest;
20import android.app.ActivityManager;
21import android.app.AppOpsManager;
22import android.bluetooth.BluetoothAdapter;
23import android.content.BroadcastReceiver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.PackageManager;
28import android.content.pm.UserInfo;
29import android.database.ContentObserver;
30import android.net.ConnectivityManager;
31import android.net.DhcpInfo;
32import android.net.DhcpResults;
33import android.net.Network;
34import android.net.NetworkScorerAppManager;
35import android.net.NetworkUtils;
36import android.net.Uri;
37import android.net.wifi.BatchedScanResult;
38import android.net.wifi.BatchedScanSettings;
39import android.net.wifi.IWifiManager;
40import android.net.wifi.ScanResult;
41import android.net.wifi.ScanSettings;
42import android.net.wifi.WifiActivityEnergyInfo;
43import android.net.wifi.WifiChannel;
44import android.net.wifi.WifiConfiguration;
45import android.net.wifi.WifiConnectionStatistics;
46import android.net.wifi.WifiEnterpriseConfig;
47import android.net.wifi.WifiInfo;
48import android.net.wifi.WifiLinkLayerStats;
49import android.net.wifi.WifiManager;
50import android.os.AsyncTask;
51import android.os.Binder;
52import android.os.Build;
53import android.os.Handler;
54import android.os.HandlerThread;
55import android.os.IBinder;
56import android.os.Message;
57import android.os.Messenger;
58import android.os.PowerManager;
59import android.os.RemoteException;
60import android.os.SystemClock;
61import android.os.SystemProperties;
62import android.os.UserHandle;
63import android.os.UserManager;
64import android.os.WorkSource;
65import android.provider.Settings;
66import android.text.TextUtils;
67import android.util.Log;
68import android.util.Slog;
69
70import com.android.internal.R;
71import com.android.internal.app.IBatteryStats;
72import com.android.internal.telephony.TelephonyIntents;
73import com.android.internal.util.AsyncChannel;
74import com.android.server.am.BatteryStatsService;
75import com.android.server.wifi.configparse.ConfigBuilder;
76
77import org.xml.sax.SAXException;
78
79import java.io.BufferedReader;
80import java.io.FileDescriptor;
81import java.io.FileNotFoundException;
82import java.io.FileReader;
83import java.io.IOException;
84import java.io.PrintWriter;
85import java.net.Inet4Address;
86import java.net.InetAddress;
87import java.security.GeneralSecurityException;
88import java.security.KeyStore;
89import java.security.cert.CertPath;
90import java.security.cert.CertPathValidator;
91import java.security.cert.CertPathValidatorException;
92import java.security.cert.CertificateFactory;
93import java.security.cert.PKIXParameters;
94import java.security.cert.X509Certificate;
95import java.util.ArrayList;
96import java.util.Arrays;
97import java.util.List;
98
99import static com.android.server.wifi.WifiController.CMD_AIRPLANE_TOGGLED;
100import static com.android.server.wifi.WifiController.CMD_BATTERY_CHANGED;
101import static com.android.server.wifi.WifiController.CMD_EMERGENCY_MODE_CHANGED;
102import static com.android.server.wifi.WifiController.CMD_LOCKS_CHANGED;
103import static com.android.server.wifi.WifiController.CMD_SCAN_ALWAYS_MODE_CHANGED;
104import static com.android.server.wifi.WifiController.CMD_SCREEN_OFF;
105import static com.android.server.wifi.WifiController.CMD_SCREEN_ON;
106import static com.android.server.wifi.WifiController.CMD_SET_AP;
107import static com.android.server.wifi.WifiController.CMD_USER_PRESENT;
108import static com.android.server.wifi.WifiController.CMD_WIFI_TOGGLED;
109/**
110 * WifiService handles remote WiFi operation requests by implementing
111 * the IWifiManager interface.
112 *
113 * @hide
114 */
115public final class WifiServiceImpl extends IWifiManager.Stub {
116    private static final String TAG = "WifiService";
117    private static final boolean DBG = true;
118    private static final boolean VDBG = false;
119
120    final WifiStateMachine mWifiStateMachine;
121
122    private final Context mContext;
123
124    final LockList mLocks = new LockList();
125    // some wifi lock statistics
126    private int mFullHighPerfLocksAcquired;
127    private int mFullHighPerfLocksReleased;
128    private int mFullLocksAcquired;
129    private int mFullLocksReleased;
130    private int mScanLocksAcquired;
131    private int mScanLocksReleased;
132
133    private final List<Multicaster> mMulticasters =
134            new ArrayList<Multicaster>();
135    private int mMulticastEnabled;
136    private int mMulticastDisabled;
137
138    private final IBatteryStats mBatteryStats;
139    private final PowerManager mPowerManager;
140    private final AppOpsManager mAppOps;
141    private final UserManager mUserManager;
142
143    private String mInterfaceName;
144
145    // Debug counter tracking scan requests sent by WifiManager
146    private int scanRequestCounter = 0;
147
148    /* Tracks the open wi-fi network notification */
149    private WifiNotificationController mNotificationController;
150    /* Polls traffic stats and notifies clients */
151    private WifiTrafficPoller mTrafficPoller;
152    /* Tracks the persisted states for wi-fi & airplane mode */
153    final WifiSettingsStore mSettingsStore;
154
155    /**
156     * Asynchronous channel to WifiStateMachine
157     */
158    private AsyncChannel mWifiStateMachineChannel;
159
160    /**
161     * Handles client connections
162     */
163    private class ClientHandler extends Handler {
164
165        ClientHandler(android.os.Looper looper) {
166            super(looper);
167        }
168
169        @Override
170        public void handleMessage(Message msg) {
171            switch (msg.what) {
172                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
173                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
174                        if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
175                        // We track the clients by the Messenger
176                        // since it is expected to be always available
177                        mTrafficPoller.addClient(msg.replyTo);
178                    } else {
179                        Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
180                    }
181                    break;
182                }
183                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
184                    if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
185                        if (DBG) Slog.d(TAG, "Send failed, client connection lost");
186                    } else {
187                        if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
188                    }
189                    mTrafficPoller.removeClient(msg.replyTo);
190                    break;
191                }
192                case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
193                    AsyncChannel ac = new AsyncChannel();
194                    ac.connect(mContext, this, msg.replyTo);
195                    break;
196                }
197                /* Client commands are forwarded to state machine */
198                case WifiManager.CONNECT_NETWORK:
199                case WifiManager.SAVE_NETWORK: {
200                    WifiConfiguration config = (WifiConfiguration) msg.obj;
201                    int networkId = msg.arg1;
202                    if (msg.what == WifiManager.SAVE_NETWORK) {
203                        Slog.e("WiFiServiceImpl ", "SAVE"
204                                + " nid=" + Integer.toString(networkId)
205                                + " uid=" + msg.sendingUid
206                                + " name="
207                                + mContext.getPackageManager().getNameForUid(msg.sendingUid));
208                    }
209                    if (msg.what == WifiManager.CONNECT_NETWORK) {
210                        Slog.e("WiFiServiceImpl ", "CONNECT "
211                                + " nid=" + Integer.toString(networkId)
212                                + " uid=" + msg.sendingUid
213                                + " name="
214                                + mContext.getPackageManager().getNameForUid(msg.sendingUid));
215                    }
216
217                    if (config != null && isValid(config)) {
218                        if (DBG) Slog.d(TAG, "Connect with config" + config);
219                        mWifiStateMachine.sendMessage(Message.obtain(msg));
220                    } else if (config == null
221                            && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
222                        if (DBG) Slog.d(TAG, "Connect with networkId" + networkId);
223                        mWifiStateMachine.sendMessage(Message.obtain(msg));
224                    } else {
225                        Slog.e(TAG, "ClientHandler.handleMessage ignoring invalid msg=" + msg);
226                        if (msg.what == WifiManager.CONNECT_NETWORK) {
227                            replyFailed(msg, WifiManager.CONNECT_NETWORK_FAILED,
228                                    WifiManager.INVALID_ARGS);
229                        } else {
230                            replyFailed(msg, WifiManager.SAVE_NETWORK_FAILED,
231                                    WifiManager.INVALID_ARGS);
232                        }
233                    }
234                    break;
235                }
236                case WifiManager.FORGET_NETWORK:
237                    if (isOwner(msg.sendingUid)) {
238                        mWifiStateMachine.sendMessage(Message.obtain(msg));
239                    } else {
240                        Slog.e(TAG, "Forget is not authorized for user");
241                        replyFailed(msg, WifiManager.FORGET_NETWORK_FAILED,
242                                WifiManager.NOT_AUTHORIZED);
243                    }
244                    break;
245                case WifiManager.START_WPS:
246                case WifiManager.CANCEL_WPS:
247                case WifiManager.DISABLE_NETWORK:
248                case WifiManager.RSSI_PKTCNT_FETCH: {
249                    mWifiStateMachine.sendMessage(Message.obtain(msg));
250                    break;
251                }
252                default: {
253                    Slog.d(TAG, "ClientHandler.handleMessage ignoring msg=" + msg);
254                    break;
255                }
256            }
257        }
258
259        private void replyFailed(Message msg, int what, int why) {
260            Message reply = msg.obtain();
261            reply.what = what;
262            reply.arg1 = why;
263            try {
264                msg.replyTo.send(reply);
265            } catch (RemoteException e) {
266                // There's not much we can do if reply can't be sent!
267            }
268        }
269    }
270    private ClientHandler mClientHandler;
271
272    /**
273     * Handles interaction with WifiStateMachine
274     */
275    private class WifiStateMachineHandler extends Handler {
276        private AsyncChannel mWsmChannel;
277
278        WifiStateMachineHandler(android.os.Looper looper) {
279            super(looper);
280            mWsmChannel = new AsyncChannel();
281            mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
282        }
283
284        @Override
285        public void handleMessage(Message msg) {
286            switch (msg.what) {
287                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
288                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
289                        mWifiStateMachineChannel = mWsmChannel;
290                    } else {
291                        Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
292                        mWifiStateMachineChannel = null;
293                    }
294                    break;
295                }
296                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
297                    Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
298                    mWifiStateMachineChannel = null;
299                    //Re-establish connection to state machine
300                    mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
301                    break;
302                }
303                default: {
304                    Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
305                    break;
306                }
307            }
308        }
309    }
310
311    WifiStateMachineHandler mWifiStateMachineHandler;
312
313    private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
314
315    private WifiController mWifiController;
316
317    public WifiServiceImpl(Context context) {
318        mContext = context;
319
320        mInterfaceName =  SystemProperties.get("wifi.interface", "wlan0");
321
322        mTrafficPoller = new WifiTrafficPoller(mContext, mInterfaceName);
323        mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName, mTrafficPoller);
324        mWifiStateMachine.enableRssiPolling(true);
325        mBatteryStats = BatteryStatsService.getService();
326        mPowerManager = context.getSystemService(PowerManager.class);
327        mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
328        mUserManager = UserManager.get(mContext);
329
330        mNotificationController = new WifiNotificationController(mContext, mWifiStateMachine);
331        mSettingsStore = new WifiSettingsStore(mContext);
332
333        HandlerThread wifiThread = new HandlerThread("WifiService");
334        wifiThread.start();
335        mClientHandler = new ClientHandler(wifiThread.getLooper());
336        mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
337        mWifiController = new WifiController(mContext, this, wifiThread.getLooper());
338    }
339
340
341    /**
342     * Check if Wi-Fi needs to be enabled and start
343     * if needed
344     *
345     * This function is used only at boot time
346     */
347    public void checkAndStartWifi() {
348        /* Check if wi-fi needs to be enabled */
349        boolean wifiEnabled = mSettingsStore.isWifiToggleEnabled();
350        Slog.i(TAG, "WifiService starting up with Wi-Fi " +
351                (wifiEnabled ? "enabled" : "disabled"));
352
353        registerForScanModeChange();
354        mContext.registerReceiver(
355                new BroadcastReceiver() {
356                    @Override
357                    public void onReceive(Context context, Intent intent) {
358                        if (mSettingsStore.handleAirplaneModeToggled()) {
359                            mWifiController.sendMessage(CMD_AIRPLANE_TOGGLED);
360                        }
361                    }
362                },
363                new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
364
365        // Adding optimizations of only receiving broadcasts when wifi is enabled
366        // can result in race conditions when apps toggle wifi in the background
367        // without active user involvement. Always receive broadcasts.
368        registerForBroadcasts();
369        registerForPackageOrUserRemoval();
370        mInIdleMode = mPowerManager.isDeviceIdleMode();
371
372        mWifiController.start();
373
374        // If we are already disabled (could be due to airplane mode), avoid changing persist
375        // state here
376        if (wifiEnabled) setWifiEnabled(wifiEnabled);
377
378        mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
379               makeWifiWatchdogStateMachine(mContext, mWifiStateMachine.getMessenger());
380    }
381
382    /**
383     * see {@link android.net.wifi.WifiManager#pingSupplicant()}
384     * @return {@code true} if the operation succeeds, {@code false} otherwise
385     */
386    public boolean pingSupplicant() {
387        enforceAccessPermission();
388        if (mWifiStateMachineChannel != null) {
389            return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
390        } else {
391            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
392            return false;
393        }
394    }
395
396    /**
397     * see {@link android.net.wifi.WifiManager#getChannelList}
398     */
399    public List<WifiChannel> getChannelList() {
400        enforceAccessPermission();
401        if (mWifiStateMachineChannel != null) {
402            return mWifiStateMachine.syncGetChannelList(mWifiStateMachineChannel);
403        } else {
404            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
405            return null;
406        }
407    }
408
409    // Start a location scan.
410    // L release: A location scan is implemented as a normal scan and avoids scanning DFS channels
411    // Deprecated: Will soon remove implementation
412    public void startLocationRestrictedScan(WorkSource workSource) {
413        enforceChangePermission();
414        enforceLocationHardwarePermission();
415        List<WifiChannel> channels = getChannelList();
416        if (channels == null) {
417            Slog.e(TAG, "startLocationRestrictedScan cant get channels");
418            return;
419        }
420        ScanSettings settings = new ScanSettings();
421        for (WifiChannel channel : channels) {
422            if (!channel.isDFS) {
423                settings.channelSet.add(channel);
424            }
425        }
426        if (workSource == null) {
427            // Make sure we always have a workSource indicating the origin of the scan
428            // hence if there is none, pick an internal WifiStateMachine one
429            workSource = new WorkSource(WifiStateMachine.DFS_RESTRICTED_SCAN_REQUEST);
430        }
431        startScan(settings, workSource);
432    }
433
434    /**
435     * see {@link android.net.wifi.WifiManager#startScan}
436     * and {@link android.net.wifi.WifiManager#startCustomizedScan}
437     *
438     * @param settings If null, use default parameter, i.e. full scan.
439     * @param workSource If null, all blame is given to the calling uid.
440     */
441    public void startScan(ScanSettings settings, WorkSource workSource) {
442        enforceChangePermission();
443        synchronized (this) {
444            if (mInIdleMode) {
445                // Need to send an immediate scan result broadcast in case the
446                // caller is waiting for a result ..
447                mWifiStateMachine.sendScanResultsAvailableBroadcast(/* scanSucceeded = */ false);
448                mScanPending = true;
449                return;
450            }
451        }
452        if (settings != null) {
453            settings = new ScanSettings(settings);
454            if (!settings.isValid()) {
455                Slog.e(TAG, "invalid scan setting");
456                return;
457            }
458        }
459        if (workSource != null) {
460            enforceWorkSourcePermission();
461            // WifiManager currently doesn't use names, so need to clear names out of the
462            // supplied WorkSource to allow future WorkSource combining.
463            workSource.clearNames();
464        }
465        mWifiStateMachine.startScan(Binder.getCallingUid(), scanRequestCounter++,
466                settings, workSource);
467    }
468
469    public boolean isBatchedScanSupported() {
470        return false;
471    }
472
473    public void pollBatchedScan() { }
474
475    public String getWpsNfcConfigurationToken(int netId) {
476        enforceConnectivityInternalPermission();
477        return mWifiStateMachine.syncGetWpsNfcConfigurationToken(netId);
478    }
479
480    /**
481     * see {@link android.net.wifi.WifiManager#requestBatchedScan()}
482     */
483    public boolean requestBatchedScan(BatchedScanSettings requested, IBinder binder,
484            WorkSource workSource) {
485        return false;
486    }
487
488    public List<BatchedScanResult> getBatchedScanResults(String callingPackage) {
489        return null;
490    }
491
492    public void stopBatchedScan(BatchedScanSettings settings) { }
493
494    boolean mInIdleMode;
495    boolean mScanPending;
496
497    void handleIdleModeChanged() {
498        boolean doScan = false;
499        synchronized (this) {
500            boolean idle = mPowerManager.isDeviceIdleMode();
501            if (mInIdleMode != idle) {
502                mInIdleMode = idle;
503                if (!idle) {
504                    if (mScanPending) {
505                        mScanPending = false;
506                        doScan = true;
507                    }
508                }
509            }
510        }
511        if (doScan) {
512            // Someone requested a scan while we were idle; do a full scan now.
513            startScan(null, null);
514        }
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    private void enforceLocationHardwarePermission() {
528        mContext.enforceCallingOrSelfPermission(Manifest.permission.LOCATION_HARDWARE,
529                "LocationHardware");
530    }
531
532    private void enforceReadCredentialPermission() {
533        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.READ_WIFI_CREDENTIAL,
534                                                "WifiService");
535    }
536
537    private void enforceWorkSourcePermission() {
538        mContext.enforceCallingPermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
539                "WifiService");
540
541    }
542
543    private void enforceMulticastChangePermission() {
544        mContext.enforceCallingOrSelfPermission(
545                android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
546                "WifiService");
547    }
548
549    private void enforceConnectivityInternalPermission() {
550        mContext.enforceCallingOrSelfPermission(
551                android.Manifest.permission.CONNECTIVITY_INTERNAL,
552                "ConnectivityService");
553    }
554
555    /**
556     * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
557     * @param enable {@code true} to enable, {@code false} to disable.
558     * @return {@code true} if the enable/disable operation was
559     *         started or is already in the queue.
560     */
561    public synchronized boolean setWifiEnabled(boolean enable) {
562        enforceChangePermission();
563        Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
564                    + ", uid=" + Binder.getCallingUid());
565        if (DBG) {
566            Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
567        }
568
569        /*
570        * Caller might not have WRITE_SECURE_SETTINGS,
571        * only CHANGE_WIFI_STATE is enforced
572        */
573
574        long ident = Binder.clearCallingIdentity();
575        try {
576            if (! mSettingsStore.handleWifiToggled(enable)) {
577                // Nothing to do if wifi cannot be toggled
578                return true;
579            }
580        } finally {
581            Binder.restoreCallingIdentity(ident);
582        }
583
584        mWifiController.sendMessage(CMD_WIFI_TOGGLED);
585        return true;
586    }
587
588    /**
589     * see {@link WifiManager#getWifiState()}
590     * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
591     *         {@link WifiManager#WIFI_STATE_DISABLING},
592     *         {@link WifiManager#WIFI_STATE_ENABLED},
593     *         {@link WifiManager#WIFI_STATE_ENABLING},
594     *         {@link WifiManager#WIFI_STATE_UNKNOWN}
595     */
596    public int getWifiEnabledState() {
597        enforceAccessPermission();
598        return mWifiStateMachine.syncGetWifiState();
599    }
600
601    /**
602     * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
603     * @param wifiConfig SSID, security and channel details as
604     *        part of WifiConfiguration
605     * @param enabled true to enable and false to disable
606     */
607    public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
608        enforceChangePermission();
609        ConnectivityManager.enforceTetherChangePermission(mContext);
610        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
611            throw new SecurityException("DISALLOW_CONFIG_TETHERING is enabled for this user.");
612        }
613        // null wifiConfig is a meaningful input for CMD_SET_AP
614        if (wifiConfig == null || isValid(wifiConfig)) {
615            mWifiController.obtainMessage(CMD_SET_AP, enabled ? 1 : 0, 0, wifiConfig).sendToTarget();
616        } else {
617            Slog.e(TAG, "Invalid WifiConfiguration");
618        }
619    }
620
621    /**
622     * see {@link WifiManager#getWifiApState()}
623     * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
624     *         {@link WifiManager#WIFI_AP_STATE_DISABLING},
625     *         {@link WifiManager#WIFI_AP_STATE_ENABLED},
626     *         {@link WifiManager#WIFI_AP_STATE_ENABLING},
627     *         {@link WifiManager#WIFI_AP_STATE_FAILED}
628     */
629    public int getWifiApEnabledState() {
630        enforceAccessPermission();
631        return mWifiStateMachine.syncGetWifiApState();
632    }
633
634    /**
635     * see {@link WifiManager#getWifiApConfiguration()}
636     * @return soft access point configuration
637     */
638    public WifiConfiguration getWifiApConfiguration() {
639        enforceAccessPermission();
640        return mWifiStateMachine.syncGetWifiApConfiguration();
641    }
642
643    /**
644     * see {@link WifiManager#buildWifiConfig()}
645     * @return a WifiConfiguration.
646     */
647    public WifiConfiguration buildWifiConfig(String uriString, String mimeType, byte[] data) {
648        if (mimeType.equals(ConfigBuilder.WifiConfigType)) {
649            try {
650                return ConfigBuilder.buildConfig(uriString, data, mContext);
651            }
652            catch (IOException | GeneralSecurityException | SAXException e) {
653                Log.e(TAG, "Failed to parse wi-fi configuration: " + e);
654            }
655        }
656        else {
657            Log.i(TAG, "Unknown wi-fi config type: " + mimeType);
658        }
659        return null;
660    }
661
662    /**
663     * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
664     * @param wifiConfig WifiConfiguration details for soft access point
665     */
666    public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
667        enforceChangePermission();
668        if (wifiConfig == null)
669            return;
670        if (isValid(wifiConfig)) {
671            mWifiStateMachine.setWifiApConfiguration(wifiConfig);
672        } else {
673            Slog.e(TAG, "Invalid WifiConfiguration");
674        }
675    }
676
677    /**
678     * @param enable {@code true} to enable, {@code false} to disable.
679     * @return {@code true} if the enable/disable operation was
680     *         started or is already in the queue.
681     */
682    public boolean isScanAlwaysAvailable() {
683        enforceAccessPermission();
684        return mSettingsStore.isScanAlwaysAvailable();
685    }
686
687    /**
688     * see {@link android.net.wifi.WifiManager#disconnect()}
689     */
690    public void disconnect() {
691        enforceChangePermission();
692        mWifiStateMachine.disconnectCommand();
693    }
694
695    /**
696     * see {@link android.net.wifi.WifiManager#reconnect()}
697     */
698    public void reconnect() {
699        enforceChangePermission();
700        mWifiStateMachine.reconnectCommand();
701    }
702
703    /**
704     * see {@link android.net.wifi.WifiManager#reassociate()}
705     */
706    public void reassociate() {
707        enforceChangePermission();
708        mWifiStateMachine.reassociateCommand();
709    }
710
711    /**
712     * see {@link android.net.wifi.WifiManager#getSupportedFeatures}
713     */
714    public int getSupportedFeatures() {
715        enforceAccessPermission();
716        if (mWifiStateMachineChannel != null) {
717            return mWifiStateMachine.syncGetSupportedFeatures(mWifiStateMachineChannel);
718        } else {
719            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
720            return 0;
721        }
722    }
723
724    /**
725     * see {@link android.net.wifi.WifiManager#getControllerActivityEnergyInfo(int)}
726     */
727    public WifiActivityEnergyInfo reportActivityInfo() {
728        enforceAccessPermission();
729        WifiLinkLayerStats stats;
730        WifiActivityEnergyInfo energyInfo = null;
731        if (mWifiStateMachineChannel != null) {
732            stats = mWifiStateMachine.syncGetLinkLayerStats(mWifiStateMachineChannel);
733            if (stats != null) {
734                final long rxIdleCurrent = mContext.getResources().getInteger(
735                        com.android.internal.R.integer.config_wifi_idle_receive_cur_ma);
736                final long rxCurrent = mContext.getResources().getInteger(
737                        com.android.internal.R.integer.config_wifi_active_rx_cur_ma);
738                final long txCurrent = mContext.getResources().getInteger(
739                        com.android.internal.R.integer.config_wifi_tx_cur_ma);
740                final double voltage = mContext.getResources().getInteger(
741                        com.android.internal.R.integer.config_wifi_operating_voltage_mv)
742                        / 1000.0;
743
744                final long rxIdleTime = stats.on_time - stats.tx_time - stats.rx_time;
745                final long energyUsed = (long)((stats.tx_time * txCurrent +
746                        stats.rx_time * rxCurrent +
747                        rxIdleTime * rxIdleCurrent) * voltage);
748                if (VDBG) {
749                    StringBuilder sb = new StringBuilder();
750                    sb.append(" rxIdleCur=" + rxIdleCurrent);
751                    sb.append(" rxCur=" + rxCurrent);
752                    sb.append(" txCur=" + txCurrent);
753                    sb.append(" voltage=" + voltage);
754                    sb.append(" on_time=" + stats.on_time);
755                    sb.append(" tx_time=" + stats.tx_time);
756                    sb.append(" rx_time=" + stats.rx_time);
757                    sb.append(" rxIdleTime=" + rxIdleTime);
758                    sb.append(" energy=" + energyUsed);
759                    Log.e(TAG, " reportActivityInfo: " + sb.toString());
760                }
761
762                // Convert the LinkLayerStats into EnergyActivity
763                energyInfo = new WifiActivityEnergyInfo(SystemClock.elapsedRealtime(),
764                        WifiActivityEnergyInfo.STACK_STATE_STATE_IDLE, stats.tx_time,
765                        stats.rx_time, rxIdleTime, energyUsed);
766            }
767            return energyInfo;
768        } else {
769            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
770            return null;
771        }
772    }
773
774    /**
775     * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
776     * @return the list of configured networks
777     */
778    public List<WifiConfiguration> getConfiguredNetworks() {
779        enforceAccessPermission();
780        if (mWifiStateMachineChannel != null) {
781            return mWifiStateMachine.syncGetConfiguredNetworks(Binder.getCallingUid(),
782                    mWifiStateMachineChannel);
783        } else {
784            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
785            return null;
786        }
787    }
788
789    /**
790     * see {@link android.net.wifi.WifiManager#getPrivilegedConfiguredNetworks()}
791     * @return the list of configured networks with real preSharedKey
792     */
793    public List<WifiConfiguration> getPrivilegedConfiguredNetworks() {
794        enforceReadCredentialPermission();
795        enforceAccessPermission();
796        if (mWifiStateMachineChannel != null) {
797            return mWifiStateMachine.syncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel);
798        } else {
799            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
800            return null;
801        }
802    }
803
804    /**
805     * Returns a WifiConfiguration matching this ScanResult
806     * @param scanResult scanResult that represents the BSSID
807     * @return {@link WifiConfiguration} that matches this BSSID or null
808     */
809    public WifiConfiguration getMatchingWifiConfig(ScanResult scanResult) {
810        enforceAccessPermission();
811        return mWifiStateMachine.syncGetMatchingWifiConfig(scanResult, mWifiStateMachineChannel);
812    }
813
814
815    /**
816     * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
817     * @return the supplicant-assigned identifier for the new or updated
818     * network if the operation succeeds, or {@code -1} if it fails
819     */
820    public int addOrUpdateNetwork(WifiConfiguration config) {
821        enforceChangePermission();
822        if (isValid(config) && isValidPasspoint(config)) {
823
824            WifiEnterpriseConfig enterpriseConfig = config.enterpriseConfig;
825
826            if (config.isPasspoint() &&
827                    (enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS ||
828                enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TTLS)) {
829                try {
830                    verifyCert(enterpriseConfig.getCaCertificate());
831                } catch (CertPathValidatorException cpve) {
832                    Slog.e(TAG, "CA Cert " +
833                            enterpriseConfig.getCaCertificate().getSubjectX500Principal() +
834                            " untrusted: " + cpve.getMessage());
835                    return -1;
836                } catch (GeneralSecurityException | IOException e) {
837                    Slog.e(TAG, "Failed to verify certificate" +
838                            enterpriseConfig.getCaCertificate().getSubjectX500Principal() +
839                            ": " + e);
840                    return -1;
841                }
842            }
843
844            //TODO: pass the Uid the WifiStateMachine as a message parameter
845            Slog.i("addOrUpdateNetwork", " uid = " + Integer.toString(Binder.getCallingUid())
846                    + " SSID " + config.SSID
847                    + " nid=" + Integer.toString(config.networkId));
848            if (config.networkId == WifiConfiguration.INVALID_NETWORK_ID) {
849                config.creatorUid = Binder.getCallingUid();
850            } else {
851                config.lastUpdateUid = Binder.getCallingUid();
852            }
853            if (mWifiStateMachineChannel != null) {
854                return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
855            } else {
856                Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
857                return -1;
858            }
859        } else {
860            Slog.e(TAG, "bad network configuration");
861            return -1;
862        }
863    }
864
865    public static void verifyCert(X509Certificate caCert)
866            throws GeneralSecurityException, IOException {
867        CertificateFactory factory = CertificateFactory.getInstance("X.509");
868        CertPathValidator validator =
869                CertPathValidator.getInstance(CertPathValidator.getDefaultType());
870        CertPath path = factory.generateCertPath(
871                Arrays.asList(caCert));
872        KeyStore ks = KeyStore.getInstance("AndroidCAStore");
873        ks.load(null, null);
874        PKIXParameters params = new PKIXParameters(ks);
875        params.setRevocationEnabled(false);
876        validator.validate(path, params);
877    }
878
879    /**
880     * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
881     * @param netId the integer that identifies the network configuration
882     * to the supplicant
883     * @return {@code true} if the operation succeeded
884     */
885    public boolean removeNetwork(int netId) {
886        enforceChangePermission();
887
888        if (!isOwner(Binder.getCallingUid())) {
889            Slog.e(TAG, "Remove is not authorized for user");
890            return false;
891        }
892
893        if (mWifiStateMachineChannel != null) {
894            return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
895        } else {
896            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
897            return false;
898        }
899    }
900
901    /**
902     * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
903     * @param netId the integer that identifies the network configuration
904     * to the supplicant
905     * @param disableOthers if true, disable all other networks.
906     * @return {@code true} if the operation succeeded
907     */
908    public boolean enableNetwork(int netId, boolean disableOthers) {
909        enforceChangePermission();
910        if (mWifiStateMachineChannel != null) {
911            return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
912                    disableOthers);
913        } else {
914            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
915            return false;
916        }
917    }
918
919    /**
920     * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
921     * @param netId the integer that identifies the network configuration
922     * to the supplicant
923     * @return {@code true} if the operation succeeded
924     */
925    public boolean disableNetwork(int netId) {
926        enforceChangePermission();
927        if (mWifiStateMachineChannel != null) {
928            return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
929        } else {
930            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
931            return false;
932        }
933    }
934
935    /**
936     * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
937     * @return the Wi-Fi information, contained in {@link WifiInfo}.
938     */
939    public WifiInfo getConnectionInfo() {
940        enforceAccessPermission();
941        /*
942         * Make sure we have the latest information, by sending
943         * a status request to the supplicant.
944         */
945        return mWifiStateMachine.syncRequestConnectionInfo();
946    }
947
948    /**
949     * Return the results of the most recent access point scan, in the form of
950     * a list of {@link ScanResult} objects.
951     * @return the list of results
952     */
953    public List<ScanResult> getScanResults(String callingPackage) {
954        enforceAccessPermission();
955        int userId = UserHandle.getCallingUserId();
956        int uid = Binder.getCallingUid();
957        boolean canReadPeerMacAddresses = checkPeersMacAddress();
958        boolean isActiveNetworkScorer =
959                NetworkScorerAppManager.isCallerActiveScorer(mContext, uid);
960        boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
961        long ident = Binder.clearCallingIdentity();
962        try {
963            if (!canReadPeerMacAddresses && !isActiveNetworkScorer
964                    && !isLocationEnabled()) {
965                return new ArrayList<ScanResult>();
966            }
967            if (!canReadPeerMacAddresses && !isActiveNetworkScorer
968                    && !checkCallerHasLocationPermission(callingPackage, uid)) {
969                return new ArrayList<ScanResult>();
970            }
971            if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
972                    != AppOpsManager.MODE_ALLOWED) {
973                return new ArrayList<ScanResult>();
974            }
975            if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
976                return new ArrayList<ScanResult>();
977            }
978            return mWifiStateMachine.syncGetScanResultsList();
979        } finally {
980            Binder.restoreCallingIdentity(ident);
981        }
982    }
983
984    private boolean isLocationEnabled() {
985        return Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
986                Settings.Secure.LOCATION_MODE_OFF) != Settings.Secure.LOCATION_MODE_OFF;
987    }
988
989    /**
990     * Returns true if the caller holds INTERACT_ACROSS_USERS_FULL.
991     */
992    private boolean checkInteractAcrossUsersFull() {
993        return mContext.checkCallingOrSelfPermission(
994                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
995                == PackageManager.PERMISSION_GRANTED;
996    }
997
998    /**
999     * Returns true if the caller holds PEERS_MAC_ADDRESS.
1000     */
1001    private boolean checkPeersMacAddress() {
1002        return mContext.checkCallingOrSelfPermission(
1003                android.Manifest.permission.PEERS_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1004    }
1005
1006    /**
1007     * Returns true if the calling user is the current one or a profile of the
1008     * current user..
1009     */
1010    private boolean isCurrentProfile(int userId) {
1011        int currentUser = ActivityManager.getCurrentUser();
1012        if (userId == currentUser) {
1013            return true;
1014        }
1015        List<UserInfo> profiles = mUserManager.getProfiles(currentUser);
1016        for (UserInfo user : profiles) {
1017            if (userId == user.id) {
1018                return true;
1019            }
1020        }
1021        return false;
1022    }
1023
1024    /**
1025     * Returns true if uid is an application running under the owner or a profile of the owner.
1026     *
1027     * Note: Should not be called if identity is cleared.
1028     */
1029    private boolean isOwner(int uid) {
1030        long ident = Binder.clearCallingIdentity();
1031        int userId = UserHandle.getUserId(uid);
1032        try {
1033            int ownerUser = UserHandle.USER_OWNER;
1034            if (userId == ownerUser) {
1035                return true;
1036            }
1037            List<UserInfo> profiles = mUserManager.getProfiles(ownerUser);
1038            for (UserInfo profile : profiles) {
1039                if (userId == profile.id) {
1040                    return true;
1041                }
1042            }
1043            return false;
1044        }
1045        finally {
1046            Binder.restoreCallingIdentity(ident);
1047        }
1048    }
1049
1050
1051    /**
1052     * Tell the supplicant to persist the current list of configured networks.
1053     * @return {@code true} if the operation succeeded
1054     *
1055     * TODO: deprecate this
1056     */
1057    public boolean saveConfiguration() {
1058        boolean result = true;
1059        enforceChangePermission();
1060        if (mWifiStateMachineChannel != null) {
1061            return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
1062        } else {
1063            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1064            return false;
1065        }
1066    }
1067
1068    /**
1069     * Set the country code
1070     * @param countryCode ISO 3166 country code.
1071     * @param persist {@code true} if the setting should be remembered.
1072     *
1073     * The persist behavior exists so that wifi can fall back to the last
1074     * persisted country code on a restart, when the locale information is
1075     * not available from telephony.
1076     */
1077    public void setCountryCode(String countryCode, boolean persist) {
1078        Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
1079                " with persist set to " + persist);
1080        enforceConnectivityInternalPermission();
1081        final long token = Binder.clearCallingIdentity();
1082        try {
1083            mWifiStateMachine.setCountryCode(countryCode, persist);
1084        } finally {
1085            Binder.restoreCallingIdentity(token);
1086        }
1087    }
1088
1089     /**
1090     * Get the country code
1091     * @return ISO 3166 country code.
1092     */
1093    public String getCountryCode() {
1094        enforceConnectivityInternalPermission();
1095        String country = mWifiStateMachine.getCountryCode();
1096        return country;
1097    }
1098    /**
1099     * Set the operational frequency band
1100     * @param band One of
1101     *     {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
1102     *     {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
1103     *     {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
1104     * @param persist {@code true} if the setting should be remembered.
1105     *
1106     */
1107    public void setFrequencyBand(int band, boolean persist) {
1108        enforceChangePermission();
1109        if (!isDualBandSupported()) return;
1110        Slog.i(TAG, "WifiService trying to set frequency band to " + band +
1111                " with persist set to " + persist);
1112        final long token = Binder.clearCallingIdentity();
1113        try {
1114            mWifiStateMachine.setFrequencyBand(band, persist);
1115        } finally {
1116            Binder.restoreCallingIdentity(token);
1117        }
1118    }
1119
1120
1121    /**
1122     * Get the operational frequency band
1123     */
1124    public int getFrequencyBand() {
1125        enforceAccessPermission();
1126        return mWifiStateMachine.getFrequencyBand();
1127    }
1128
1129    public boolean isDualBandSupported() {
1130        //TODO: Should move towards adding a driver API that checks at runtime
1131        return mContext.getResources().getBoolean(
1132                com.android.internal.R.bool.config_wifi_dual_band_support);
1133    }
1134
1135    /**
1136     * Return the DHCP-assigned addresses from the last successful DHCP request,
1137     * if any.
1138     * @return the DHCP information
1139     * @deprecated
1140     */
1141    public DhcpInfo getDhcpInfo() {
1142        enforceAccessPermission();
1143        DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
1144
1145        DhcpInfo info = new DhcpInfo();
1146
1147        if (dhcpResults.ipAddress != null &&
1148                dhcpResults.ipAddress.getAddress() instanceof Inet4Address) {
1149            info.ipAddress = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.ipAddress.getAddress());
1150        }
1151
1152        if (dhcpResults.gateway != null) {
1153            info.gateway = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.gateway);
1154        }
1155
1156        int dnsFound = 0;
1157        for (InetAddress dns : dhcpResults.dnsServers) {
1158            if (dns instanceof Inet4Address) {
1159                if (dnsFound == 0) {
1160                    info.dns1 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1161                } else {
1162                    info.dns2 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1163                }
1164                if (++dnsFound > 1) break;
1165            }
1166        }
1167        InetAddress serverAddress = dhcpResults.serverAddress;
1168        if (serverAddress instanceof Inet4Address) {
1169            info.serverAddress = NetworkUtils.inetAddressToInt((Inet4Address)serverAddress);
1170        }
1171        info.leaseDuration = dhcpResults.leaseDuration;
1172
1173        return info;
1174    }
1175
1176    /**
1177     * see {@link android.net.wifi.WifiManager#startWifi}
1178     *
1179     */
1180    public void startWifi() {
1181        enforceConnectivityInternalPermission();
1182        /* TODO: may be add permissions for access only to connectivity service
1183         * TODO: if a start issued, keep wifi alive until a stop issued irrespective
1184         * of WifiLock & device idle status unless wifi enabled status is toggled
1185         */
1186
1187        mWifiStateMachine.setDriverStart(true);
1188        mWifiStateMachine.reconnectCommand();
1189    }
1190
1191    /**
1192     * see {@link android.net.wifi.WifiManager#stopWifi}
1193     *
1194     */
1195    public void stopWifi() {
1196        enforceConnectivityInternalPermission();
1197        /*
1198         * TODO: if a stop is issued, wifi is brought up only by startWifi
1199         * unless wifi enabled status is toggled
1200         */
1201        mWifiStateMachine.setDriverStart(false);
1202    }
1203
1204    /**
1205     * see {@link android.net.wifi.WifiManager#addToBlacklist}
1206     *
1207     */
1208    public void addToBlacklist(String bssid) {
1209        enforceChangePermission();
1210
1211        mWifiStateMachine.addToBlacklist(bssid);
1212    }
1213
1214    /**
1215     * see {@link android.net.wifi.WifiManager#clearBlacklist}
1216     *
1217     */
1218    public void clearBlacklist() {
1219        enforceChangePermission();
1220
1221        mWifiStateMachine.clearBlacklist();
1222    }
1223
1224    /**
1225     * enable TDLS for the local NIC to remote NIC
1226     * The APPs don't know the remote MAC address to identify NIC though,
1227     * so we need to do additional work to find it from remote IP address
1228     */
1229
1230    class TdlsTaskParams {
1231        public String remoteIpAddress;
1232        public boolean enable;
1233    }
1234
1235    class TdlsTask extends AsyncTask<TdlsTaskParams, Integer, Integer> {
1236        @Override
1237        protected Integer doInBackground(TdlsTaskParams... params) {
1238
1239            // Retrieve parameters for the call
1240            TdlsTaskParams param = params[0];
1241            String remoteIpAddress = param.remoteIpAddress.trim();
1242            boolean enable = param.enable;
1243
1244            // Get MAC address of Remote IP
1245            String macAddress = null;
1246
1247            BufferedReader reader = null;
1248
1249            try {
1250                reader = new BufferedReader(new FileReader("/proc/net/arp"));
1251
1252                // Skip over the line bearing colum titles
1253                String line = reader.readLine();
1254
1255                while ((line = reader.readLine()) != null) {
1256                    String[] tokens = line.split("[ ]+");
1257                    if (tokens.length < 6) {
1258                        continue;
1259                    }
1260
1261                    // ARP column format is
1262                    // Address HWType HWAddress Flags Mask IFace
1263                    String ip = tokens[0];
1264                    String mac = tokens[3];
1265
1266                    if (remoteIpAddress.equals(ip)) {
1267                        macAddress = mac;
1268                        break;
1269                    }
1270                }
1271
1272                if (macAddress == null) {
1273                    Slog.w(TAG, "Did not find remoteAddress {" + remoteIpAddress + "} in " +
1274                            "/proc/net/arp");
1275                } else {
1276                    enableTdlsWithMacAddress(macAddress, enable);
1277                }
1278
1279            } catch (FileNotFoundException e) {
1280                Slog.e(TAG, "Could not open /proc/net/arp to lookup mac address");
1281            } catch (IOException e) {
1282                Slog.e(TAG, "Could not read /proc/net/arp to lookup mac address");
1283            } finally {
1284                try {
1285                    if (reader != null) {
1286                        reader.close();
1287                    }
1288                }
1289                catch (IOException e) {
1290                    // Do nothing
1291                }
1292            }
1293
1294            return 0;
1295        }
1296    }
1297
1298    public void enableTdls(String remoteAddress, boolean enable) {
1299        if (remoteAddress == null) {
1300          throw new IllegalArgumentException("remoteAddress cannot be null");
1301        }
1302
1303        TdlsTaskParams params = new TdlsTaskParams();
1304        params.remoteIpAddress = remoteAddress;
1305        params.enable = enable;
1306        new TdlsTask().execute(params);
1307    }
1308
1309
1310    public void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable) {
1311        if (remoteMacAddress == null) {
1312          throw new IllegalArgumentException("remoteMacAddress cannot be null");
1313        }
1314
1315        mWifiStateMachine.enableTdls(remoteMacAddress, enable);
1316    }
1317
1318    /**
1319     * Get a reference to handler. This is used by a client to establish
1320     * an AsyncChannel communication with WifiService
1321     */
1322    public Messenger getWifiServiceMessenger() {
1323        enforceAccessPermission();
1324        enforceChangePermission();
1325        return new Messenger(mClientHandler);
1326    }
1327
1328    /**
1329     * Disable an ephemeral network, i.e. network that is created thru a WiFi Scorer
1330     */
1331    public void disableEphemeralNetwork(String SSID) {
1332        enforceAccessPermission();
1333        enforceChangePermission();
1334        mWifiStateMachine.disableEphemeralNetwork(SSID);
1335    }
1336
1337    /**
1338     * Get the IP and proxy configuration file
1339     */
1340    public String getConfigFile() {
1341        enforceAccessPermission();
1342        return mWifiStateMachine.getConfigFile();
1343    }
1344
1345    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1346        @Override
1347        public void onReceive(Context context, Intent intent) {
1348            String action = intent.getAction();
1349            if (action.equals(Intent.ACTION_SCREEN_ON)) {
1350                mWifiController.sendMessage(CMD_SCREEN_ON);
1351            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1352                mWifiController.sendMessage(CMD_USER_PRESENT);
1353            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1354                mWifiController.sendMessage(CMD_SCREEN_OFF);
1355            } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1356                int pluggedType = intent.getIntExtra("plugged", 0);
1357                mWifiController.sendMessage(CMD_BATTERY_CHANGED, pluggedType, 0, null);
1358            } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1359                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1360                        BluetoothAdapter.STATE_DISCONNECTED);
1361                mWifiStateMachine.sendBluetoothAdapterStateChange(state);
1362            } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1363                boolean emergencyMode = intent.getBooleanExtra("phoneinECMState", false);
1364                mWifiController.sendMessage(CMD_EMERGENCY_MODE_CHANGED, emergencyMode ? 1 : 0, 0);
1365            } else if (action.equals(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)) {
1366                handleIdleModeChanged();
1367            }
1368        }
1369    };
1370
1371    /**
1372     * Observes settings changes to scan always mode.
1373     */
1374    private void registerForScanModeChange() {
1375        ContentObserver contentObserver = new ContentObserver(null) {
1376            @Override
1377            public void onChange(boolean selfChange) {
1378                mSettingsStore.handleWifiScanAlwaysAvailableToggled();
1379                mWifiController.sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);
1380            }
1381        };
1382
1383        mContext.getContentResolver().registerContentObserver(
1384                Settings.Global.getUriFor(Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE),
1385                false, contentObserver);
1386    }
1387
1388    private void registerForBroadcasts() {
1389        IntentFilter intentFilter = new IntentFilter();
1390        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1391        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
1392        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1393        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1394        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
1395        intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
1396        intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
1397        intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
1398        mContext.registerReceiver(mReceiver, intentFilter);
1399    }
1400
1401    private void registerForPackageOrUserRemoval() {
1402        IntentFilter intentFilter = new IntentFilter();
1403        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1404        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
1405        mContext.registerReceiverAsUser(new BroadcastReceiver() {
1406            @Override
1407            public void onReceive(Context context, Intent intent) {
1408                switch (intent.getAction()) {
1409                    case Intent.ACTION_PACKAGE_REMOVED: {
1410                        if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1411                            return;
1412                        }
1413                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
1414                        Uri uri = intent.getData();
1415                        if (uid == -1 || uri == null) {
1416                            return;
1417                        }
1418                        String pkgName = uri.getSchemeSpecificPart();
1419                        mWifiStateMachine.removeAppConfigs(pkgName, uid);
1420                        break;
1421                    }
1422                    case Intent.ACTION_USER_REMOVED: {
1423                        int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
1424                        mWifiStateMachine.removeUserConfigs(userHandle);
1425                        break;
1426                    }
1427                }
1428            }
1429        }, UserHandle.ALL, intentFilter, null, null);
1430    }
1431
1432    @Override
1433    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1434        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1435                != PackageManager.PERMISSION_GRANTED) {
1436            pw.println("Permission Denial: can't dump WifiService from from pid="
1437                    + Binder.getCallingPid()
1438                    + ", uid=" + Binder.getCallingUid());
1439            return;
1440        }
1441        pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
1442        pw.println("Stay-awake conditions: " +
1443                Settings.Global.getInt(mContext.getContentResolver(),
1444                                       Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
1445        pw.println("mMulticastEnabled " + mMulticastEnabled);
1446        pw.println("mMulticastDisabled " + mMulticastDisabled);
1447        pw.println("mInIdleMode " + mInIdleMode);
1448        pw.println("mScanPending " + mScanPending);
1449        mWifiController.dump(fd, pw, args);
1450        mSettingsStore.dump(fd, pw, args);
1451        mNotificationController.dump(fd, pw, args);
1452        mTrafficPoller.dump(fd, pw, args);
1453
1454        pw.println("Latest scan results:");
1455        List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
1456        long nowMs = System.currentTimeMillis();
1457        if (scanResults != null && scanResults.size() != 0) {
1458            pw.println("    BSSID              Frequency  RSSI    Age      SSID " +
1459                    "                                Flags");
1460            for (ScanResult r : scanResults) {
1461                long ageSec = 0;
1462                long ageMilli = 0;
1463                if (nowMs > r.seen && r.seen > 0) {
1464                    ageSec = (nowMs - r.seen) / 1000;
1465                    ageMilli = (nowMs - r.seen) % 1000;
1466                }
1467                String candidate = " ";
1468                if (r.isAutoJoinCandidate > 0) candidate = "+";
1469                pw.printf("  %17s  %9d  %5d  %3d.%03d%s   %-32s  %s\n",
1470                                         r.BSSID,
1471                                         r.frequency,
1472                                         r.level,
1473                                         ageSec, ageMilli,
1474                                         candidate,
1475                                         r.SSID == null ? "" : r.SSID,
1476                                         r.capabilities);
1477            }
1478        }
1479        pw.println();
1480        pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1481                mFullHighPerfLocksAcquired + " full high perf, " +
1482                mScanLocksAcquired + " scan");
1483        pw.println("Locks released: " + mFullLocksReleased + " full, " +
1484                mFullHighPerfLocksReleased + " full high perf, " +
1485                mScanLocksReleased + " scan");
1486        pw.println();
1487        pw.println("Locks held:");
1488        mLocks.dump(pw);
1489
1490        pw.println("Multicast Locks held:");
1491        for (Multicaster l : mMulticasters) {
1492            pw.print("    ");
1493            pw.println(l);
1494        }
1495
1496        mWifiWatchdogStateMachine.dump(fd, pw, args);
1497        pw.println();
1498        mWifiStateMachine.dump(fd, pw, args);
1499        pw.println();
1500    }
1501
1502    private class WifiLock extends DeathRecipient {
1503        WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1504            super(lockMode, tag, binder, ws);
1505        }
1506
1507        public void binderDied() {
1508            synchronized (mLocks) {
1509                releaseWifiLockLocked(mBinder);
1510            }
1511        }
1512
1513        public String toString() {
1514            return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
1515        }
1516    }
1517
1518    class LockList {
1519        private List<WifiLock> mList;
1520
1521        private LockList() {
1522            mList = new ArrayList<WifiLock>();
1523        }
1524
1525        synchronized boolean hasLocks() {
1526            return !mList.isEmpty();
1527        }
1528
1529        synchronized int getStrongestLockMode() {
1530            if (mList.isEmpty()) {
1531                return WifiManager.WIFI_MODE_FULL;
1532            }
1533
1534            if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1535                return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
1536            }
1537
1538            if (mFullLocksAcquired > mFullLocksReleased) {
1539                return WifiManager.WIFI_MODE_FULL;
1540            }
1541
1542            return WifiManager.WIFI_MODE_SCAN_ONLY;
1543        }
1544
1545        synchronized void updateWorkSource(WorkSource ws) {
1546            for (int i = 0; i < mLocks.mList.size(); i++) {
1547                ws.add(mLocks.mList.get(i).mWorkSource);
1548            }
1549        }
1550
1551        private void addLock(WifiLock lock) {
1552            if (findLockByBinder(lock.mBinder) < 0) {
1553                mList.add(lock);
1554            }
1555        }
1556
1557        private WifiLock removeLock(IBinder binder) {
1558            int index = findLockByBinder(binder);
1559            if (index >= 0) {
1560                WifiLock ret = mList.remove(index);
1561                ret.unlinkDeathRecipient();
1562                return ret;
1563            } else {
1564                return null;
1565            }
1566        }
1567
1568        private int findLockByBinder(IBinder binder) {
1569            int size = mList.size();
1570            for (int i = size - 1; i >= 0; i--) {
1571                if (mList.get(i).mBinder == binder)
1572                    return i;
1573            }
1574            return -1;
1575        }
1576
1577        private void dump(PrintWriter pw) {
1578            for (WifiLock l : mList) {
1579                pw.print("    ");
1580                pw.println(l);
1581            }
1582        }
1583    }
1584
1585    void enforceWakeSourcePermission(int uid, int pid) {
1586        if (uid == android.os.Process.myUid()) {
1587            return;
1588        }
1589        mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1590                pid, uid, null);
1591    }
1592
1593    public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
1594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1595        if (lockMode != WifiManager.WIFI_MODE_FULL &&
1596                lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1597                lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1598            Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1599            if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
1600            return false;
1601        }
1602        if (ws != null && ws.size() == 0) {
1603            ws = null;
1604        }
1605        if (ws != null) {
1606            enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1607        }
1608        if (ws == null) {
1609            ws = new WorkSource(Binder.getCallingUid());
1610        }
1611        WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
1612        synchronized (mLocks) {
1613            return acquireWifiLockLocked(wifiLock);
1614        }
1615    }
1616
1617    private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1618        switch(wifiLock.mMode) {
1619            case WifiManager.WIFI_MODE_FULL:
1620            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1621            case WifiManager.WIFI_MODE_SCAN_ONLY:
1622                mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1623                break;
1624        }
1625    }
1626
1627    private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1628        switch(wifiLock.mMode) {
1629            case WifiManager.WIFI_MODE_FULL:
1630            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1631            case WifiManager.WIFI_MODE_SCAN_ONLY:
1632                mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1633                break;
1634        }
1635    }
1636
1637    private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1638        if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1639
1640        mLocks.addLock(wifiLock);
1641
1642        long ident = Binder.clearCallingIdentity();
1643        try {
1644            noteAcquireWifiLock(wifiLock);
1645            switch(wifiLock.mMode) {
1646            case WifiManager.WIFI_MODE_FULL:
1647                ++mFullLocksAcquired;
1648                break;
1649            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1650                ++mFullHighPerfLocksAcquired;
1651                break;
1652
1653            case WifiManager.WIFI_MODE_SCAN_ONLY:
1654                ++mScanLocksAcquired;
1655                break;
1656            }
1657            mWifiController.sendMessage(CMD_LOCKS_CHANGED);
1658            return true;
1659        } catch (RemoteException e) {
1660            return false;
1661        } finally {
1662            Binder.restoreCallingIdentity(ident);
1663        }
1664    }
1665
1666    public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1667        int uid = Binder.getCallingUid();
1668        int pid = Binder.getCallingPid();
1669        if (ws != null && ws.size() == 0) {
1670            ws = null;
1671        }
1672        if (ws != null) {
1673            enforceWakeSourcePermission(uid, pid);
1674        }
1675        long ident = Binder.clearCallingIdentity();
1676        try {
1677            synchronized (mLocks) {
1678                int index = mLocks.findLockByBinder(lock);
1679                if (index < 0) {
1680                    throw new IllegalArgumentException("Wifi lock not active");
1681                }
1682                WifiLock wl = mLocks.mList.get(index);
1683                noteReleaseWifiLock(wl);
1684                wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1685                noteAcquireWifiLock(wl);
1686            }
1687        } catch (RemoteException e) {
1688        } finally {
1689            Binder.restoreCallingIdentity(ident);
1690        }
1691    }
1692
1693    public boolean releaseWifiLock(IBinder lock) {
1694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1695        synchronized (mLocks) {
1696            return releaseWifiLockLocked(lock);
1697        }
1698    }
1699
1700    private boolean releaseWifiLockLocked(IBinder lock) {
1701        boolean hadLock;
1702
1703        WifiLock wifiLock = mLocks.removeLock(lock);
1704
1705        if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1706
1707        hadLock = (wifiLock != null);
1708
1709        long ident = Binder.clearCallingIdentity();
1710        try {
1711            if (hadLock) {
1712                noteReleaseWifiLock(wifiLock);
1713                switch(wifiLock.mMode) {
1714                    case WifiManager.WIFI_MODE_FULL:
1715                        ++mFullLocksReleased;
1716                        break;
1717                    case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1718                        ++mFullHighPerfLocksReleased;
1719                        break;
1720                    case WifiManager.WIFI_MODE_SCAN_ONLY:
1721                        ++mScanLocksReleased;
1722                        break;
1723                }
1724                mWifiController.sendMessage(CMD_LOCKS_CHANGED);
1725            }
1726        } catch (RemoteException e) {
1727        } finally {
1728            Binder.restoreCallingIdentity(ident);
1729        }
1730
1731        return hadLock;
1732    }
1733
1734    private abstract class DeathRecipient
1735            implements IBinder.DeathRecipient {
1736        String mTag;
1737        int mMode;
1738        IBinder mBinder;
1739        WorkSource mWorkSource;
1740
1741        DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
1742            super();
1743            mTag = tag;
1744            mMode = mode;
1745            mBinder = binder;
1746            mWorkSource = ws;
1747            try {
1748                mBinder.linkToDeath(this, 0);
1749            } catch (RemoteException e) {
1750                binderDied();
1751            }
1752        }
1753
1754        void unlinkDeathRecipient() {
1755            mBinder.unlinkToDeath(this, 0);
1756        }
1757    }
1758
1759    private class Multicaster extends DeathRecipient {
1760        Multicaster(String tag, IBinder binder) {
1761            super(Binder.getCallingUid(), tag, binder, null);
1762        }
1763
1764        public void binderDied() {
1765            Slog.e(TAG, "Multicaster binderDied");
1766            synchronized (mMulticasters) {
1767                int i = mMulticasters.indexOf(this);
1768                if (i != -1) {
1769                    removeMulticasterLocked(i, mMode);
1770                }
1771            }
1772        }
1773
1774        public String toString() {
1775            return "Multicaster{" + mTag + " binder=" + mBinder + "}";
1776        }
1777
1778        public int getUid() {
1779            return mMode;
1780        }
1781    }
1782
1783    public void initializeMulticastFiltering() {
1784        enforceMulticastChangePermission();
1785
1786        synchronized (mMulticasters) {
1787            // if anybody had requested filters be off, leave off
1788            if (mMulticasters.size() != 0) {
1789                return;
1790            } else {
1791                mWifiStateMachine.startFilteringMulticastV4Packets();
1792            }
1793        }
1794    }
1795
1796    public void acquireMulticastLock(IBinder binder, String tag) {
1797        enforceMulticastChangePermission();
1798
1799        synchronized (mMulticasters) {
1800            mMulticastEnabled++;
1801            mMulticasters.add(new Multicaster(tag, binder));
1802            // Note that we could call stopFilteringMulticastV4Packets only when
1803            // our new size == 1 (first call), but this function won't
1804            // be called often and by making the stopPacket call each
1805            // time we're less fragile and self-healing.
1806            mWifiStateMachine.stopFilteringMulticastV4Packets();
1807        }
1808
1809        int uid = Binder.getCallingUid();
1810        final long ident = Binder.clearCallingIdentity();
1811        try {
1812            mBatteryStats.noteWifiMulticastEnabled(uid);
1813        } catch (RemoteException e) {
1814        } finally {
1815            Binder.restoreCallingIdentity(ident);
1816        }
1817    }
1818
1819    public void releaseMulticastLock() {
1820        enforceMulticastChangePermission();
1821
1822        int uid = Binder.getCallingUid();
1823        synchronized (mMulticasters) {
1824            mMulticastDisabled++;
1825            int size = mMulticasters.size();
1826            for (int i = size - 1; i >= 0; i--) {
1827                Multicaster m = mMulticasters.get(i);
1828                if ((m != null) && (m.getUid() == uid)) {
1829                    removeMulticasterLocked(i, uid);
1830                }
1831            }
1832        }
1833    }
1834
1835    private void removeMulticasterLocked(int i, int uid)
1836    {
1837        Multicaster removed = mMulticasters.remove(i);
1838
1839        if (removed != null) {
1840            removed.unlinkDeathRecipient();
1841        }
1842        if (mMulticasters.size() == 0) {
1843            mWifiStateMachine.startFilteringMulticastV4Packets();
1844        }
1845
1846        final long ident = Binder.clearCallingIdentity();
1847        try {
1848            mBatteryStats.noteWifiMulticastDisabled(uid);
1849        } catch (RemoteException e) {
1850        } finally {
1851            Binder.restoreCallingIdentity(ident);
1852        }
1853    }
1854
1855    public boolean isMulticastEnabled() {
1856        enforceAccessPermission();
1857
1858        synchronized (mMulticasters) {
1859            return (mMulticasters.size() > 0);
1860        }
1861    }
1862
1863    public WifiMonitor getWifiMonitor() {
1864        return mWifiStateMachine.getWifiMonitor();
1865    }
1866
1867    public void enableVerboseLogging(int verbose) {
1868        enforceAccessPermission();
1869        mWifiStateMachine.enableVerboseLogging(verbose);
1870    }
1871
1872    public int getVerboseLoggingLevel() {
1873        enforceAccessPermission();
1874        return mWifiStateMachine.getVerboseLoggingLevel();
1875    }
1876
1877    public void enableAggressiveHandover(int enabled) {
1878        enforceAccessPermission();
1879        mWifiStateMachine.enableAggressiveHandover(enabled);
1880    }
1881
1882    public int getAggressiveHandover() {
1883        enforceAccessPermission();
1884        return mWifiStateMachine.getAggressiveHandover();
1885    }
1886
1887    public void setAllowScansWithTraffic(int enabled) {
1888        enforceAccessPermission();
1889        mWifiStateMachine.setAllowScansWithTraffic(enabled);
1890    }
1891
1892    public int getAllowScansWithTraffic() {
1893        enforceAccessPermission();
1894        return mWifiStateMachine.getAllowScansWithTraffic();
1895    }
1896
1897    public boolean enableAutoJoinWhenAssociated(boolean enabled) {
1898        enforceChangePermission();
1899        return mWifiStateMachine.enableAutoJoinWhenAssociated(enabled);
1900    }
1901
1902    public boolean getEnableAutoJoinWhenAssociated() {
1903        enforceAccessPermission();
1904        return mWifiStateMachine.getEnableAutoJoinWhenAssociated();
1905    }
1906    public void setHalBasedAutojoinOffload(int enabled) {
1907        enforceChangePermission();
1908        mWifiStateMachine.setHalBasedAutojoinOffload(enabled);
1909    }
1910
1911    public int getHalBasedAutojoinOffload() {
1912        enforceAccessPermission();
1913        return mWifiStateMachine.getHalBasedAutojoinOffload();
1914    }
1915
1916    /* Return the Wifi Connection statistics object */
1917    public WifiConnectionStatistics getConnectionStatistics() {
1918        enforceAccessPermission();
1919        enforceReadCredentialPermission();
1920        if (mWifiStateMachineChannel != null) {
1921            return mWifiStateMachine.syncGetConnectionStatistics(mWifiStateMachineChannel);
1922        } else {
1923            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1924            return null;
1925        }
1926    }
1927
1928    public void factoryReset() {
1929        enforceConnectivityInternalPermission();
1930
1931        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
1932            return;
1933        }
1934
1935        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
1936            // Turn mobile hotspot off
1937            setWifiApEnabled(null, false);
1938        }
1939
1940        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI)) {
1941            // Enable wifi
1942            setWifiEnabled(true);
1943            // Delete all Wifi SSIDs
1944            List<WifiConfiguration> networks = getConfiguredNetworks();
1945            if (networks != null) {
1946                for (WifiConfiguration config : networks) {
1947                    removeNetwork(config.networkId);
1948                }
1949                saveConfiguration();
1950            }
1951        }
1952    }
1953
1954    /* private methods */
1955    static boolean logAndReturnFalse(String s) {
1956        Log.d(TAG, s);
1957        return false;
1958    }
1959
1960    public static boolean isValid(WifiConfiguration config) {
1961        String validity = checkValidity(config);
1962        return validity == null || logAndReturnFalse(validity);
1963    }
1964
1965    public static boolean isValidPasspoint(WifiConfiguration config) {
1966        String validity = checkPasspointValidity(config);
1967        return validity == null || logAndReturnFalse(validity);
1968    }
1969
1970    public static String checkValidity(WifiConfiguration config) {
1971        if (config.allowedKeyManagement == null)
1972            return "allowed kmgmt";
1973
1974        if (config.allowedKeyManagement.cardinality() > 1) {
1975            if (config.allowedKeyManagement.cardinality() != 2) {
1976                return "cardinality != 2";
1977            }
1978            if (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) {
1979                return "not WPA_EAP";
1980            }
1981            if ((!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X))
1982                    && (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))) {
1983                return "not PSK or 8021X";
1984            }
1985        }
1986        return null;
1987    }
1988
1989    public static String checkPasspointValidity(WifiConfiguration config) {
1990        if (!TextUtils.isEmpty(config.FQDN)) {
1991            /* this is passpoint configuration; it must not have an SSID */
1992            if (!TextUtils.isEmpty(config.SSID)) {
1993                return "SSID not expected for Passpoint: '" + config.SSID +
1994                        "' FQDN " + toHexString(config.FQDN);
1995            }
1996            /* this is passpoint configuration; it must have a providerFriendlyName */
1997            if (TextUtils.isEmpty(config.providerFriendlyName)) {
1998                return "no provider friendly name";
1999            }
2000            WifiEnterpriseConfig enterpriseConfig = config.enterpriseConfig;
2001            /* this is passpoint configuration; it must have enterprise config */
2002            if (enterpriseConfig == null
2003                    || enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.NONE ) {
2004                return "no enterprise config";
2005            }
2006            if ((enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS ||
2007                    enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TTLS ||
2008                    enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.PEAP) &&
2009                    enterpriseConfig.getCaCertificate() == null) {
2010                return "no CA certificate";
2011            }
2012        }
2013        return null;
2014    }
2015
2016    public Network getCurrentNetwork() {
2017        enforceAccessPermission();
2018        return mWifiStateMachine.getCurrentNetwork();
2019    }
2020
2021    public static String toHexString(String s) {
2022        if (s == null) {
2023            return "null";
2024        }
2025        StringBuilder sb = new StringBuilder();
2026        sb.append('\'').append(s).append('\'');
2027        for (int n = 0; n < s.length(); n++) {
2028            sb.append(String.format(" %02x", s.charAt(n) & 0xffff));
2029        }
2030        return sb.toString();
2031    }
2032
2033    /**
2034     * Checks that calling process has android.Manifest.permission.ACCESS_COARSE_LOCATION or
2035     * android.Manifest.permission.ACCESS_FINE_LOCATION and a corresponding app op is allowed
2036     */
2037    private boolean checkCallerHasLocationPermission(String callingPackage, int uid) {
2038        if (ActivityManager.checkUidPermission(Manifest.permission.ACCESS_FINE_LOCATION, uid)
2039                == PackageManager.PERMISSION_GRANTED
2040                && isAppOppAllowed(AppOpsManager.OP_FINE_LOCATION, callingPackage, uid)) {
2041            return true;
2042        }
2043
2044        if (ActivityManager.checkUidPermission(Manifest.permission.ACCESS_COARSE_LOCATION, uid)
2045                == PackageManager.PERMISSION_GRANTED
2046                && isAppOppAllowed(AppOpsManager.OP_COARSE_LOCATION, callingPackage, uid)) {
2047            return true;
2048        }
2049        // Enforce location permission for apps targeting MNC and later versions
2050        boolean enforceLocationPermission = true;
2051        try {
2052            enforceLocationPermission = mContext.getPackageManager().getApplicationInfo(
2053                    callingPackage, 0).targetSdkVersion >= Build.VERSION_CODES.MNC;
2054        } catch (PackageManager.NameNotFoundException e) {
2055            // In case of exception, enforce permission anyway
2056        }
2057        if (enforceLocationPermission) {
2058            throw new SecurityException("Need ACCESS_COARSE_LOCATION or "
2059                    + "ACCESS_FINE_LOCATION permission to get scan results");
2060        } else {
2061            Log.e(TAG, "Permission denial: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION "
2062                    + "permission to get scan results");
2063        }
2064        return false;
2065    }
2066
2067    private boolean isAppOppAllowed(int op, String callingPackage, int uid) {
2068        return mAppOps.noteOp(op, uid, callingPackage) == AppOpsManager.MODE_ALLOWED;
2069    }
2070
2071}
2072