WifiServiceImpl.java revision 1545f9403866abab36163eea9df7d18d3a388e98
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 static android.net.wifi.WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE;
20import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_FAILURE_REASON;
21import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE;
22import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_GENERIC;
23import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_NO_CHANNEL;
24import static android.net.wifi.WifiManager.SAP_START_FAILURE_NO_CHANNEL;
25import 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_FAILED;
28
29import static com.android.server.connectivity.tethering.IControlsTethering.STATE_LOCAL_ONLY;
30import static com.android.server.connectivity.tethering.IControlsTethering.STATE_TETHERED;
31import static com.android.server.wifi.LocalOnlyHotspotRequestInfo.HOTSPOT_NO_ERROR;
32import static com.android.server.wifi.WifiController.CMD_AIRPLANE_TOGGLED;
33import static com.android.server.wifi.WifiController.CMD_BATTERY_CHANGED;
34import static com.android.server.wifi.WifiController.CMD_EMERGENCY_CALL_STATE_CHANGED;
35import static com.android.server.wifi.WifiController.CMD_EMERGENCY_MODE_CHANGED;
36import static com.android.server.wifi.WifiController.CMD_LOCKS_CHANGED;
37import static com.android.server.wifi.WifiController.CMD_SCAN_ALWAYS_MODE_CHANGED;
38import static com.android.server.wifi.WifiController.CMD_SCREEN_OFF;
39import static com.android.server.wifi.WifiController.CMD_SCREEN_ON;
40import static com.android.server.wifi.WifiController.CMD_SET_AP;
41import static com.android.server.wifi.WifiController.CMD_USER_PRESENT;
42import static com.android.server.wifi.WifiController.CMD_WIFI_TOGGLED;
43
44import android.Manifest;
45import android.app.ActivityManager;
46import android.app.ActivityManager.RunningAppProcessInfo;
47import android.app.AppOpsManager;
48import android.bluetooth.BluetoothAdapter;
49import android.content.BroadcastReceiver;
50import android.content.Context;
51import android.content.Intent;
52import android.content.IntentFilter;
53import android.content.pm.ApplicationInfo;
54import android.content.pm.PackageManager;
55import android.content.pm.ParceledListSlice;
56import android.database.ContentObserver;
57import android.net.DhcpInfo;
58import android.net.DhcpResults;
59import android.net.IpConfiguration;
60import android.net.Network;
61import android.net.NetworkUtils;
62import android.net.StaticIpConfiguration;
63import android.net.Uri;
64import android.net.ip.IpManager;
65import android.net.wifi.IWifiManager;
66import android.net.wifi.ScanResult;
67import android.net.wifi.ScanSettings;
68import android.net.wifi.WifiActivityEnergyInfo;
69import android.net.wifi.WifiConfiguration;
70import android.net.wifi.WifiConnectionStatistics;
71import android.net.wifi.WifiInfo;
72import android.net.wifi.WifiLinkLayerStats;
73import android.net.wifi.WifiManager;
74import android.net.wifi.WifiManager.LocalOnlyHotspotCallback;
75import android.net.wifi.WifiScanner;
76import android.net.wifi.hotspot2.PasspointConfiguration;
77import android.os.AsyncTask;
78import android.os.BatteryStats;
79import android.os.Binder;
80import android.os.Build;
81import android.os.Bundle;
82import android.os.HandlerThread;
83import android.os.IBinder;
84import android.os.Looper;
85import android.os.Message;
86import android.os.Messenger;
87import android.os.PowerManager;
88import android.os.Process;
89import android.os.RemoteException;
90import android.os.ResultReceiver;
91import android.os.ShellCallback;
92import android.os.UserHandle;
93import android.os.UserManager;
94import android.os.WorkSource;
95import android.provider.Settings;
96import android.util.ArrayMap;
97import android.util.ArraySet;
98import android.util.Log;
99import android.util.Slog;
100
101import com.android.internal.annotations.GuardedBy;
102import com.android.internal.annotations.VisibleForTesting;
103import com.android.internal.telephony.IccCardConstants;
104import com.android.internal.telephony.PhoneConstants;
105import com.android.internal.telephony.TelephonyIntents;
106import com.android.internal.util.AsyncChannel;
107import com.android.server.wifi.hotspot2.PasspointProvider;
108import com.android.server.wifi.util.WifiHandler;
109import com.android.server.wifi.util.WifiPermissionsUtil;
110
111import java.io.BufferedReader;
112import java.io.FileDescriptor;
113import java.io.FileNotFoundException;
114import java.io.FileReader;
115import java.io.IOException;
116import java.io.PrintWriter;
117import java.net.Inet4Address;
118import java.net.InetAddress;
119import java.security.GeneralSecurityException;
120import java.security.KeyStore;
121import java.security.cert.CertPath;
122import java.security.cert.CertPathValidator;
123import java.security.cert.CertificateFactory;
124import java.security.cert.PKIXParameters;
125import java.security.cert.X509Certificate;
126import java.util.ArrayList;
127import java.util.Arrays;
128import java.util.HashMap;
129import java.util.List;
130import java.util.concurrent.ConcurrentHashMap;
131
132/**
133 * WifiService handles remote WiFi operation requests by implementing
134 * the IWifiManager interface.
135 *
136 * @hide
137 */
138public class WifiServiceImpl extends IWifiManager.Stub {
139    private static final String TAG = "WifiService";
140    private static final boolean DBG = true;
141    private static final boolean VDBG = false;
142
143    // Package names for Settings, QuickSettings and QuickQuickSettings
144    private static final String SYSUI_PACKAGE_NAME = "com.android.systemui";
145    private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
146
147    // Default scan background throttling interval if not overriden in settings
148    private static final long DEFAULT_SCAN_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
149
150    // Apps with importance higher than this value is considered as background app.
151    private static final int BACKGROUND_IMPORTANCE_CUTOFF =
152            RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
153
154    final WifiStateMachine mWifiStateMachine;
155
156    private final Context mContext;
157    private final FrameworkFacade mFacade;
158    private final Clock mClock;
159    private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
160
161    private final PowerManager mPowerManager;
162    private final AppOpsManager mAppOps;
163    private final UserManager mUserManager;
164    private final ActivityManager mActivityManager;
165    private final WifiCountryCode mCountryCode;
166    private long mBackgroundThrottleInterval;
167    // Debug counter tracking scan requests sent by WifiManager
168    private int scanRequestCounter = 0;
169
170    /* Tracks the open wi-fi network notification */
171    private WifiNotificationController mNotificationController;
172    /* Polls traffic stats and notifies clients */
173    private WifiTrafficPoller mTrafficPoller;
174    /* Tracks the persisted states for wi-fi & airplane mode */
175    final WifiSettingsStore mSettingsStore;
176    /* Logs connection events and some general router and scan stats */
177    private final WifiMetrics mWifiMetrics;
178    /* Manages affiliated certificates for current user */
179    private final WifiCertManager mCertManager;
180
181    private final WifiInjector mWifiInjector;
182    /* Backup/Restore Module */
183    private final WifiBackupRestore mWifiBackupRestore;
184
185    // Map of package name of background scan apps and last scan timestamp.
186    private final ArrayMap<String, Long> mLastScanTimestamps;
187
188    private WifiScanner mWifiScanner;
189    private WifiLog mLog;
190
191    /**
192     * Asynchronous channel to WifiStateMachine
193     */
194    private AsyncChannel mWifiStateMachineChannel;
195
196    private final boolean mPermissionReviewRequired;
197    private final FrameworkFacade mFrameworkFacade;
198
199    private WifiPermissionsUtil mWifiPermissionsUtil;
200
201    @GuardedBy("mLocalOnlyHotspotRequests")
202    private final HashMap<Integer, LocalOnlyHotspotRequestInfo> mLocalOnlyHotspotRequests;
203    @GuardedBy("mLocalOnlyHotspotRequests")
204    private WifiConfiguration mLocalOnlyHotspotConfig = null;
205    @GuardedBy("mLocalOnlyHotspotRequests")
206    private final ConcurrentHashMap<String, Integer> mIfaceIpModes;
207
208    /**
209     * Callback for use with LocalOnlyHotspot to unregister requesting applications upon death.
210     *
211     * @hide
212     */
213    public final class LocalOnlyRequestorCallback
214            implements LocalOnlyHotspotRequestInfo.RequestingApplicationDeathCallback {
215        /**
216         * Called with requesting app has died.
217         */
218        @Override
219        public void onLocalOnlyHotspotRequestorDeath(LocalOnlyHotspotRequestInfo requestor) {
220            unregisterCallingAppAndStopLocalOnlyHotspot(requestor);
221        };
222    }
223
224    /**
225     * Handles client connections
226     */
227    private class ClientHandler extends WifiHandler {
228
229        ClientHandler(String tag, Looper looper) {
230            super(tag, looper);
231        }
232
233        @Override
234        public void handleMessage(Message msg) {
235            super.handleMessage(msg);
236            switch (msg.what) {
237                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
238                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
239                        if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
240                        // We track the clients by the Messenger
241                        // since it is expected to be always available
242                        mTrafficPoller.addClient(msg.replyTo);
243                    } else {
244                        Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
245                    }
246                    break;
247                }
248                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
249                    if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
250                        if (DBG) Slog.d(TAG, "Send failed, client connection lost");
251                    } else {
252                        if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
253                    }
254                    mTrafficPoller.removeClient(msg.replyTo);
255                    break;
256                }
257                case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
258                    AsyncChannel ac = mFrameworkFacade.makeWifiAsyncChannel(TAG);
259                    ac.connect(mContext, this, msg.replyTo);
260                    break;
261                }
262                case WifiManager.CONNECT_NETWORK: {
263                    WifiConfiguration config = (WifiConfiguration) msg.obj;
264                    int networkId = msg.arg1;
265                    Slog.d("WiFiServiceImpl ", "CONNECT "
266                            + " nid=" + Integer.toString(networkId)
267                            + " uid=" + msg.sendingUid
268                            + " name="
269                            + mContext.getPackageManager().getNameForUid(msg.sendingUid));
270                    if (config != null && isValid(config)) {
271                        if (DBG) Slog.d(TAG, "Connect with config " + config);
272                        /* Command is forwarded to state machine */
273                        mWifiStateMachine.sendMessage(Message.obtain(msg));
274                    } else if (config == null
275                            && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
276                        if (DBG) Slog.d(TAG, "Connect with networkId " + networkId);
277                        mWifiStateMachine.sendMessage(Message.obtain(msg));
278                    } else {
279                        Slog.e(TAG, "ClientHandler.handleMessage ignoring invalid msg=" + msg);
280                        replyFailed(msg, WifiManager.CONNECT_NETWORK_FAILED,
281                                WifiManager.INVALID_ARGS);
282                    }
283                    break;
284                }
285                case WifiManager.SAVE_NETWORK: {
286                    WifiConfiguration config = (WifiConfiguration) msg.obj;
287                    int networkId = msg.arg1;
288                    Slog.d("WiFiServiceImpl ", "SAVE"
289                            + " nid=" + Integer.toString(networkId)
290                            + " uid=" + msg.sendingUid
291                            + " name="
292                            + mContext.getPackageManager().getNameForUid(msg.sendingUid));
293                    if (config != null && isValid(config)) {
294                        if (DBG) Slog.d(TAG, "Save network with config " + config);
295                        /* Command is forwarded to state machine */
296                        mWifiStateMachine.sendMessage(Message.obtain(msg));
297                    } else {
298                        Slog.e(TAG, "ClientHandler.handleMessage ignoring invalid msg=" + msg);
299                        replyFailed(msg, WifiManager.SAVE_NETWORK_FAILED,
300                                WifiManager.INVALID_ARGS);
301                    }
302                    break;
303                }
304                case WifiManager.FORGET_NETWORK:
305                    mWifiStateMachine.sendMessage(Message.obtain(msg));
306                    break;
307                case WifiManager.START_WPS:
308                case WifiManager.CANCEL_WPS:
309                case WifiManager.DISABLE_NETWORK:
310                case WifiManager.RSSI_PKTCNT_FETCH: {
311                    mWifiStateMachine.sendMessage(Message.obtain(msg));
312                    break;
313                }
314                default: {
315                    Slog.d(TAG, "ClientHandler.handleMessage ignoring msg=" + msg);
316                    break;
317                }
318            }
319        }
320
321        private void replyFailed(Message msg, int what, int why) {
322            if (msg.replyTo == null) return;
323            Message reply = Message.obtain();
324            reply.what = what;
325            reply.arg1 = why;
326            try {
327                msg.replyTo.send(reply);
328            } catch (RemoteException e) {
329                // There's not much we can do if reply can't be sent!
330            }
331        }
332    }
333    private ClientHandler mClientHandler;
334
335    /**
336     * Handles interaction with WifiStateMachine
337     */
338    private class WifiStateMachineHandler extends WifiHandler {
339        private AsyncChannel mWsmChannel;
340
341        WifiStateMachineHandler(String tag, Looper looper, AsyncChannel asyncChannel) {
342            super(tag, looper);
343            mWsmChannel = asyncChannel;
344            mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
345        }
346
347        @Override
348        public void handleMessage(Message msg) {
349            super.handleMessage(msg);
350            switch (msg.what) {
351                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
352                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
353                        mWifiStateMachineChannel = mWsmChannel;
354                    } else {
355                        Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
356                        mWifiStateMachineChannel = null;
357                    }
358                    break;
359                }
360                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
361                    Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
362                    mWifiStateMachineChannel = null;
363                    //Re-establish connection to state machine
364                    mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
365                    break;
366                }
367                default: {
368                    Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
369                    break;
370                }
371            }
372        }
373    }
374
375    WifiStateMachineHandler mWifiStateMachineHandler;
376    private WifiController mWifiController;
377    private final WifiLockManager mWifiLockManager;
378    private final WifiMulticastLockManager mWifiMulticastLockManager;
379
380    public WifiServiceImpl(Context context, WifiInjector wifiInjector, AsyncChannel asyncChannel) {
381        mContext = context;
382        mWifiInjector = wifiInjector;
383        mClock = wifiInjector.getClock();
384
385        mFacade = mWifiInjector.getFrameworkFacade();
386        mWifiMetrics = mWifiInjector.getWifiMetrics();
387        mTrafficPoller = mWifiInjector.getWifiTrafficPoller();
388        mUserManager = mWifiInjector.getUserManager();
389        mCountryCode = mWifiInjector.getWifiCountryCode();
390        mWifiStateMachine = mWifiInjector.getWifiStateMachine();
391        mWifiStateMachine.enableRssiPolling(true);
392        mSettingsStore = mWifiInjector.getWifiSettingsStore();
393        mPowerManager = mContext.getSystemService(PowerManager.class);
394        mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
395        mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
396        mCertManager = mWifiInjector.getWifiCertManager();
397        mNotificationController = mWifiInjector.getWifiNotificationController();
398        mWifiLockManager = mWifiInjector.getWifiLockManager();
399        mWifiMulticastLockManager = mWifiInjector.getWifiMulticastLockManager();
400        HandlerThread wifiServiceHandlerThread = mWifiInjector.getWifiServiceHandlerThread();
401        mClientHandler = new ClientHandler(TAG, wifiServiceHandlerThread.getLooper());
402        mWifiStateMachineHandler = new WifiStateMachineHandler(TAG,
403                wifiServiceHandlerThread.getLooper(), asyncChannel);
404        mWifiController = mWifiInjector.getWifiController();
405        mWifiBackupRestore = mWifiInjector.getWifiBackupRestore();
406        mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
407                || context.getResources().getBoolean(
408                com.android.internal.R.bool.config_permissionReviewRequired);
409        mWifiPermissionsUtil = mWifiInjector.getWifiPermissionsUtil();
410        mLog = mWifiInjector.makeLog(TAG);
411        mFrameworkFacade = wifiInjector.getFrameworkFacade();
412        mLastScanTimestamps = new ArrayMap<>();
413        updateBackgroundThrottleInterval();
414        updateBackgroundThrottlingWhitelist();
415        mIfaceIpModes = new ConcurrentHashMap<>();
416        mLocalOnlyHotspotRequests = new HashMap<>();
417        enableVerboseLoggingInternal(getVerboseLoggingLevel());
418    }
419
420    /**
421     * Provide a way for unit tests to set valid log object in the WifiHandler
422     * @param log WifiLog object to assign to the clientHandler
423     */
424    @VisibleForTesting
425    public void setWifiHandlerLogForTest(WifiLog log) {
426        mClientHandler.setWifiLog(log);
427    }
428
429    /**
430     * Check if we are ready to start wifi.
431     *
432     * First check if we will be restarting system services to decrypt the device. If the device is
433     * not encrypted, check if Wi-Fi needs to be enabled and start if needed
434     *
435     * This function is used only at boot time.
436     */
437    public void checkAndStartWifi() {
438        // First check if we will end up restarting WifiService
439        if (mFrameworkFacade.inStorageManagerCryptKeeperBounce()) {
440            Log.d(TAG, "Device still encrypted. Need to restart SystemServer.  Do not start wifi.");
441            return;
442        }
443
444        // Check if wi-fi needs to be enabled
445        boolean wifiEnabled = mSettingsStore.isWifiToggleEnabled();
446        Slog.i(TAG, "WifiService starting up with Wi-Fi " +
447                (wifiEnabled ? "enabled" : "disabled"));
448
449        registerForScanModeChange();
450        registerForBackgroundThrottleChanges();
451        mContext.registerReceiver(
452                new BroadcastReceiver() {
453                    @Override
454                    public void onReceive(Context context, Intent intent) {
455                        if (mSettingsStore.handleAirplaneModeToggled()) {
456                            mWifiController.sendMessage(CMD_AIRPLANE_TOGGLED);
457                        }
458                        if (mSettingsStore.isAirplaneModeOn()) {
459                            Log.d(TAG, "resetting country code because Airplane mode is ON");
460                            mCountryCode.airplaneModeEnabled();
461                        }
462                    }
463                },
464                new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
465
466        mContext.registerReceiver(
467                new BroadcastReceiver() {
468                    @Override
469                    public void onReceive(Context context, Intent intent) {
470                        String state = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE);
471                        if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(state)) {
472                            Log.d(TAG, "resetting networks because SIM was removed");
473                            mWifiStateMachine.resetSimAuthNetworks(false);
474                            Log.d(TAG, "resetting country code because SIM is removed");
475                            mCountryCode.simCardRemoved();
476                        } else if (IccCardConstants.INTENT_VALUE_ICC_LOADED.equals(state)) {
477                            Log.d(TAG, "resetting networks because SIM was loaded");
478                            mWifiStateMachine.resetSimAuthNetworks(true);
479                        }
480                    }
481                },
482                new IntentFilter(TelephonyIntents.ACTION_SIM_STATE_CHANGED));
483
484        mContext.registerReceiver(
485                new BroadcastReceiver() {
486                    @Override
487                    public void onReceive(Context context, Intent intent) {
488                        final int currentState = intent.getIntExtra(EXTRA_WIFI_AP_STATE,
489                                                                    WIFI_AP_STATE_DISABLED);
490                        final int prevState = intent.getIntExtra(EXTRA_PREVIOUS_WIFI_AP_STATE,
491                                                                 WIFI_AP_STATE_DISABLED);
492                        final int errorCode = intent.getIntExtra(EXTRA_WIFI_AP_FAILURE_REASON,
493                                                                 HOTSPOT_NO_ERROR);
494                        handleWifiApStateChange(currentState, prevState, errorCode);
495                    }
496                },
497                new IntentFilter(WifiManager.WIFI_AP_STATE_CHANGED_ACTION));
498
499        // Adding optimizations of only receiving broadcasts when wifi is enabled
500        // can result in race conditions when apps toggle wifi in the background
501        // without active user involvement. Always receive broadcasts.
502        registerForBroadcasts();
503        registerForPackageOrUserRemoval();
504        mInIdleMode = mPowerManager.isDeviceIdleMode();
505
506        if (!mWifiStateMachine.syncInitialize(mWifiStateMachineChannel)) {
507            Log.wtf(TAG, "Failed to initialize WifiStateMachine");
508        }
509        mWifiController.start();
510
511        // If we are already disabled (could be due to airplane mode), avoid changing persist
512        // state here
513        if (wifiEnabled) {
514            try {
515                setWifiEnabled(mContext.getPackageName(), wifiEnabled);
516            } catch (RemoteException e) {
517                /* ignore - local call */
518            }
519        }
520    }
521
522    public void handleUserSwitch(int userId) {
523        mWifiStateMachine.handleUserSwitch(userId);
524    }
525
526    public void handleUserUnlock(int userId) {
527        mWifiStateMachine.handleUserUnlock(userId);
528    }
529
530    public void handleUserStop(int userId) {
531        mWifiStateMachine.handleUserStop(userId);
532    }
533
534    /**
535     * see {@link android.net.wifi.WifiManager#startScan}
536     * and {@link android.net.wifi.WifiManager#startCustomizedScan}
537     *
538     * @param settings If null, use default parameter, i.e. full scan.
539     * @param workSource If null, all blame is given to the calling uid.
540     * @param packageName Package name of the app that requests wifi scan.
541     */
542    @Override
543    public void startScan(ScanSettings settings, WorkSource workSource, String packageName) {
544        enforceChangePermission();
545
546        mLog.trace("startScan uid=%").c(Binder.getCallingUid()).flush();
547        // Check and throttle background apps for wifi scan.
548        if (isRequestFromBackground(packageName)) {
549            long lastScanMs = mLastScanTimestamps.getOrDefault(packageName, 0L);
550            long elapsedRealtime = mClock.getElapsedSinceBootMillis();
551
552            if (lastScanMs != 0 && (elapsedRealtime - lastScanMs) < mBackgroundThrottleInterval) {
553                sendFailedScanBroadcast();
554                return;
555            }
556            // Proceed with the scan request and record the time.
557            mLastScanTimestamps.put(packageName, elapsedRealtime);
558        }
559        synchronized (this) {
560            if (mWifiScanner == null) {
561                mWifiScanner = mWifiInjector.getWifiScanner();
562            }
563            if (mInIdleMode) {
564                // Need to send an immediate scan result broadcast in case the
565                // caller is waiting for a result ..
566
567                // TODO: investigate if the logic to cancel scans when idle can move to
568                // WifiScanningServiceImpl.  This will 1 - clean up WifiServiceImpl and 2 -
569                // avoid plumbing an awkward path to report a cancelled/failed scan.  This will
570                // be sent directly until b/31398592 is fixed.
571                sendFailedScanBroadcast();
572                mScanPending = true;
573                return;
574            }
575        }
576        if (settings != null) {
577            settings = new ScanSettings(settings);
578            if (!settings.isValid()) {
579                Slog.e(TAG, "invalid scan setting");
580                return;
581            }
582        }
583        if (workSource != null) {
584            enforceWorkSourcePermission();
585            // WifiManager currently doesn't use names, so need to clear names out of the
586            // supplied WorkSource to allow future WorkSource combining.
587            workSource.clearNames();
588        }
589        if (workSource == null && Binder.getCallingUid() >= 0) {
590            workSource = new WorkSource(Binder.getCallingUid());
591        }
592        mWifiStateMachine.startScan(Binder.getCallingUid(), scanRequestCounter++,
593                settings, workSource);
594    }
595
596    // Send a failed scan broadcast to indicate the current scan request failed.
597    private void sendFailedScanBroadcast() {
598        // clear calling identity to send broadcast
599        long callingIdentity = Binder.clearCallingIdentity();
600        try {
601            Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
602            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
603            intent.putExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
604            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
605        } finally {
606            // restore calling identity
607            Binder.restoreCallingIdentity(callingIdentity);
608        }
609
610    }
611
612    // Check if the request comes from background.
613    private boolean isRequestFromBackground(String packageName) {
614        // Requests from system or wifi are not background.
615        if (Binder.getCallingUid() == Process.SYSTEM_UID
616                || Binder.getCallingUid() == Process.WIFI_UID) {
617            return false;
618        }
619        mAppOps.checkPackage(Binder.getCallingUid(), packageName);
620        if (mBackgroundThrottlePackageWhitelist.contains(packageName)) {
621            return false;
622        }
623
624        // getPackageImportance requires PACKAGE_USAGE_STATS permission, so clearing the incoming
625        // identify so the permission check can be done on system process where wifi runs in.
626        long callingIdentity = Binder.clearCallingIdentity();
627        try {
628            return mActivityManager.getPackageImportance(packageName)
629                    > BACKGROUND_IMPORTANCE_CUTOFF;
630        } finally {
631            Binder.restoreCallingIdentity(callingIdentity);
632        }
633    }
634
635    @Override
636    public String getCurrentNetworkWpsNfcConfigurationToken() {
637        enforceConnectivityInternalPermission();
638        mLog.trace("getCurrentNetworkWpsNfcConfigurationToken uid=%")
639                .c(Binder.getCallingUid()).flush();
640        // TODO Add private logging for netId b/33807876
641        return mWifiStateMachine.syncGetCurrentNetworkWpsNfcConfigurationToken();
642    }
643
644    boolean mInIdleMode;
645    boolean mScanPending;
646
647    void handleIdleModeChanged() {
648        boolean doScan = false;
649        synchronized (this) {
650            boolean idle = mPowerManager.isDeviceIdleMode();
651            if (mInIdleMode != idle) {
652                mInIdleMode = idle;
653                if (!idle) {
654                    if (mScanPending) {
655                        mScanPending = false;
656                        doScan = true;
657                    }
658                }
659            }
660        }
661        if (doScan) {
662            // Someone requested a scan while we were idle; do a full scan now.
663            // The package name doesn't matter as the request comes from System UID.
664            startScan(null, null, "");
665        }
666    }
667
668    private void enforceNetworkSettingsPermission() {
669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS,
670                "WifiService");
671    }
672
673    private void enforceNetworkStackPermission() {
674        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK,
675                "WifiService");
676    }
677
678    private void enforceAccessPermission() {
679        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
680                "WifiService");
681    }
682
683    private void enforceChangePermission() {
684        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
685                "WifiService");
686    }
687
688    private void enforceLocationHardwarePermission() {
689        mContext.enforceCallingOrSelfPermission(Manifest.permission.LOCATION_HARDWARE,
690                "LocationHardware");
691    }
692
693    private void enforceReadCredentialPermission() {
694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.READ_WIFI_CREDENTIAL,
695                                                "WifiService");
696    }
697
698    private void enforceWorkSourcePermission() {
699        mContext.enforceCallingPermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
700                "WifiService");
701
702    }
703
704    private void enforceMulticastChangePermission() {
705        mContext.enforceCallingOrSelfPermission(
706                android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
707                "WifiService");
708    }
709
710    private void enforceConnectivityInternalPermission() {
711        mContext.enforceCallingOrSelfPermission(
712                android.Manifest.permission.CONNECTIVITY_INTERNAL,
713                "ConnectivityService");
714    }
715
716    private void enforceLocationPermission(String pkgName, int uid) {
717        mWifiPermissionsUtil.enforceLocationPermission(pkgName, uid);
718    }
719
720    /**
721     * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
722     * @param enable {@code true} to enable, {@code false} to disable.
723     * @return {@code true} if the enable/disable operation was
724     *         started or is already in the queue.
725     */
726    @Override
727    public synchronized boolean setWifiEnabled(String packageName, boolean enable)
728            throws RemoteException {
729        enforceChangePermission();
730        Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
731                    + ", uid=" + Binder.getCallingUid() + ", package=" + packageName);
732        mLog.trace("setWifiEnabled package=% uid=% enable=%").c(packageName)
733                .c(Binder.getCallingUid()).c(enable).flush();
734
735        // If SoftAp is enabled, only Settings is allowed to toggle wifi
736        boolean apEnabled =
737                mWifiStateMachine.syncGetWifiApState() != WifiManager.WIFI_AP_STATE_DISABLED;
738        boolean isFromSettings =
739                packageName.equals(SYSUI_PACKAGE_NAME) || packageName.equals(SETTINGS_PACKAGE_NAME);
740        if (apEnabled && !isFromSettings) {
741            mLog.trace("setWifiEnabled SoftAp not disabled: only Settings can enable wifi").flush();
742            return false;
743        }
744
745        /*
746        * Caller might not have WRITE_SECURE_SETTINGS,
747        * only CHANGE_WIFI_STATE is enforced
748        */
749        long ident = Binder.clearCallingIdentity();
750        try {
751            if (! mSettingsStore.handleWifiToggled(enable)) {
752                // Nothing to do if wifi cannot be toggled
753                return true;
754            }
755        } finally {
756            Binder.restoreCallingIdentity(ident);
757        }
758
759
760        if (mPermissionReviewRequired) {
761            final int wiFiEnabledState = getWifiEnabledState();
762            if (enable) {
763                if (wiFiEnabledState == WifiManager.WIFI_STATE_DISABLING
764                        || wiFiEnabledState == WifiManager.WIFI_STATE_DISABLED) {
765                    if (startConsentUi(packageName, Binder.getCallingUid(),
766                            WifiManager.ACTION_REQUEST_ENABLE)) {
767                        return true;
768                    }
769                }
770            } else if (wiFiEnabledState == WifiManager.WIFI_STATE_ENABLING
771                    || wiFiEnabledState == WifiManager.WIFI_STATE_ENABLED) {
772                if (startConsentUi(packageName, Binder.getCallingUid(),
773                        WifiManager.ACTION_REQUEST_DISABLE)) {
774                    return true;
775                }
776            }
777        }
778
779        mWifiController.sendMessage(CMD_WIFI_TOGGLED);
780        return true;
781    }
782
783    /**
784     * see {@link WifiManager#getWifiState()}
785     * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
786     *         {@link WifiManager#WIFI_STATE_DISABLING},
787     *         {@link WifiManager#WIFI_STATE_ENABLED},
788     *         {@link WifiManager#WIFI_STATE_ENABLING},
789     *         {@link WifiManager#WIFI_STATE_UNKNOWN}
790     */
791    @Override
792    public int getWifiEnabledState() {
793        enforceAccessPermission();
794        mLog.trace("getWifiEnabledState uid=%").c(Binder.getCallingUid()).flush();
795        return mWifiStateMachine.syncGetWifiState();
796    }
797
798    /**
799     * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
800     * @param wifiConfig SSID, security and channel details as
801     *        part of WifiConfiguration
802     * @param enabled true to enable and false to disable
803     */
804    @Override
805    public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
806        enforceChangePermission();
807        mWifiPermissionsUtil.enforceTetherChangePermission(mContext);
808
809        mLog.trace("setWifiApEnabled uid=% enable=%").c(Binder.getCallingUid()).c(enabled).flush();
810
811        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
812            throw new SecurityException("DISALLOW_CONFIG_TETHERING is enabled for this user.");
813        }
814        // null wifiConfig is a meaningful input for CMD_SET_AP
815        if (wifiConfig == null || isValid(wifiConfig)) {
816            mWifiController.sendMessage(CMD_SET_AP, enabled ? 1 : 0, 0, wifiConfig);
817        } else {
818            Slog.e(TAG, "Invalid WifiConfiguration");
819        }
820    }
821
822    /**
823     * see {@link WifiManager#getWifiApState()}
824     * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
825     *         {@link WifiManager#WIFI_AP_STATE_DISABLING},
826     *         {@link WifiManager#WIFI_AP_STATE_ENABLED},
827     *         {@link WifiManager#WIFI_AP_STATE_ENABLING},
828     *         {@link WifiManager#WIFI_AP_STATE_FAILED}
829     */
830    @Override
831    public int getWifiApEnabledState() {
832        enforceAccessPermission();
833        mLog.trace("getWifiApEnabledState uid=%").c(Binder.getCallingUid()).flush();
834        return mWifiStateMachine.syncGetWifiApState();
835    }
836
837    /**
838     * see {@link android.net.wifi.WifiManager#updateInterfaceIpState(String, int)}
839     *
840     * The possible modes include: {@link WifiManager#IFACE_IP_MODE_TETHERED},
841     *                             {@link WifiManager#IFACE_IP_MODE_LOCAL_ONLY},
842     *                             {@link WifiManager#IFACE_IP_MODE_CONFIGURATION_ERROR}
843     *
844     * @param ifaceName String name of the updated interface
845     * @param mode new operating mode of the interface
846     *
847     * @throws SecurityException if the caller does not have permission to call update
848     */
849    @Override
850    public void updateInterfaceIpState(String ifaceName, int mode) {
851        // NETWORK_STACK is a signature only permission.
852        enforceNetworkStackPermission();
853
854        // hand off the work to our handler thread
855        mClientHandler.post(() -> {
856            updateInterfaceIpStateInternal(ifaceName, mode);
857        });
858    }
859
860    private void updateInterfaceIpStateInternal(String ifaceName, int mode) {
861        // update interface IP state related to tethering and hotspot
862        synchronized (mLocalOnlyHotspotRequests) {
863            // update the mode tracker here - we clear out state below
864            Integer previousMode = WifiManager.IFACE_IP_MODE_UNSPECIFIED;
865            if (ifaceName != null) {
866                previousMode = mIfaceIpModes.put(ifaceName, mode);
867            }
868            Slog.d(TAG, "updateInterfaceIpState: ifaceName=" + ifaceName + " mode=" + mode
869                    + " previous mode= " + previousMode);
870
871            switch (mode) {
872                case WifiManager.IFACE_IP_MODE_LOCAL_ONLY:
873                    // first make sure we have registered requests..  otherwise clean up
874                    if (mLocalOnlyHotspotRequests.isEmpty()) {
875                        // we don't have requests...  stop the hotspot
876                        stopSoftAp();
877                        updateInterfaceIpStateInternal(null, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
878                        return;
879                    }
880                    // LOHS is ready to go!  Call our registered requestors!
881                    sendHotspotStartedMessageToAllLOHSRequestInfoEntriesLocked();
882                    break;
883                case WifiManager.IFACE_IP_MODE_TETHERED:
884                    // we have tethered an interface. we don't really act on this now other than if
885                    // we have LOHS requests, and this is an issue.  return incompatible mode for
886                    // onFailed for the registered requestors since this can result from a race
887                    // between a tether request and a hotspot request (tethering wins).
888                    sendHotspotFailedMessageToAllLOHSRequestInfoEntriesLocked(
889                            LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE);
890                    mLocalOnlyHotspotRequests.clear();
891                    break;
892                case WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR:
893                    // there was an error setting up the hotspot...  trigger onFailed for the
894                    // registered LOHS requestors
895                    sendHotspotFailedMessageToAllLOHSRequestInfoEntriesLocked(
896                            LocalOnlyHotspotCallback.ERROR_GENERIC);
897                    mLocalOnlyHotspotRequests.clear();
898                    updateInterfaceIpStateInternal(null, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
899                    break;
900                case WifiManager.IFACE_IP_MODE_UNSPECIFIED:
901                    if (ifaceName == null) {
902                        // interface name is null, this is due to softap teardown.  clear all
903                        // entries for now.
904                        // TODO: Deal with individual interfaces when we receive updates for them
905                        mIfaceIpModes.clear();
906                        return;
907                    }
908                    break;
909                default:
910                    mLog.trace("updateInterfaceIpStateInternal: unknown mode %").c(mode).flush();
911            }
912        }
913    }
914
915    /**
916     * see {@link android.net.wifi.WifiManager#startSoftAp(WifiConfiguration)}
917     * @param wifiConfig SSID, security and channel details as part of WifiConfiguration
918     * @return {@code true} if softap start was triggered
919     * @throws SecurityException if the caller does not have permission to start softap
920     */
921    @Override
922    public boolean startSoftAp(WifiConfiguration wifiConfig) {
923        // NETWORK_STACK is a signature only permission.
924        enforceNetworkStackPermission();
925
926        mLog.trace("startSoftAp uid=%").c(Binder.getCallingUid()).flush();
927
928        // TODO: determine if we need to stop softap and clean up state if a tethering request comes
929        // from the user while we are just setting up. For now, the second CMD_START_AP will be
930        // ignored in WifiStateMachine.  This will still bring up tethering and the registered LOHS
931        // requests will be cleared when we get the interface ip tethered status.
932
933        return startSoftApInternal(wifiConfig, STATE_TETHERED);
934    }
935
936    /**
937     * Internal method to start softap mode. Callers of this method should have already checked
938     * proper permissions beyond the NetworkStack permission.
939     */
940    private boolean startSoftApInternal(WifiConfiguration wifiConfig, int mode) {
941        mLog.trace("startSoftApInternal uid=% mode=%")
942                .c(Binder.getCallingUid()).c(mode).flush();
943
944        // null wifiConfig is a meaningful input for CMD_SET_AP
945        if (wifiConfig == null || isValid(wifiConfig)) {
946            // TODO: need a way to set the mode
947            mWifiController.sendMessage(CMD_SET_AP, 1, 0, wifiConfig);
948            return true;
949        }
950        Slog.e(TAG, "Invalid WifiConfiguration");
951        return false;
952    }
953
954    /**
955     * see {@link android.net.wifi.WifiManager#stopSoftAp()}
956     * @return {@code true} if softap stop was triggered
957     * @throws SecurityException if the caller does not have permission to stop softap
958     */
959    @Override
960    public boolean stopSoftAp() {
961        // NETWORK_STACK is a signature only permission.
962        enforceNetworkStackPermission();
963
964        mLog.trace("stopSoftAp uid=%").c(Binder.getCallingUid()).flush();
965
966        // add checks here to make sure this is the proper caller - apps can't disable tethering or
967        // instances of local only hotspot that they didn't start.  return false for those cases
968
969        return stopSoftApInternal();
970    }
971
972    /**
973     * Internal method to stop softap mode.  Callers of this method should have already checked
974     * proper permissions beyond the NetworkStack permission.
975     */
976    private boolean stopSoftApInternal() {
977        mLog.trace("stopSoftApInternal uid=%").c(Binder.getCallingUid()).flush();
978
979        // we have an allowed caller - clear local only hotspot if it was enabled
980        synchronized (mLocalOnlyHotspotRequests) {
981            mLocalOnlyHotspotRequests.clear();
982            mLocalOnlyHotspotConfig = null;
983        }
984        mWifiController.sendMessage(CMD_SET_AP, 0, 0);
985        return true;
986    }
987
988    /**
989     * Private method to handle SoftAp state changes
990     */
991    private void handleWifiApStateChange(int currentState, int previousState, int errorCode) {
992        // The AP state update from WifiStateMachine for softap
993        Slog.d(TAG, "handleWifiApStateChange: currentState=" + currentState
994                + " previousState=" + previousState + " errorCode= " + errorCode);
995
996        // check if we have a failure - since it is possible (worst case scenario where
997        // WifiController and WifiStateMachine are out of sync wrt modes) to get two FAILED
998        // notifications in a row, we need to handle this first.
999        if (currentState == WIFI_AP_STATE_FAILED) {
1000            // update registered LOHS callbacks if we see a failure
1001            synchronized (mLocalOnlyHotspotRequests) {
1002                int errorToReport = ERROR_GENERIC;
1003                if (errorCode == SAP_START_FAILURE_NO_CHANNEL) {
1004                    errorToReport = ERROR_NO_CHANNEL;
1005                }
1006                // holding the required lock: send message to requestors and clear the list
1007                sendHotspotFailedMessageToAllLOHSRequestInfoEntriesLocked(
1008                        errorToReport);
1009                // also need to clear interface ip state - send null for now since we don't know
1010                // what interface (and we have one anyway)
1011                updateInterfaceIpStateInternal(null, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
1012            }
1013            return;
1014        }
1015
1016        if (currentState == WIFI_AP_STATE_DISABLING || currentState == WIFI_AP_STATE_DISABLED) {
1017            // softap is shutting down or is down...  let requestors know via the onStopped call
1018            synchronized (mLocalOnlyHotspotRequests) {
1019                // if we are currently in hotspot mode, then trigger onStopped for registered
1020                // requestors, otherwise something odd happened and we should clear state
1021                if (mIfaceIpModes.contains(WifiManager.IFACE_IP_MODE_LOCAL_ONLY)) {
1022                    // holding the required lock: send message to requestors and clear the list
1023                    sendHotspotStoppedMessageToAllLOHSRequestInfoEntriesLocked();
1024                } else {
1025                    // LOHS not active: report an error (still holding the required lock)
1026                    sendHotspotFailedMessageToAllLOHSRequestInfoEntriesLocked(ERROR_GENERIC);
1027                }
1028                // also clear interface ip state - send null for now since we don't know what
1029                // interface (and we only have one anyway)
1030                updateInterfaceIpState(null, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
1031            }
1032            return;
1033        }
1034
1035        // remaining states are enabling or enabled...  those are not used for the callbacks
1036    }
1037
1038    /**
1039     * Helper method to send a HOTSPOT_FAILED message to all registered LocalOnlyHotspotRequest
1040     * callers and clear the registrations.
1041     *
1042     * Callers should already hold the mLocalOnlyHotspotRequests lock.
1043     */
1044    private void sendHotspotFailedMessageToAllLOHSRequestInfoEntriesLocked(int arg1) {
1045        for (LocalOnlyHotspotRequestInfo requestor : mLocalOnlyHotspotRequests.values()) {
1046            try {
1047                requestor.sendHotspotFailedMessage(arg1);
1048            } catch (RemoteException e) {
1049                // This will be cleaned up by binder death handling
1050            }
1051        }
1052
1053        // Since all callers were notified, now clear the registrations.
1054        mLocalOnlyHotspotRequests.clear();
1055    }
1056
1057    /**
1058     * Helper method to send a HOTSPOT_STOPPED message to all registered LocalOnlyHotspotRequest
1059     * callers and clear the registrations.
1060     *
1061     * Callers should already hold the mLocalOnlyHotspotRequests lock.
1062     */
1063    private void sendHotspotStoppedMessageToAllLOHSRequestInfoEntriesLocked() {
1064        for (LocalOnlyHotspotRequestInfo requestor : mLocalOnlyHotspotRequests.values()) {
1065            try {
1066                requestor.sendHotspotStoppedMessage();
1067            } catch (RemoteException e) {
1068                // This will be cleaned up by binder death handling
1069            }
1070        }
1071
1072        // Since all callers were notified, now clear the registrations.
1073        mLocalOnlyHotspotRequests.clear();
1074    }
1075
1076    /**
1077     * Helper method to send a HOTSPOT_STARTED message to all registered LocalOnlyHotspotRequest
1078     * callers.
1079     *
1080     * Callers should already hold the mLocalOnlyHotspotRequests lock.
1081     */
1082    private void sendHotspotStartedMessageToAllLOHSRequestInfoEntriesLocked() {
1083        for (LocalOnlyHotspotRequestInfo requestor : mLocalOnlyHotspotRequests.values()) {
1084            try {
1085                requestor.sendHotspotStartedMessage(mLocalOnlyHotspotConfig);
1086            } catch (RemoteException e) {
1087                // This will be cleaned up by binder death handling
1088            }
1089        }
1090    }
1091
1092    /**
1093     * Temporary method used for testing while startLocalOnlyHotspot is not fully implemented.  This
1094     * method allows unit tests to register callbacks directly for testing mechanisms triggered by
1095     * softap mode changes.
1096     */
1097    @VisibleForTesting
1098    void registerLOHSForTest(int pid, LocalOnlyHotspotRequestInfo request) {
1099        mLocalOnlyHotspotRequests.put(pid, request);
1100    }
1101
1102    /**
1103     * Method to start LocalOnlyHotspot.  In this method, permissions, settings and modes are
1104     * checked to verify that we can enter softapmode.  This method returns
1105     * {@link LocalOnlyHotspotCallback#REQUEST_REGISTERED} if we will attempt to start, otherwise,
1106     * possible startup erros may include tethering being disallowed failure reason {@link
1107     * LocalOnlyHotspotCallback#ERROR_TETHERING_DISALLOWED} or an incompatible mode failure reason
1108     * {@link LocalOnlyHotspotCallback#ERROR_INCOMPATIBLE_MODE}.
1109     *
1110     * see {@link WifiManager#startLocalOnlyHotspot(LocalOnlyHotspotCallback)}
1111     *
1112     * @param messenger Messenger to send messages to the corresponding WifiManager.
1113     * @param binder IBinder instance to allow cleanup if the app dies
1114     * @param packageName String name of the calling package
1115     *
1116     * @return int return code for attempt to start LocalOnlyHotspot.
1117     *
1118     * @throws SecurityException if the caller does not have permission to start a Local Only
1119     * Hotspot.
1120     * @throws IllegalStateException if the caller attempts to start the LocalOnlyHotspot while they
1121     * have an outstanding request.
1122     */
1123    @Override
1124    public int startLocalOnlyHotspot(Messenger messenger, IBinder binder, String packageName) {
1125        // first check if the caller has permission to start a local only hotspot
1126        // need to check for WIFI_STATE_CHANGE and location permission
1127        final int uid = Binder.getCallingUid();
1128        final int pid = Binder.getCallingPid();
1129
1130        enforceChangePermission();
1131        enforceLocationPermission(packageName, uid);
1132        // also need to verify that Locations services are enabled.
1133        if (mSettingsStore.getLocationModeSetting(mContext) == Settings.Secure.LOCATION_MODE_OFF) {
1134            throw new SecurityException("Location mode is not enabled.");
1135        }
1136
1137        // verify that tethering is not disabled
1138        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
1139            return LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED;
1140        }
1141
1142        mLog.trace("startLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
1143
1144        synchronized (mLocalOnlyHotspotRequests) {
1145            // check if we are currently tethering
1146            if (mIfaceIpModes.contains(WifiManager.IFACE_IP_MODE_TETHERED)) {
1147                // Tethering is enabled, cannot start LocalOnlyHotspot
1148                mLog.trace("Cannot start localOnlyHotspot when WiFi Tethering is active.");
1149                return LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
1150            }
1151
1152            // does this caller already have a request?
1153            LocalOnlyHotspotRequestInfo request = mLocalOnlyHotspotRequests.get(pid);
1154            if (request != null) {
1155                mLog.trace("caller already has an active request");
1156                throw new IllegalStateException(
1157                        "Caller already has an active LocalOnlyHotspot request");
1158            }
1159
1160            // now create the new LOHS request info object
1161            request = new LocalOnlyHotspotRequestInfo(binder, messenger,
1162                    new LocalOnlyRequestorCallback());
1163
1164            // check current operating state and take action if needed
1165            if (mIfaceIpModes.contains(WifiManager.IFACE_IP_MODE_LOCAL_ONLY)) {
1166                // LOHS is already active, send out what is running
1167                try {
1168                    mLog.trace("LOHS already up, trigger onStarted callback");
1169                    request.sendHotspotStartedMessage(mLocalOnlyHotspotConfig);
1170                } catch (RemoteException e) {
1171                    return LocalOnlyHotspotCallback.ERROR_GENERIC;
1172                }
1173            } else if (mLocalOnlyHotspotRequests.isEmpty()) {
1174                // this is the first request, then set up our config and start LOHS
1175                mLocalOnlyHotspotConfig =
1176                        WifiApConfigStore.generateLocalOnlyHotspotConfig(mContext);
1177                startSoftApInternal(mLocalOnlyHotspotConfig, STATE_LOCAL_ONLY);
1178            }
1179
1180            mLocalOnlyHotspotRequests.put(pid, request);
1181            return LocalOnlyHotspotCallback.REQUEST_REGISTERED;
1182        }
1183    }
1184
1185    /**
1186     * see {@link WifiManager#stopLocalOnlyHotspot()}
1187     *
1188     * @throws SecurityException if the caller does not have permission to stop a Local Only
1189     * Hotspot.
1190     */
1191    @Override
1192    public void stopLocalOnlyHotspot() {
1193        // first check if the caller has permission to stop a local only hotspot
1194        enforceChangePermission();
1195        final int uid = Binder.getCallingUid();
1196        final int pid = Binder.getCallingPid();
1197
1198        mLog.trace("stopLocalOnlyHotspot uid=% pid=%").c(uid).c(pid).flush();
1199
1200        synchronized (mLocalOnlyHotspotRequests) {
1201            // was the caller already registered?  check request tracker - return false if not
1202            LocalOnlyHotspotRequestInfo requestInfo = mLocalOnlyHotspotRequests.get(pid);
1203            if (requestInfo == null) {
1204                return;
1205            }
1206            requestInfo.unlinkDeathRecipient();
1207            unregisterCallingAppAndStopLocalOnlyHotspot(requestInfo);
1208        } // end synchronized
1209    }
1210
1211    /**
1212     * Helper method to unregister LocalOnlyHotspot requestors and stop the hotspot if needed.
1213     */
1214    private void unregisterCallingAppAndStopLocalOnlyHotspot(LocalOnlyHotspotRequestInfo request) {
1215        mLog.trace("unregisterCallingAppAndStopLocalOnlyHotspot pid=%").c(request.getPid()).flush();
1216
1217        synchronized (mLocalOnlyHotspotRequests) {
1218            if (mLocalOnlyHotspotRequests.remove(request.getPid()) == null) {
1219                mLog.trace("LocalOnlyHotspotRequestInfo not found to remove");
1220                return;
1221            }
1222
1223            if (mLocalOnlyHotspotRequests.isEmpty()) {
1224                mLocalOnlyHotspotConfig = null;
1225                updateInterfaceIpStateInternal(null, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
1226                // if that was the last caller, then call stopSoftAp as WifiService
1227                long identity = Binder.clearCallingIdentity();
1228                try {
1229                    stopSoftApInternal();
1230                } finally {
1231                    Binder.restoreCallingIdentity(identity);
1232                }
1233            }
1234        }
1235    }
1236
1237    /**
1238     * see {@link WifiManager#watchLocalOnlyHotspot(LocalOnlyHotspotObserver)}
1239     *
1240     * This call requires the android.permission.NETWORK_SETTINGS permission.
1241     *
1242     * @param messenger Messenger to send messages to the corresponding WifiManager.
1243     * @param binder IBinder instance to allow cleanup if the app dies
1244     *
1245     * @throws SecurityException if the caller does not have permission to watch Local Only Hotspot
1246     * status updates.
1247     * @throws IllegalStateException if the caller attempts to watch LocalOnlyHotspot updates with
1248     * an existing subscription.
1249     */
1250    @Override
1251    public void startWatchLocalOnlyHotspot(Messenger messenger, IBinder binder) {
1252        final String packageName = mContext.getOpPackageName();
1253
1254        // NETWORK_SETTINGS is a signature only permission.
1255        enforceNetworkSettingsPermission();
1256
1257        throw new UnsupportedOperationException("LocalOnlyHotspot is still in development");
1258    }
1259
1260    /**
1261     * see {@link WifiManager#unregisterLocalOnlyHotspotObserver()}
1262     */
1263    @Override
1264    public void stopWatchLocalOnlyHotspot() {
1265        // NETWORK_STACK is a signature only permission.
1266        enforceNetworkSettingsPermission();
1267        throw new UnsupportedOperationException("LocalOnlyHotspot is still in development");
1268    }
1269
1270    /**
1271     * see {@link WifiManager#getWifiApConfiguration()}
1272     * @return soft access point configuration
1273     * @throws SecurityException if the caller does not have permission to retrieve the softap
1274     * config
1275     */
1276    @Override
1277    public WifiConfiguration getWifiApConfiguration() {
1278        enforceAccessPermission();
1279        int uid = Binder.getCallingUid();
1280        // only allow Settings UI to get the saved SoftApConfig
1281        if (!mWifiPermissionsUtil.checkConfigOverridePermission(uid)) {
1282            // random apps should not be allowed to read the user specified config
1283            throw new SecurityException("App not allowed to read or update stored WiFi Ap config "
1284                    + "(uid = " + uid + ")");
1285        }
1286        mLog.trace("getWifiApConfiguration uid=%").c(uid).flush();
1287        return mWifiStateMachine.syncGetWifiApConfiguration();
1288    }
1289
1290    /**
1291     * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
1292     * @param wifiConfig WifiConfiguration details for soft access point
1293     * @throws SecurityException if the caller does not have permission to write the sotap config
1294     */
1295    @Override
1296    public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
1297        enforceChangePermission();
1298        int uid = Binder.getCallingUid();
1299        // only allow Settings UI to write the stored SoftApConfig
1300        if (!mWifiPermissionsUtil.checkConfigOverridePermission(uid)) {
1301            // random apps should not be allowed to read the user specified config
1302            throw new SecurityException("App not allowed to read or update stored WiFi AP config "
1303                    + "(uid = " + uid + ")");
1304        }
1305        mLog.trace("setWifiApConfiguration uid=%").c(uid).flush();
1306        if (wifiConfig == null)
1307            return;
1308        if (isValid(wifiConfig)) {
1309            mWifiStateMachine.setWifiApConfiguration(wifiConfig);
1310        } else {
1311            Slog.e(TAG, "Invalid WifiConfiguration");
1312        }
1313    }
1314
1315    /**
1316     * see {@link android.net.wifi.WifiManager#isScanAlwaysAvailable()}
1317     */
1318    @Override
1319    public boolean isScanAlwaysAvailable() {
1320        enforceAccessPermission();
1321        mLog.trace("isScanAlwaysAvailable uid=%").c(Binder.getCallingUid()).flush();
1322        return mSettingsStore.isScanAlwaysAvailable();
1323    }
1324
1325    /**
1326     * see {@link android.net.wifi.WifiManager#disconnect()}
1327     */
1328    @Override
1329    public void disconnect() {
1330        enforceChangePermission();
1331        mLog.trace("disconnect uid=%").c(Binder.getCallingUid()).flush();
1332        mWifiStateMachine.disconnectCommand();
1333    }
1334
1335    /**
1336     * see {@link android.net.wifi.WifiManager#reconnect()}
1337     */
1338    @Override
1339    public void reconnect() {
1340        enforceChangePermission();
1341        mLog.trace("reconnect uid=%").c(Binder.getCallingUid()).flush();
1342        mWifiStateMachine.reconnectCommand();
1343    }
1344
1345    /**
1346     * see {@link android.net.wifi.WifiManager#reassociate()}
1347     */
1348    @Override
1349    public void reassociate() {
1350        enforceChangePermission();
1351        mLog.trace("reassociate uid=%").c(Binder.getCallingUid()).flush();
1352        mWifiStateMachine.reassociateCommand();
1353    }
1354
1355    /**
1356     * see {@link android.net.wifi.WifiManager#getSupportedFeatures}
1357     */
1358    @Override
1359    public int getSupportedFeatures() {
1360        enforceAccessPermission();
1361        mLog.trace("getSupportedFeatures uid=%").c(Binder.getCallingUid()).flush();
1362        if (mWifiStateMachineChannel != null) {
1363            return mWifiStateMachine.syncGetSupportedFeatures(mWifiStateMachineChannel);
1364        } else {
1365            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1366            return 0;
1367        }
1368    }
1369
1370    @Override
1371    public void requestActivityInfo(ResultReceiver result) {
1372        Bundle bundle = new Bundle();
1373        mLog.trace("requestActivityInfo uid=%").c(Binder.getCallingUid()).flush();
1374        bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, reportActivityInfo());
1375        result.send(0, bundle);
1376    }
1377
1378    /**
1379     * see {@link android.net.wifi.WifiManager#getControllerActivityEnergyInfo(int)}
1380     */
1381    @Override
1382    public WifiActivityEnergyInfo reportActivityInfo() {
1383        enforceAccessPermission();
1384        mLog.trace("reportActivityInfo uid=%").c(Binder.getCallingUid()).flush();
1385        if ((getSupportedFeatures() & WifiManager.WIFI_FEATURE_LINK_LAYER_STATS) == 0) {
1386            return null;
1387        }
1388        WifiLinkLayerStats stats;
1389        WifiActivityEnergyInfo energyInfo = null;
1390        if (mWifiStateMachineChannel != null) {
1391            stats = mWifiStateMachine.syncGetLinkLayerStats(mWifiStateMachineChannel);
1392            if (stats != null) {
1393                final long rxIdleCurrent = mContext.getResources().getInteger(
1394                        com.android.internal.R.integer.config_wifi_idle_receive_cur_ma);
1395                final long rxCurrent = mContext.getResources().getInteger(
1396                        com.android.internal.R.integer.config_wifi_active_rx_cur_ma);
1397                final long txCurrent = mContext.getResources().getInteger(
1398                        com.android.internal.R.integer.config_wifi_tx_cur_ma);
1399                final double voltage = mContext.getResources().getInteger(
1400                        com.android.internal.R.integer.config_wifi_operating_voltage_mv)
1401                        / 1000.0;
1402
1403                final long rxIdleTime = stats.on_time - stats.tx_time - stats.rx_time;
1404                final long[] txTimePerLevel;
1405                if (stats.tx_time_per_level != null) {
1406                    txTimePerLevel = new long[stats.tx_time_per_level.length];
1407                    for (int i = 0; i < txTimePerLevel.length; i++) {
1408                        txTimePerLevel[i] = stats.tx_time_per_level[i];
1409                        // TODO(b/27227497): Need to read the power consumed per level from config
1410                    }
1411                } else {
1412                    // This will happen if the HAL get link layer API returned null.
1413                    txTimePerLevel = new long[0];
1414                }
1415                final long energyUsed = (long)((stats.tx_time * txCurrent +
1416                        stats.rx_time * rxCurrent +
1417                        rxIdleTime * rxIdleCurrent) * voltage);
1418                if (VDBG || rxIdleTime < 0 || stats.on_time < 0 || stats.tx_time < 0 ||
1419                        stats.rx_time < 0 || energyUsed < 0) {
1420                    StringBuilder sb = new StringBuilder();
1421                    sb.append(" rxIdleCur=" + rxIdleCurrent);
1422                    sb.append(" rxCur=" + rxCurrent);
1423                    sb.append(" txCur=" + txCurrent);
1424                    sb.append(" voltage=" + voltage);
1425                    sb.append(" on_time=" + stats.on_time);
1426                    sb.append(" tx_time=" + stats.tx_time);
1427                    sb.append(" tx_time_per_level=" + Arrays.toString(txTimePerLevel));
1428                    sb.append(" rx_time=" + stats.rx_time);
1429                    sb.append(" rxIdleTime=" + rxIdleTime);
1430                    sb.append(" energy=" + energyUsed);
1431                    Log.d(TAG, " reportActivityInfo: " + sb.toString());
1432                }
1433
1434                // Convert the LinkLayerStats into EnergyActivity
1435                energyInfo = new WifiActivityEnergyInfo(mClock.getElapsedSinceBootMillis(),
1436                        WifiActivityEnergyInfo.STACK_STATE_STATE_IDLE, stats.tx_time,
1437                        txTimePerLevel, stats.rx_time, rxIdleTime, energyUsed);
1438            }
1439            if (energyInfo != null && energyInfo.isValid()) {
1440                return energyInfo;
1441            } else {
1442                return null;
1443            }
1444        } else {
1445            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1446            return null;
1447        }
1448    }
1449
1450    /**
1451     * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
1452     * @return the list of configured networks
1453     */
1454    @Override
1455    public ParceledListSlice<WifiConfiguration> getConfiguredNetworks() {
1456        enforceAccessPermission();
1457        mLog.trace("getConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
1458        if (mWifiStateMachineChannel != null) {
1459            List<WifiConfiguration> configs = mWifiStateMachine.syncGetConfiguredNetworks(
1460                    Binder.getCallingUid(), mWifiStateMachineChannel);
1461            if (configs != null) {
1462                return new ParceledListSlice<WifiConfiguration>(configs);
1463            }
1464        } else {
1465            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1466        }
1467        return null;
1468    }
1469
1470    /**
1471     * see {@link android.net.wifi.WifiManager#getPrivilegedConfiguredNetworks()}
1472     * @return the list of configured networks with real preSharedKey
1473     */
1474    @Override
1475    public ParceledListSlice<WifiConfiguration> getPrivilegedConfiguredNetworks() {
1476        enforceReadCredentialPermission();
1477        enforceAccessPermission();
1478        mLog.trace("getPrivilegedConfiguredNetworks uid=%").c(Binder.getCallingUid()).flush();
1479        if (mWifiStateMachineChannel != null) {
1480            List<WifiConfiguration> configs =
1481                    mWifiStateMachine.syncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel);
1482            if (configs != null) {
1483                return new ParceledListSlice<WifiConfiguration>(configs);
1484            }
1485        } else {
1486            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1487        }
1488        return null;
1489    }
1490
1491    /**
1492     * Returns a WifiConfiguration for a Passpoint network matching this ScanResult.
1493     *
1494     * @param scanResult scanResult that represents the BSSID
1495     * @return {@link WifiConfiguration} that matches this BSSID or null
1496     */
1497    @Override
1498    public WifiConfiguration getMatchingWifiConfig(ScanResult scanResult) {
1499        enforceAccessPermission();
1500        mLog.trace("getMatchingWifiConfig uid=%").c(Binder.getCallingUid()).flush();
1501        if (!mContext.getPackageManager().hasSystemFeature(
1502                PackageManager.FEATURE_WIFI_PASSPOINT)) {
1503            throw new UnsupportedOperationException("Passpoint not enabled");
1504        }
1505        return mWifiStateMachine.syncGetMatchingWifiConfig(scanResult, mWifiStateMachineChannel);
1506    }
1507
1508    /**
1509     * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
1510     * @return the supplicant-assigned identifier for the new or updated
1511     * network if the operation succeeds, or {@code -1} if it fails
1512     */
1513    @Override
1514    public int addOrUpdateNetwork(WifiConfiguration config) {
1515        enforceChangePermission();
1516        mLog.trace("addOrUpdateNetwork uid=%").c(Binder.getCallingUid()).flush();
1517
1518        // Previously, this API is overloaded for installing Passpoint profiles.  Now
1519        // that we have a dedicated API for doing it, redirect the call to the dedicated API.
1520        if (config.isPasspoint()) {
1521            PasspointConfiguration passpointConfig =
1522                    PasspointProvider.convertFromWifiConfig(config);
1523            if (passpointConfig.getCredential() == null) {
1524                Slog.e(TAG, "Missing credential for Passpoint profile");
1525                return -1;
1526            }
1527            // Copy over certificates and keys.
1528            passpointConfig.getCredential().setCaCertificate(
1529                    config.enterpriseConfig.getCaCertificate());
1530            passpointConfig.getCredential().setClientCertificateChain(
1531                    config.enterpriseConfig.getClientCertificateChain());
1532            passpointConfig.getCredential().setClientPrivateKey(
1533                    config.enterpriseConfig.getClientPrivateKey());
1534            if (!addOrUpdatePasspointConfiguration(passpointConfig)) {
1535                Slog.e(TAG, "Failed to add Passpoint profile");
1536                return -1;
1537            }
1538            // There is no network ID associated with a Passpoint profile.
1539            return 0;
1540        }
1541
1542        if (isValid(config)) {
1543            //TODO: pass the Uid the WifiStateMachine as a message parameter
1544            Slog.i("addOrUpdateNetwork", " uid = " + Integer.toString(Binder.getCallingUid())
1545                    + " SSID " + config.SSID
1546                    + " nid=" + Integer.toString(config.networkId));
1547            if (config.networkId == WifiConfiguration.INVALID_NETWORK_ID) {
1548                config.creatorUid = Binder.getCallingUid();
1549            } else {
1550                config.lastUpdateUid = Binder.getCallingUid();
1551            }
1552            if (mWifiStateMachineChannel != null) {
1553                return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
1554            } else {
1555                Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1556                return -1;
1557            }
1558        } else {
1559            Slog.e(TAG, "bad network configuration");
1560            return -1;
1561        }
1562    }
1563
1564    public static void verifyCert(X509Certificate caCert)
1565            throws GeneralSecurityException, IOException {
1566        CertificateFactory factory = CertificateFactory.getInstance("X.509");
1567        CertPathValidator validator =
1568                CertPathValidator.getInstance(CertPathValidator.getDefaultType());
1569        CertPath path = factory.generateCertPath(
1570                Arrays.asList(caCert));
1571        KeyStore ks = KeyStore.getInstance("AndroidCAStore");
1572        ks.load(null, null);
1573        PKIXParameters params = new PKIXParameters(ks);
1574        params.setRevocationEnabled(false);
1575        validator.validate(path, params);
1576    }
1577
1578    /**
1579     * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1580     * @param netId the integer that identifies the network configuration
1581     * to the supplicant
1582     * @return {@code true} if the operation succeeded
1583     */
1584    @Override
1585    public boolean removeNetwork(int netId) {
1586        enforceChangePermission();
1587        mLog.trace("removeNetwork uid=%").c(Binder.getCallingUid()).flush();
1588        // TODO Add private logging for netId b/33807876
1589        if (mWifiStateMachineChannel != null) {
1590            return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
1591        } else {
1592            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1593            return false;
1594        }
1595    }
1596
1597    /**
1598     * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1599     * @param netId the integer that identifies the network configuration
1600     * to the supplicant
1601     * @param disableOthers if true, disable all other networks.
1602     * @return {@code true} if the operation succeeded
1603     */
1604    @Override
1605    public boolean enableNetwork(int netId, boolean disableOthers) {
1606        enforceChangePermission();
1607        // TODO b/33807876 Log netId
1608        mLog.trace("enableNetwork uid=% disableOthers=%")
1609                .c(Binder.getCallingUid())
1610                .c(disableOthers).flush();
1611
1612        if (mWifiStateMachineChannel != null) {
1613            return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
1614                    disableOthers);
1615        } else {
1616            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1617            return false;
1618        }
1619    }
1620
1621    /**
1622     * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1623     * @param netId the integer that identifies the network configuration
1624     * to the supplicant
1625     * @return {@code true} if the operation succeeded
1626     */
1627    @Override
1628    public boolean disableNetwork(int netId) {
1629        enforceChangePermission();
1630        // TODO b/33807876 Log netId
1631        mLog.trace("disableNetwork uid=%").c(Binder.getCallingUid()).flush();
1632
1633        if (mWifiStateMachineChannel != null) {
1634            return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
1635        } else {
1636            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1637            return false;
1638        }
1639    }
1640
1641    /**
1642     * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1643     * @return the Wi-Fi information, contained in {@link WifiInfo}.
1644     */
1645    @Override
1646    public WifiInfo getConnectionInfo() {
1647        enforceAccessPermission();
1648        mLog.trace("getConnectionInfo uid=%").c(Binder.getCallingUid()).flush();
1649        /*
1650         * Make sure we have the latest information, by sending
1651         * a status request to the supplicant.
1652         */
1653        return mWifiStateMachine.syncRequestConnectionInfo();
1654    }
1655
1656    /**
1657     * Return the results of the most recent access point scan, in the form of
1658     * a list of {@link ScanResult} objects.
1659     * @return the list of results
1660     */
1661    @Override
1662    public List<ScanResult> getScanResults(String callingPackage) {
1663        enforceAccessPermission();
1664        int uid = Binder.getCallingUid();
1665        long ident = Binder.clearCallingIdentity();
1666        try {
1667            if (!mWifiPermissionsUtil.canAccessScanResults(callingPackage,
1668                      uid, Build.VERSION_CODES.M)) {
1669                return new ArrayList<ScanResult>();
1670            }
1671            if (mWifiScanner == null) {
1672                mWifiScanner = mWifiInjector.getWifiScanner();
1673            }
1674            return mWifiScanner.getSingleScanResults();
1675        } finally {
1676            Binder.restoreCallingIdentity(ident);
1677        }
1678    }
1679
1680    /**
1681     * Add or update a Passpoint configuration.
1682     *
1683     * @param config The Passpoint configuration to be added
1684     * @return true on success or false on failure
1685     */
1686    @Override
1687    public boolean addOrUpdatePasspointConfiguration(PasspointConfiguration config) {
1688        enforceChangePermission();
1689        mLog.trace("addorUpdatePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
1690        if (!mContext.getPackageManager().hasSystemFeature(
1691                PackageManager.FEATURE_WIFI_PASSPOINT)) {
1692            throw new UnsupportedOperationException("Passpoint not enabled");
1693        }
1694        return mWifiStateMachine.syncAddOrUpdatePasspointConfig(mWifiStateMachineChannel, config,
1695                Binder.getCallingUid());
1696    }
1697
1698    /**
1699     * Remove the Passpoint configuration identified by its FQDN (Fully Qualified Domain Name).
1700     *
1701     * @param fqdn The FQDN of the Passpoint configuration to be removed
1702     * @return true on success or false on failure
1703     */
1704    @Override
1705    public boolean removePasspointConfiguration(String fqdn) {
1706        enforceChangePermission();
1707        mLog.trace("removePasspointConfiguration uid=%").c(Binder.getCallingUid()).flush();
1708        if (!mContext.getPackageManager().hasSystemFeature(
1709                PackageManager.FEATURE_WIFI_PASSPOINT)) {
1710            throw new UnsupportedOperationException("Passpoint not enabled");
1711        }
1712        return mWifiStateMachine.syncRemovePasspointConfig(mWifiStateMachineChannel, fqdn);
1713    }
1714
1715    /**
1716     * Return the list of the installed Passpoint configurations.
1717     *
1718     * An empty list will be returned when no configuration is installed.
1719     *
1720     * @return A list of {@link PasspointConfiguration}
1721     */
1722    @Override
1723    public List<PasspointConfiguration> getPasspointConfigurations() {
1724        enforceAccessPermission();
1725        mLog.trace("getPasspointConfigurations uid=%").c(Binder.getCallingUid()).flush();
1726        if (!mContext.getPackageManager().hasSystemFeature(
1727                PackageManager.FEATURE_WIFI_PASSPOINT)) {
1728            throw new UnsupportedOperationException("Passpoint not enabled");
1729        }
1730        return mWifiStateMachine.syncGetPasspointConfigs(mWifiStateMachineChannel);
1731    }
1732
1733    /**
1734     * Query for a Hotspot 2.0 release 2 OSU icon
1735     * @param bssid The BSSID of the AP
1736     * @param fileName Icon file name
1737     */
1738    @Override
1739    public void queryPasspointIcon(long bssid, String fileName) {
1740        enforceAccessPermission();
1741        mLog.trace("queryPasspointIcon uid=%").c(Binder.getCallingUid()).flush();
1742        if (!mContext.getPackageManager().hasSystemFeature(
1743                PackageManager.FEATURE_WIFI_PASSPOINT)) {
1744            throw new UnsupportedOperationException("Passpoint not enabled");
1745        }
1746        mWifiStateMachine.syncQueryPasspointIcon(mWifiStateMachineChannel, bssid, fileName);
1747    }
1748
1749    /**
1750     * Match the currently associated network against the SP matching the given FQDN
1751     * @param fqdn FQDN of the SP
1752     * @return ordinal [HomeProvider, RoamingProvider, Incomplete, None, Declined]
1753     */
1754    @Override
1755    public int matchProviderWithCurrentNetwork(String fqdn) {
1756        mLog.trace("matchProviderWithCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
1757        return mWifiStateMachine.matchProviderWithCurrentNetwork(mWifiStateMachineChannel, fqdn);
1758    }
1759
1760    /**
1761     * Deauthenticate and set the re-authentication hold off time for the current network
1762     * @param holdoff hold off time in milliseconds
1763     * @param ess set if the hold off pertains to an ESS rather than a BSS
1764     */
1765    @Override
1766    public void deauthenticateNetwork(long holdoff, boolean ess) {
1767        mLog.trace("deauthenticateNetwork uid=%").c(Binder.getCallingUid()).flush();
1768        mWifiStateMachine.deauthenticateNetwork(mWifiStateMachineChannel, holdoff, ess);
1769    }
1770
1771    /**
1772     * Tell the supplicant to persist the current list of configured networks.
1773     * @return {@code true} if the operation succeeded
1774     *
1775     * TODO: deprecate this
1776     */
1777    @Override
1778    public boolean saveConfiguration() {
1779        enforceChangePermission();
1780        mLog.trace("saveConfiguration uid=%").c(Binder.getCallingUid()).flush();
1781        if (mWifiStateMachineChannel != null) {
1782            return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
1783        } else {
1784            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1785            return false;
1786        }
1787    }
1788
1789    /**
1790     * Set the country code
1791     * @param countryCode ISO 3166 country code.
1792     * @param persist {@code true} if the setting should be remembered.
1793     *
1794     * The persist behavior exists so that wifi can fall back to the last
1795     * persisted country code on a restart, when the locale information is
1796     * not available from telephony.
1797     */
1798    @Override
1799    public void setCountryCode(String countryCode, boolean persist) {
1800        Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
1801                " with persist set to " + persist);
1802        enforceConnectivityInternalPermission();
1803        mLog.trace("setCountryCode uid=%").c(Binder.getCallingUid()).flush();
1804        final long token = Binder.clearCallingIdentity();
1805        mCountryCode.setCountryCode(countryCode);
1806        Binder.restoreCallingIdentity(token);
1807    }
1808
1809     /**
1810     * Get the country code
1811     * @return Get the best choice country code for wifi, regardless of if it was set or
1812     * not.
1813     * Returns null when there is no country code available.
1814     */
1815    @Override
1816    public String getCountryCode() {
1817        enforceConnectivityInternalPermission();
1818        mLog.trace("getCountryCode uid=%").c(Binder.getCallingUid()).flush();
1819        String country = mCountryCode.getCountryCode();
1820        return country;
1821    }
1822
1823    @Override
1824    public boolean isDualBandSupported() {
1825        //TODO: Should move towards adding a driver API that checks at runtime
1826        mLog.trace("isDualBandSupported uid=%").c(Binder.getCallingUid()).flush();
1827        return mContext.getResources().getBoolean(
1828                com.android.internal.R.bool.config_wifi_dual_band_support);
1829    }
1830
1831    /**
1832     * Return the DHCP-assigned addresses from the last successful DHCP request,
1833     * if any.
1834     * @return the DHCP information
1835     * @deprecated
1836     */
1837    @Override
1838    @Deprecated
1839    public DhcpInfo getDhcpInfo() {
1840        enforceAccessPermission();
1841        mLog.trace("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush();
1842        DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
1843
1844        DhcpInfo info = new DhcpInfo();
1845
1846        if (dhcpResults.ipAddress != null &&
1847                dhcpResults.ipAddress.getAddress() instanceof Inet4Address) {
1848            info.ipAddress = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.ipAddress.getAddress());
1849        }
1850
1851        if (dhcpResults.gateway != null) {
1852            info.gateway = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.gateway);
1853        }
1854
1855        int dnsFound = 0;
1856        for (InetAddress dns : dhcpResults.dnsServers) {
1857            if (dns instanceof Inet4Address) {
1858                if (dnsFound == 0) {
1859                    info.dns1 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1860                } else {
1861                    info.dns2 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1862                }
1863                if (++dnsFound > 1) break;
1864            }
1865        }
1866        Inet4Address serverAddress = dhcpResults.serverAddress;
1867        if (serverAddress != null) {
1868            info.serverAddress = NetworkUtils.inetAddressToInt(serverAddress);
1869        }
1870        info.leaseDuration = dhcpResults.leaseDuration;
1871
1872        return info;
1873    }
1874
1875    /**
1876     * enable TDLS for the local NIC to remote NIC
1877     * The APPs don't know the remote MAC address to identify NIC though,
1878     * so we need to do additional work to find it from remote IP address
1879     */
1880
1881    class TdlsTaskParams {
1882        public String remoteIpAddress;
1883        public boolean enable;
1884    }
1885
1886    class TdlsTask extends AsyncTask<TdlsTaskParams, Integer, Integer> {
1887        @Override
1888        protected Integer doInBackground(TdlsTaskParams... params) {
1889
1890            // Retrieve parameters for the call
1891            TdlsTaskParams param = params[0];
1892            String remoteIpAddress = param.remoteIpAddress.trim();
1893            boolean enable = param.enable;
1894
1895            // Get MAC address of Remote IP
1896            String macAddress = null;
1897
1898            BufferedReader reader = null;
1899
1900            try {
1901                reader = new BufferedReader(new FileReader("/proc/net/arp"));
1902
1903                // Skip over the line bearing colum titles
1904                String line = reader.readLine();
1905
1906                while ((line = reader.readLine()) != null) {
1907                    String[] tokens = line.split("[ ]+");
1908                    if (tokens.length < 6) {
1909                        continue;
1910                    }
1911
1912                    // ARP column format is
1913                    // Address HWType HWAddress Flags Mask IFace
1914                    String ip = tokens[0];
1915                    String mac = tokens[3];
1916
1917                    if (remoteIpAddress.equals(ip)) {
1918                        macAddress = mac;
1919                        break;
1920                    }
1921                }
1922
1923                if (macAddress == null) {
1924                    Slog.w(TAG, "Did not find remoteAddress {" + remoteIpAddress + "} in " +
1925                            "/proc/net/arp");
1926                } else {
1927                    enableTdlsWithMacAddress(macAddress, enable);
1928                }
1929
1930            } catch (FileNotFoundException e) {
1931                Slog.e(TAG, "Could not open /proc/net/arp to lookup mac address");
1932            } catch (IOException e) {
1933                Slog.e(TAG, "Could not read /proc/net/arp to lookup mac address");
1934            } finally {
1935                try {
1936                    if (reader != null) {
1937                        reader.close();
1938                    }
1939                }
1940                catch (IOException e) {
1941                    // Do nothing
1942                }
1943            }
1944
1945            return 0;
1946        }
1947    }
1948
1949    @Override
1950    public void enableTdls(String remoteAddress, boolean enable) {
1951        if (remoteAddress == null) {
1952          throw new IllegalArgumentException("remoteAddress cannot be null");
1953        }
1954        mLog.trace("enableTdls uid=% enable=%").c(Binder.getCallingUid()).c(enable).flush();
1955        TdlsTaskParams params = new TdlsTaskParams();
1956        params.remoteIpAddress = remoteAddress;
1957        params.enable = enable;
1958        new TdlsTask().execute(params);
1959    }
1960
1961
1962    @Override
1963    public void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable) {
1964        mLog.trace("enableTdlsWithMacAddress uid=% enable=%")
1965                .c(Binder.getCallingUid())
1966                .c(enable)
1967                .flush();
1968        if (remoteMacAddress == null) {
1969          throw new IllegalArgumentException("remoteMacAddress cannot be null");
1970        }
1971
1972        mWifiStateMachine.enableTdls(remoteMacAddress, enable);
1973    }
1974
1975    /**
1976     * Get a reference to handler. This is used by a client to establish
1977     * an AsyncChannel communication with WifiService
1978     */
1979    @Override
1980    public Messenger getWifiServiceMessenger() {
1981        enforceAccessPermission();
1982        enforceChangePermission();
1983        mLog.trace("getWifiServiceMessenger uid=%").c(Binder.getCallingUid()).flush();
1984        return new Messenger(mClientHandler);
1985    }
1986
1987    /**
1988     * Disable an ephemeral network, i.e. network that is created thru a WiFi Scorer
1989     */
1990    @Override
1991    public void disableEphemeralNetwork(String SSID) {
1992        enforceAccessPermission();
1993        enforceChangePermission();
1994        mLog.trace("disableEphemeralNetwork uid=%").c(Binder.getCallingUid()).flush();
1995        mWifiStateMachine.disableEphemeralNetwork(SSID);
1996    }
1997
1998    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1999        @Override
2000        public void onReceive(Context context, Intent intent) {
2001            String action = intent.getAction();
2002            if (action.equals(Intent.ACTION_SCREEN_ON)) {
2003                mWifiController.sendMessage(CMD_SCREEN_ON);
2004            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
2005                mWifiController.sendMessage(CMD_USER_PRESENT);
2006            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
2007                mWifiController.sendMessage(CMD_SCREEN_OFF);
2008            } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
2009                int pluggedType = intent.getIntExtra("plugged", 0);
2010                mWifiController.sendMessage(CMD_BATTERY_CHANGED, pluggedType, 0, null);
2011            } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
2012                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
2013                        BluetoothAdapter.STATE_DISCONNECTED);
2014                mWifiStateMachine.sendBluetoothAdapterStateChange(state);
2015            } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
2016                boolean emergencyMode = intent.getBooleanExtra("phoneinECMState", false);
2017                mWifiController.sendMessage(CMD_EMERGENCY_MODE_CHANGED, emergencyMode ? 1 : 0, 0);
2018            } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALL_STATE_CHANGED)) {
2019                boolean inCall = intent.getBooleanExtra(PhoneConstants.PHONE_IN_EMERGENCY_CALL, false);
2020                mWifiController.sendMessage(CMD_EMERGENCY_CALL_STATE_CHANGED, inCall ? 1 : 0, 0);
2021            } else if (action.equals(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)) {
2022                handleIdleModeChanged();
2023            }
2024        }
2025    };
2026
2027    private boolean startConsentUi(String packageName,
2028            int callingUid, String intentAction) throws RemoteException {
2029        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
2030            return false;
2031        }
2032        try {
2033            // Validate the package only if we are going to use it
2034            ApplicationInfo applicationInfo = mContext.getPackageManager()
2035                    .getApplicationInfoAsUser(packageName,
2036                            PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2037                            UserHandle.getUserId(callingUid));
2038            if (applicationInfo.uid != callingUid) {
2039                throw new SecurityException("Package " + callingUid
2040                        + " not in uid " + callingUid);
2041            }
2042
2043            // Permission review mode, trigger a user prompt
2044            Intent intent = new Intent(intentAction);
2045            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2046                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2047            intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
2048            mContext.startActivity(intent);
2049            return true;
2050        } catch (PackageManager.NameNotFoundException e) {
2051            throw new RemoteException(e.getMessage());
2052        }
2053    }
2054
2055    /**
2056     * Observes settings changes to scan always mode.
2057     */
2058    private void registerForScanModeChange() {
2059        ContentObserver contentObserver = new ContentObserver(null) {
2060            @Override
2061            public void onChange(boolean selfChange) {
2062                mSettingsStore.handleWifiScanAlwaysAvailableToggled();
2063                mWifiController.sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);
2064            }
2065        };
2066        mFrameworkFacade.registerContentObserver(mContext,
2067                Settings.Global.getUriFor(Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE),
2068                false, contentObserver);
2069
2070    }
2071
2072    // Monitors settings changes related to background wifi scan throttling.
2073    private void registerForBackgroundThrottleChanges() {
2074        mFrameworkFacade.registerContentObserver(
2075                mContext,
2076                Settings.Global.getUriFor(
2077                        Settings.Global.WIFI_SCAN_BACKGROUND_THROTTLE_INTERVAL_MS),
2078                false,
2079                new ContentObserver(null) {
2080                    @Override
2081                    public void onChange(boolean selfChange) {
2082                        updateBackgroundThrottleInterval();
2083                    }
2084                }
2085        );
2086        mFrameworkFacade.registerContentObserver(
2087                mContext,
2088                Settings.Global.getUriFor(
2089                        Settings.Global.WIFI_SCAN_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
2090                false,
2091                new ContentObserver(null) {
2092                    @Override
2093                    public void onChange(boolean selfChange) {
2094                        updateBackgroundThrottlingWhitelist();
2095                    }
2096                }
2097        );
2098    }
2099
2100    private void updateBackgroundThrottleInterval() {
2101        mBackgroundThrottleInterval = mFrameworkFacade.getLongSetting(
2102                mContext,
2103                Settings.Global.WIFI_SCAN_BACKGROUND_THROTTLE_INTERVAL_MS,
2104                DEFAULT_SCAN_BACKGROUND_THROTTLE_INTERVAL_MS);
2105    }
2106
2107    private void updateBackgroundThrottlingWhitelist() {
2108        String setting = mFrameworkFacade.getStringSetting(
2109                mContext,
2110                Settings.Global.WIFI_SCAN_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
2111        mBackgroundThrottlePackageWhitelist.clear();
2112        if (setting != null) {
2113            mBackgroundThrottlePackageWhitelist.addAll(Arrays.asList(setting.split(",")));
2114        }
2115    }
2116
2117    private void registerForBroadcasts() {
2118        IntentFilter intentFilter = new IntentFilter();
2119        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
2120        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
2121        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
2122        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
2123        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
2124        intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
2125        intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
2126        intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
2127
2128        boolean trackEmergencyCallState = mContext.getResources().getBoolean(
2129                com.android.internal.R.bool.config_wifi_turn_off_during_emergency_call);
2130        if (trackEmergencyCallState) {
2131            intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALL_STATE_CHANGED);
2132        }
2133
2134        mContext.registerReceiver(mReceiver, intentFilter);
2135    }
2136
2137    private void registerForPackageOrUserRemoval() {
2138        IntentFilter intentFilter = new IntentFilter();
2139        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2140        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
2141        mContext.registerReceiverAsUser(new BroadcastReceiver() {
2142            @Override
2143            public void onReceive(Context context, Intent intent) {
2144                switch (intent.getAction()) {
2145                    case Intent.ACTION_PACKAGE_REMOVED: {
2146                        if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2147                            return;
2148                        }
2149                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2150                        Uri uri = intent.getData();
2151                        if (uid == -1 || uri == null) {
2152                            return;
2153                        }
2154                        String pkgName = uri.getSchemeSpecificPart();
2155                        mWifiStateMachine.removeAppConfigs(pkgName, uid);
2156                        break;
2157                    }
2158                    case Intent.ACTION_USER_REMOVED: {
2159                        int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
2160                        mWifiStateMachine.removeUserConfigs(userHandle);
2161                        break;
2162                    }
2163                }
2164            }
2165        }, UserHandle.ALL, intentFilter, null, null);
2166    }
2167
2168    @Override
2169    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2170            String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
2171        (new WifiShellCommand(mWifiStateMachine)).exec(this, in, out, err, args, callback,
2172                resultReceiver);
2173    }
2174
2175    @Override
2176    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2177        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2178                != PackageManager.PERMISSION_GRANTED) {
2179            pw.println("Permission Denial: can't dump WifiService from from pid="
2180                    + Binder.getCallingPid()
2181                    + ", uid=" + Binder.getCallingUid());
2182            return;
2183        }
2184        if (args != null && args.length > 0 && WifiMetrics.PROTO_DUMP_ARG.equals(args[0])) {
2185            // WifiMetrics proto bytes were requested. Dump only these.
2186            mWifiStateMachine.updateWifiMetrics();
2187            mWifiMetrics.dump(fd, pw, args);
2188        } else if (args != null && args.length > 0 && IpManager.DUMP_ARG.equals(args[0])) {
2189            // IpManager dump was requested. Pass it along and take no further action.
2190            String[] ipManagerArgs = new String[args.length - 1];
2191            System.arraycopy(args, 1, ipManagerArgs, 0, ipManagerArgs.length);
2192            mWifiStateMachine.dumpIpManager(fd, pw, ipManagerArgs);
2193        } else {
2194            pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
2195            pw.println("Stay-awake conditions: " +
2196                    mFacade.getIntegerSetting(mContext,
2197                            Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
2198            pw.println("mInIdleMode " + mInIdleMode);
2199            pw.println("mScanPending " + mScanPending);
2200            mWifiController.dump(fd, pw, args);
2201            mSettingsStore.dump(fd, pw, args);
2202            mNotificationController.dump(fd, pw, args);
2203            mTrafficPoller.dump(fd, pw, args);
2204            pw.println();
2205            pw.println("Locks held:");
2206            mWifiLockManager.dump(pw);
2207            pw.println();
2208            mWifiMulticastLockManager.dump(pw);
2209            pw.println();
2210            mWifiStateMachine.dump(fd, pw, args);
2211            pw.println();
2212            mWifiStateMachine.updateWifiMetrics();
2213            mWifiMetrics.dump(fd, pw, args);
2214            pw.println();
2215            mWifiBackupRestore.dump(fd, pw, args);
2216            pw.println();
2217        }
2218    }
2219
2220    @Override
2221    public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
2222        mLog.trace("acquireWifiLock uid=% lockMode=%")
2223                .c(Binder.getCallingUid())
2224                .c(lockMode).flush();
2225        if (mWifiLockManager.acquireWifiLock(lockMode, tag, binder, ws)) {
2226            mWifiController.sendMessage(CMD_LOCKS_CHANGED);
2227            return true;
2228        }
2229        return false;
2230    }
2231
2232    @Override
2233    public void updateWifiLockWorkSource(IBinder binder, WorkSource ws) {
2234        mLog.trace("updateWifiLockWorkSource uid=%").c(Binder.getCallingUid()).flush();
2235        mWifiLockManager.updateWifiLockWorkSource(binder, ws);
2236    }
2237
2238    @Override
2239    public boolean releaseWifiLock(IBinder binder) {
2240        mLog.trace("releaseWifiLock uid=%").c(Binder.getCallingUid()).flush();
2241        if (mWifiLockManager.releaseWifiLock(binder)) {
2242            mWifiController.sendMessage(CMD_LOCKS_CHANGED);
2243            return true;
2244        }
2245        return false;
2246    }
2247
2248    @Override
2249    public void initializeMulticastFiltering() {
2250        enforceMulticastChangePermission();
2251        mLog.trace("initializeMulticastFiltering uid=%").c(Binder.getCallingUid()).flush();
2252        mWifiMulticastLockManager.initializeFiltering();
2253    }
2254
2255    @Override
2256    public void acquireMulticastLock(IBinder binder, String tag) {
2257        enforceMulticastChangePermission();
2258        mLog.trace("acquireMulticastLock uid=%").c(Binder.getCallingUid()).flush();
2259        mWifiMulticastLockManager.acquireLock(binder, tag);
2260    }
2261
2262    @Override
2263    public void releaseMulticastLock() {
2264        enforceMulticastChangePermission();
2265        mLog.trace("releaseMulticastLock uid=%").c(Binder.getCallingUid()).flush();
2266        mWifiMulticastLockManager.releaseLock();
2267    }
2268
2269    @Override
2270    public boolean isMulticastEnabled() {
2271        enforceAccessPermission();
2272        mLog.trace("isMulticastEnabled uid=%").c(Binder.getCallingUid()).flush();
2273        return mWifiMulticastLockManager.isMulticastEnabled();
2274    }
2275
2276    @Override
2277    public void enableVerboseLogging(int verbose) {
2278        enforceAccessPermission();
2279        mLog.trace("enableVerboseLogging uid=% verbose=%")
2280                .c(Binder.getCallingUid())
2281                .c(verbose).flush();
2282        mFacade.setIntegerSetting(
2283                mContext, Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, verbose);
2284        enableVerboseLoggingInternal(verbose);
2285    }
2286
2287    void enableVerboseLoggingInternal(int verbose) {
2288        mWifiStateMachine.enableVerboseLogging(verbose);
2289        mWifiLockManager.enableVerboseLogging(verbose);
2290        mWifiMulticastLockManager.enableVerboseLogging(verbose);
2291        mWifiInjector.getWifiLastResortWatchdog().enableVerboseLogging(verbose);
2292        mWifiInjector.getWifiBackupRestore().enableVerboseLogging(verbose);
2293        LogcatLog.enableVerboseLogging(verbose);
2294    }
2295
2296    @Override
2297    public int getVerboseLoggingLevel() {
2298        enforceAccessPermission();
2299        mLog.trace("getVerboseLoggingLevel uid=%").c(Binder.getCallingUid()).flush();
2300        return mFacade.getIntegerSetting(
2301                mContext, Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, 0);
2302    }
2303
2304    @Override
2305    public void enableAggressiveHandover(int enabled) {
2306        enforceAccessPermission();
2307        mLog.trace("enableAggressiveHandover uid=% enabled=%")
2308            .c(Binder.getCallingUid())
2309            .c(enabled)
2310            .flush();
2311        mWifiStateMachine.enableAggressiveHandover(enabled);
2312    }
2313
2314    @Override
2315    public int getAggressiveHandover() {
2316        enforceAccessPermission();
2317        mLog.trace("getAggressiveHandover uid=%").c(Binder.getCallingUid()).flush();
2318        return mWifiStateMachine.getAggressiveHandover();
2319    }
2320
2321    @Override
2322    public void setAllowScansWithTraffic(int enabled) {
2323        enforceAccessPermission();
2324        mLog.trace("setAllowScansWithTraffic uid=% enabled=%")
2325                .c(Binder.getCallingUid())
2326                .c(enabled).flush();
2327        mWifiStateMachine.setAllowScansWithTraffic(enabled);
2328    }
2329
2330    @Override
2331    public int getAllowScansWithTraffic() {
2332        enforceAccessPermission();
2333        mLog.trace("getAllowScansWithTraffic uid=%").c(Binder.getCallingUid()).flush();
2334        return mWifiStateMachine.getAllowScansWithTraffic();
2335    }
2336
2337    @Override
2338    public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
2339        enforceChangePermission();
2340        mLog.trace("setEnableAutoJoinWhenAssociated uid=% enabled=%")
2341                .c(Binder.getCallingUid())
2342                .c(enabled).flush();
2343        return mWifiStateMachine.setEnableAutoJoinWhenAssociated(enabled);
2344    }
2345
2346    @Override
2347    public boolean getEnableAutoJoinWhenAssociated() {
2348        enforceAccessPermission();
2349        mLog.trace("getEnableAutoJoinWhenAssociated uid=%").c(Binder.getCallingUid()).flush();
2350        return mWifiStateMachine.getEnableAutoJoinWhenAssociated();
2351    }
2352
2353    /* Return the Wifi Connection statistics object */
2354    @Override
2355    public WifiConnectionStatistics getConnectionStatistics() {
2356        enforceAccessPermission();
2357        enforceReadCredentialPermission();
2358        mLog.trace("getConnectionStatistics uid=%").c(Binder.getCallingUid()).flush();
2359        if (mWifiStateMachineChannel != null) {
2360            return mWifiStateMachine.syncGetConnectionStatistics(mWifiStateMachineChannel);
2361        } else {
2362            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
2363            return null;
2364        }
2365    }
2366
2367    @Override
2368    public void factoryReset() {
2369        enforceConnectivityInternalPermission();
2370        mLog.trace("factoryReset uid=%").c(Binder.getCallingUid()).flush();
2371        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2372            return;
2373        }
2374
2375        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
2376            // Turn mobile hotspot off
2377            setWifiApEnabled(null, false);
2378        }
2379
2380        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI)) {
2381            // Enable wifi
2382            try {
2383                setWifiEnabled(mContext.getOpPackageName(), true);
2384            } catch (RemoteException e) {
2385                /* ignore - local call */
2386            }
2387            // Delete all Wifi SSIDs
2388            if (mWifiStateMachineChannel != null) {
2389                List<WifiConfiguration> networks = mWifiStateMachine.syncGetConfiguredNetworks(
2390                        Binder.getCallingUid(), mWifiStateMachineChannel);
2391                if (networks != null) {
2392                    for (WifiConfiguration config : networks) {
2393                        removeNetwork(config.networkId);
2394                    }
2395                    saveConfiguration();
2396                }
2397            }
2398        }
2399    }
2400
2401    /* private methods */
2402    static boolean logAndReturnFalse(String s) {
2403        Log.d(TAG, s);
2404        return false;
2405    }
2406
2407    public static boolean isValid(WifiConfiguration config) {
2408        String validity = checkValidity(config);
2409        return validity == null || logAndReturnFalse(validity);
2410    }
2411
2412    public static String checkValidity(WifiConfiguration config) {
2413        if (config.allowedKeyManagement == null)
2414            return "allowed kmgmt";
2415
2416        if (config.allowedKeyManagement.cardinality() > 1) {
2417            if (config.allowedKeyManagement.cardinality() != 2) {
2418                return "cardinality != 2";
2419            }
2420            if (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) {
2421                return "not WPA_EAP";
2422            }
2423            if ((!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X))
2424                    && (!config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))) {
2425                return "not PSK or 8021X";
2426            }
2427        }
2428        if (config.getIpAssignment() == IpConfiguration.IpAssignment.STATIC) {
2429            StaticIpConfiguration staticIpConf = config.getStaticIpConfiguration();
2430            if (staticIpConf == null) {
2431                return "null StaticIpConfiguration";
2432            }
2433            if (staticIpConf.ipAddress == null) {
2434                return "null static ip Address";
2435            }
2436        }
2437        return null;
2438    }
2439
2440    @Override
2441    public Network getCurrentNetwork() {
2442        enforceAccessPermission();
2443        mLog.trace("getCurrentNetwork uid=%").c(Binder.getCallingUid()).flush();
2444        return mWifiStateMachine.getCurrentNetwork();
2445    }
2446
2447    public static String toHexString(String s) {
2448        if (s == null) {
2449            return "null";
2450        }
2451        StringBuilder sb = new StringBuilder();
2452        sb.append('\'').append(s).append('\'');
2453        for (int n = 0; n < s.length(); n++) {
2454            sb.append(String.format(" %02x", s.charAt(n) & 0xffff));
2455        }
2456        return sb.toString();
2457    }
2458
2459    public void hideCertFromUnaffiliatedUsers(String alias) {
2460        mCertManager.hideCertFromUnaffiliatedUsers(alias);
2461    }
2462
2463    public String[] listClientCertsForCurrentUser() {
2464        return mCertManager.listClientCertsForCurrentUser();
2465    }
2466
2467    /**
2468     * Enable/disable WifiConnectivityManager at runtime
2469     *
2470     * @param enabled true-enable; false-disable
2471     */
2472    @Override
2473    public void enableWifiConnectivityManager(boolean enabled) {
2474        enforceConnectivityInternalPermission();
2475        mLog.trace("enableWifiConnectivityManager uid=% enabled=%")
2476            .c(Binder.getCallingUid())
2477            .c(enabled).flush();
2478        mWifiStateMachine.enableWifiConnectivityManager(enabled);
2479    }
2480
2481    /**
2482     * Retrieve the data to be backed to save the current state.
2483     *
2484     * @return  Raw byte stream of the data to be backed up.
2485     */
2486    @Override
2487    public byte[] retrieveBackupData() {
2488        enforceReadCredentialPermission();
2489        enforceAccessPermission();
2490        mLog.trace("retrieveBackupData uid=%").c(Binder.getCallingUid()).flush();
2491        if (mWifiStateMachineChannel == null) {
2492            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
2493            return null;
2494        }
2495
2496        Slog.d(TAG, "Retrieving backup data");
2497        List<WifiConfiguration> wifiConfigurations =
2498                mWifiStateMachine.syncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel);
2499        byte[] backupData =
2500                mWifiBackupRestore.retrieveBackupDataFromConfigurations(wifiConfigurations);
2501        Slog.d(TAG, "Retrieved backup data");
2502        return backupData;
2503    }
2504
2505    /**
2506     * Helper method to restore networks retrieved from backup data.
2507     *
2508     * @param configurations list of WifiConfiguration objects parsed from the backup data.
2509     */
2510    private void restoreNetworks(List<WifiConfiguration> configurations) {
2511        if (configurations == null) {
2512            Slog.e(TAG, "Backup data parse failed");
2513            return;
2514        }
2515        for (WifiConfiguration configuration : configurations) {
2516            int networkId = mWifiStateMachine.syncAddOrUpdateNetwork(
2517                    mWifiStateMachineChannel, configuration);
2518            if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
2519                Slog.e(TAG, "Restore network failed: " + configuration.configKey());
2520                continue;
2521            }
2522            // Enable all networks restored.
2523            mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, networkId, false);
2524        }
2525    }
2526
2527    /**
2528     * Restore state from the backed up data.
2529     *
2530     * @param data Raw byte stream of the backed up data.
2531     */
2532    @Override
2533    public void restoreBackupData(byte[] data) {
2534        enforceChangePermission();
2535        mLog.trace("restoreBackupData uid=%").c(Binder.getCallingUid()).flush();
2536        if (mWifiStateMachineChannel == null) {
2537            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
2538            return;
2539        }
2540
2541        Slog.d(TAG, "Restoring backup data");
2542        List<WifiConfiguration> wifiConfigurations =
2543                mWifiBackupRestore.retrieveConfigurationsFromBackupData(data);
2544        restoreNetworks(wifiConfigurations);
2545        Slog.d(TAG, "Restored backup data");
2546    }
2547
2548    /**
2549     * Restore state from the older supplicant back up data.
2550     * The old backup data was essentially a backup of wpa_supplicant.conf & ipconfig.txt file.
2551     *
2552     * @param supplicantData Raw byte stream of wpa_supplicant.conf
2553     * @param ipConfigData Raw byte stream of ipconfig.txt
2554     */
2555    public void restoreSupplicantBackupData(byte[] supplicantData, byte[] ipConfigData) {
2556        enforceChangePermission();
2557        mLog.trace("restoreSupplicantBackupData uid=%").c(Binder.getCallingUid()).flush();
2558        if (mWifiStateMachineChannel == null) {
2559            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
2560            return;
2561        }
2562
2563        Slog.d(TAG, "Restoring supplicant backup data");
2564        List<WifiConfiguration> wifiConfigurations =
2565                mWifiBackupRestore.retrieveConfigurationsFromSupplicantBackupData(
2566                        supplicantData, ipConfigData);
2567        restoreNetworks(wifiConfigurations);
2568        Slog.d(TAG, "Restored supplicant backup data");
2569    }
2570}
2571