WifiInjector.java revision 9e83c3b65710cef6e04015565974750ee67200f1
1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.wifi;
18
19import android.app.ActivityManager;
20import android.content.Context;
21import android.net.NetworkKey;
22import android.net.NetworkScoreManager;
23import android.net.wifi.IApInterface;
24import android.net.wifi.IWifiScanner;
25import android.net.wifi.IWificond;
26import android.net.wifi.WifiConfiguration;
27import android.net.wifi.WifiInfo;
28import android.net.wifi.WifiNetworkScoreCache;
29import android.net.wifi.WifiScanner;
30import android.os.BatteryStats;
31import android.os.HandlerThread;
32import android.os.IBinder;
33import android.os.INetworkManagementService;
34import android.os.Looper;
35import android.os.ServiceManager;
36import android.os.SystemProperties;
37import android.os.UserManager;
38import android.security.KeyStore;
39import android.telephony.TelephonyManager;
40import android.util.LocalLog;
41
42import com.android.internal.R;
43import com.android.internal.app.IBatteryStats;
44import com.android.server.am.BatteryStatsService;
45import com.android.server.net.DelayedDiskWrite;
46import com.android.server.net.IpConfigStore;
47import com.android.server.wifi.hotspot2.LegacyPasspointConfigParser;
48import com.android.server.wifi.hotspot2.PasspointManager;
49import com.android.server.wifi.hotspot2.PasspointNetworkEvaluator;
50import com.android.server.wifi.hotspot2.PasspointObjectFactory;
51import com.android.server.wifi.p2p.SupplicantP2pIfaceHal;
52import com.android.server.wifi.p2p.WifiP2pMonitor;
53import com.android.server.wifi.p2p.WifiP2pNative;
54import com.android.server.wifi.util.WifiPermissionsUtil;
55import com.android.server.wifi.util.WifiPermissionsWrapper;
56
57/**
58 *  WiFi dependency injector. To be used for accessing various WiFi class instances and as a
59 *  handle for mock injection.
60 *
61 *  Some WiFi class instances currently depend on having a Looper from a HandlerThread that has
62 *  been started. To accommodate this, we have a two-phased approach to initialize and retrieve
63 *  an instance of the WifiInjector.
64 */
65public class WifiInjector {
66    private static final String BOOT_DEFAULT_WIFI_COUNTRY_CODE = "ro.boot.wificountrycode";
67    private static final String WIFICOND_SERVICE_NAME = "wificond";
68
69    static WifiInjector sWifiInjector = null;
70
71    private final Context mContext;
72    private final FrameworkFacade mFrameworkFacade = new FrameworkFacade();
73    private final HandlerThread mWifiServiceHandlerThread;
74    private final HandlerThread mWifiStateMachineHandlerThread;
75    private final WifiTrafficPoller mTrafficPoller;
76    private final WifiCountryCode mCountryCode;
77    private final BackupManagerProxy mBackupManagerProxy = new BackupManagerProxy();
78    private final WifiApConfigStore mWifiApConfigStore;
79    private final WifiNative mWifiNative;
80    private final WifiMonitor mWifiMonitor;
81    private final WifiP2pNative mWifiP2pNative;
82    private final WifiP2pMonitor mWifiP2pMonitor;
83    private final SupplicantStaIfaceHal mSupplicantStaIfaceHal;
84    private final SupplicantP2pIfaceHal mSupplicantP2pIfaceHal;
85    private final WifiVendorHal mWifiVendorHal;
86    private final WifiStateMachine mWifiStateMachine;
87    private final WifiSettingsStore mSettingsStore;
88    private final WifiCertManager mCertManager;
89    private final WifiNotificationController mNotificationController;
90    private final WifiLockManager mLockManager;
91    private final WifiController mWifiController;
92    private final WificondControl mWificondControl;
93    private final Clock mClock = new Clock();
94    private final WifiMetrics mWifiMetrics;
95    private final WifiLastResortWatchdog mWifiLastResortWatchdog;
96    private final PropertyService mPropertyService = new SystemPropertyService();
97    private final BuildProperties mBuildProperties = new SystemBuildProperties();
98    private final KeyStore mKeyStore = KeyStore.getInstance();
99    private final WifiBackupRestore mWifiBackupRestore;
100    private final WifiMulticastLockManager mWifiMulticastLockManager;
101    private final WifiConfigStore mWifiConfigStore;
102    private final WifiKeyStore mWifiKeyStore;
103    private final WifiNetworkHistory mWifiNetworkHistory;
104    private final IpConfigStore mIpConfigStore;
105    private final WifiConfigStoreLegacy mWifiConfigStoreLegacy;
106    private final WifiConfigManager mWifiConfigManager;
107    private final WifiConnectivityHelper mWifiConnectivityHelper;
108    private final LocalLog mConnectivityLocalLog;
109    private final WifiNetworkSelector mWifiNetworkSelector;
110    private final SavedNetworkEvaluator mSavedNetworkEvaluator;
111    private final PasspointNetworkEvaluator mPasspointNetworkEvaluator;
112    private final ScoredNetworkEvaluator mScoredNetworkEvaluator;
113    private final WifiNetworkScoreCache mWifiNetworkScoreCache;
114    private final NetworkScoreManager mNetworkScoreManager;
115    private WifiScanner mWifiScanner;
116    private final WifiPermissionsWrapper mWifiPermissionsWrapper;
117    private final WifiPermissionsUtil mWifiPermissionsUtil;
118    private final PasspointManager mPasspointManager;
119    private final SIMAccessor mSimAccessor;
120    private HandlerThread mWifiAwareHandlerThread;
121    private HalDeviceManager mHalDeviceManager;
122    private final IBatteryStats mBatteryStats;
123    private final WifiStateTracker mWifiStateTracker;
124    private final Runtime mJavaRuntime;
125    private final SelfRecovery mSelfRecovery;
126
127    private final boolean mUseRealLogger;
128
129    public WifiInjector(Context context) {
130        if (context == null) {
131            throw new IllegalStateException(
132                    "WifiInjector should not be initialized with a null Context.");
133        }
134
135        if (sWifiInjector != null) {
136            throw new IllegalStateException(
137                    "WifiInjector was already created, use getInstance instead.");
138        }
139
140        sWifiInjector = this;
141
142        mContext = context;
143        mUseRealLogger = mContext.getResources().getBoolean(
144                R.bool.config_wifi_enable_wifi_firmware_debugging);
145        mSettingsStore = new WifiSettingsStore(mContext);
146        mWifiPermissionsWrapper = new WifiPermissionsWrapper(mContext);
147        mNetworkScoreManager = mContext.getSystemService(NetworkScoreManager.class);
148        mWifiNetworkScoreCache = new WifiNetworkScoreCache(mContext);
149        mNetworkScoreManager.registerNetworkScoreCache(NetworkKey.TYPE_WIFI,
150                mWifiNetworkScoreCache, NetworkScoreManager.CACHE_FILTER_NONE);
151        mWifiPermissionsUtil = new WifiPermissionsUtil(mWifiPermissionsWrapper, mContext,
152                mSettingsStore, UserManager.get(mContext), mNetworkScoreManager, this);
153        mWifiBackupRestore = new WifiBackupRestore(mWifiPermissionsUtil);
154        mBatteryStats = IBatteryStats.Stub.asInterface(mFrameworkFacade.getService(
155                BatteryStats.SERVICE_NAME));
156        mWifiStateTracker = new WifiStateTracker(mBatteryStats);
157        // Now create and start handler threads
158        mWifiServiceHandlerThread = new HandlerThread("WifiService");
159        mWifiServiceHandlerThread.start();
160        mWifiStateMachineHandlerThread = new HandlerThread("WifiStateMachine");
161        mWifiStateMachineHandlerThread.start();
162        Looper wifiStateMachineLooper = mWifiStateMachineHandlerThread.getLooper();
163        mWifiMetrics = new WifiMetrics(mClock, wifiStateMachineLooper);
164        // Modules interacting with Native.
165        mWifiMonitor = new WifiMonitor(this);
166        mHalDeviceManager = new HalDeviceManager();
167        mWifiVendorHal =
168                new WifiVendorHal(mHalDeviceManager, mWifiStateMachineHandlerThread.getLooper());
169        mSupplicantStaIfaceHal = new SupplicantStaIfaceHal(mContext, mWifiMonitor);
170        mWificondControl = new WificondControl(this, mWifiMonitor);
171        mWifiNative = new WifiNative(SystemProperties.get("wifi.interface", "wlan0"),
172                mWifiVendorHal, mSupplicantStaIfaceHal, mWificondControl);
173        mWifiP2pMonitor = new WifiP2pMonitor(this);
174        mSupplicantP2pIfaceHal = new SupplicantP2pIfaceHal(mWifiP2pMonitor);
175        mWifiP2pNative = new WifiP2pNative(SystemProperties.get("wifi.direct.interface", "p2p0"),
176                mSupplicantP2pIfaceHal);
177
178        // Now get instances of all the objects that depend on the HandlerThreads
179        mTrafficPoller =  new WifiTrafficPoller(mContext, mWifiServiceHandlerThread.getLooper(),
180                mWifiNative.getInterfaceName());
181        mCountryCode = new WifiCountryCode(mWifiNative,
182                SystemProperties.get(BOOT_DEFAULT_WIFI_COUNTRY_CODE),
183                mContext.getResources()
184                        .getBoolean(R.bool.config_wifi_revert_country_code_on_cellular_loss));
185        mWifiApConfigStore = new WifiApConfigStore(mContext, mBackupManagerProxy);
186
187        // WifiConfigManager/Store objects and their dependencies.
188        // New config store
189        mWifiKeyStore = new WifiKeyStore(mKeyStore);
190        mWifiConfigStore = new WifiConfigStore(
191                mContext, wifiStateMachineLooper, mClock,
192                WifiConfigStore.createSharedFile());
193        // Legacy config store
194        DelayedDiskWrite writer = new DelayedDiskWrite();
195        mWifiNetworkHistory = new WifiNetworkHistory(mContext, writer);
196        mIpConfigStore = new IpConfigStore(writer);
197        mWifiConfigStoreLegacy = new WifiConfigStoreLegacy(
198                mWifiNetworkHistory, mWifiNative, mIpConfigStore,
199                new LegacyPasspointConfigParser());
200        // Config Manager
201        mWifiConfigManager = new WifiConfigManager(mContext, mClock,
202                UserManager.get(mContext), TelephonyManager.from(mContext),
203                mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy, mWifiPermissionsUtil,
204                mWifiPermissionsWrapper, new NetworkListStoreData(),
205                new DeletedEphemeralSsidsStoreData());
206        mWifiConnectivityHelper = new WifiConnectivityHelper(mWifiNative);
207        mConnectivityLocalLog = new LocalLog(ActivityManager.isLowRamDeviceStatic() ? 256 : 512);
208        mWifiNetworkSelector = new WifiNetworkSelector(mContext, mWifiConfigManager, mClock,
209                mConnectivityLocalLog);
210        mSavedNetworkEvaluator = new SavedNetworkEvaluator(mContext,
211                mWifiConfigManager, mClock, mConnectivityLocalLog, mWifiConnectivityHelper);
212        mScoredNetworkEvaluator = new ScoredNetworkEvaluator(context, wifiStateMachineLooper,
213                mFrameworkFacade, mNetworkScoreManager, mWifiConfigManager, mConnectivityLocalLog,
214                mWifiNetworkScoreCache);
215        mSimAccessor = new SIMAccessor(mContext);
216        mPasspointManager = new PasspointManager(mContext, mWifiNative, mWifiKeyStore, mClock,
217                mSimAccessor, new PasspointObjectFactory(), mWifiConfigManager, mWifiConfigStore);
218        mPasspointNetworkEvaluator = new PasspointNetworkEvaluator(
219                mPasspointManager, mWifiConfigManager, mConnectivityLocalLog);
220        // mWifiStateMachine has an implicit dependency on mJavaRuntime due to WifiDiagnostics.
221        mJavaRuntime = Runtime.getRuntime();
222        mWifiStateMachine = new WifiStateMachine(mContext, mFrameworkFacade,
223                wifiStateMachineLooper, UserManager.get(mContext),
224                this, mBackupManagerProxy, mCountryCode, mWifiNative);
225        mCertManager = new WifiCertManager(mContext);
226        mNotificationController = new WifiNotificationController(mContext,
227                mWifiServiceHandlerThread.getLooper(), mFrameworkFacade, null, this);
228        mLockManager = new WifiLockManager(mContext, BatteryStatsService.getService());
229        mWifiController = new WifiController(mContext, mWifiStateMachine, mSettingsStore,
230                mLockManager, mWifiServiceHandlerThread.getLooper(), mFrameworkFacade);
231        mSelfRecovery = new SelfRecovery(mWifiController);
232        mWifiLastResortWatchdog = new WifiLastResortWatchdog(mSelfRecovery, mWifiMetrics);
233        mWifiMulticastLockManager = new WifiMulticastLockManager(mWifiStateMachine,
234                BatteryStatsService.getService());
235    }
236
237    /**
238     *  Obtain an instance of the WifiInjector class.
239     *
240     *  This is the generic method to get an instance of the class. The first instance should be
241     *  retrieved using the getInstanceWithContext method.
242     */
243    public static WifiInjector getInstance() {
244        if (sWifiInjector == null) {
245            throw new IllegalStateException(
246                    "Attempted to retrieve a WifiInjector instance before constructor was called.");
247        }
248        return sWifiInjector;
249    }
250
251    public UserManager getUserManager() {
252        return UserManager.get(mContext);
253    }
254
255    public WifiMetrics getWifiMetrics() {
256        return mWifiMetrics;
257    }
258
259    public SupplicantStaIfaceHal getSupplicantStaIfaceHal() {
260        return mSupplicantStaIfaceHal;
261    }
262
263    public BackupManagerProxy getBackupManagerProxy() {
264        return mBackupManagerProxy;
265    }
266
267    public FrameworkFacade getFrameworkFacade() {
268        return mFrameworkFacade;
269    }
270
271    public HandlerThread getWifiServiceHandlerThread() {
272        return mWifiServiceHandlerThread;
273    }
274
275    public HandlerThread getWifiStateMachineHandlerThread() {
276        return mWifiStateMachineHandlerThread;
277    }
278
279    public WifiTrafficPoller getWifiTrafficPoller() {
280        return mTrafficPoller;
281    }
282
283    public WifiCountryCode getWifiCountryCode() {
284        return mCountryCode;
285    }
286
287    public WifiApConfigStore getWifiApConfigStore() {
288        return mWifiApConfigStore;
289    }
290
291    public WifiStateMachine getWifiStateMachine() {
292        return mWifiStateMachine;
293    }
294
295    public WifiSettingsStore getWifiSettingsStore() {
296        return mSettingsStore;
297    }
298
299    public WifiCertManager getWifiCertManager() {
300        return mCertManager;
301    }
302
303    public WifiNotificationController getWifiNotificationController() {
304        return mNotificationController;
305    }
306
307    public WifiLockManager getWifiLockManager() {
308        return mLockManager;
309    }
310
311    public WifiController getWifiController() {
312        return mWifiController;
313    }
314
315    public WifiLastResortWatchdog getWifiLastResortWatchdog() {
316        return mWifiLastResortWatchdog;
317    }
318
319    public Clock getClock() {
320        return mClock;
321    }
322
323    public PropertyService getPropertyService() {
324        return mPropertyService;
325    }
326
327    public BuildProperties getBuildProperties() {
328        return mBuildProperties;
329    }
330
331    public KeyStore getKeyStore() {
332        return mKeyStore;
333    }
334
335    public WifiBackupRestore getWifiBackupRestore() {
336        return mWifiBackupRestore;
337    }
338
339    public WifiMulticastLockManager getWifiMulticastLockManager() {
340        return mWifiMulticastLockManager;
341    }
342
343    public WifiConfigManager getWifiConfigManager() {
344        return mWifiConfigManager;
345    }
346
347    public PasspointManager getPasspointManager() {
348        return mPasspointManager;
349    }
350
351    public TelephonyManager makeTelephonyManager() {
352        // may not be available when WiFi starts
353        return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
354    }
355
356    public WifiStateTracker getWifiStateTracker() {
357        return mWifiStateTracker;
358    }
359
360    public IWificond makeWificond() {
361        // We depend on being able to refresh our binder in WifiStateMachine, so don't cache it.
362        IBinder binder = ServiceManager.getService(WIFICOND_SERVICE_NAME);
363        return IWificond.Stub.asInterface(binder);
364    }
365
366    /**
367     * Create a SoftApManager.
368     * @param nmService NetworkManagementService allowing SoftApManager to listen for interface
369     * changes
370     * @param listener listener for SoftApManager
371     * @param apInterface network interface to start hostapd against
372     * @param config softAp WifiConfiguration
373     * @return an instance of SoftApManager
374     */
375    public SoftApManager makeSoftApManager(INetworkManagementService nmService,
376                                           SoftApManager.Listener listener,
377                                           IApInterface apInterface,
378                                           WifiConfiguration config) {
379        return new SoftApManager(mWifiServiceHandlerThread.getLooper(),
380                                 mWifiNative, mCountryCode.getCountryCode(),
381                                 listener, apInterface, nmService,
382                                 mWifiApConfigStore, config, mWifiMetrics);
383    }
384
385    /**
386     * Create a WifiLog instance.
387     * @param tag module name to include in all log messages
388     */
389    public WifiLog makeLog(String tag) {
390        return new LogcatLog(tag);
391    }
392
393    public BaseWifiDiagnostics makeWifiDiagnostics(WifiNative wifiNative) {
394        if (mUseRealLogger) {
395            return new WifiDiagnostics(
396                    mContext, this, mWifiStateMachine, wifiNative, mBuildProperties,
397                    new LastMileLogger(this));
398        } else {
399            return new BaseWifiDiagnostics(wifiNative);
400        }
401    }
402
403    /**
404     * Obtain an instance of WifiScanner.
405     * If it was not already created, then obtain an instance.  Note, this must be done lazily since
406     * WifiScannerService is separate and created later.
407     */
408    public synchronized WifiScanner getWifiScanner() {
409        if (mWifiScanner == null) {
410            mWifiScanner = new WifiScanner(mContext,
411                    IWifiScanner.Stub.asInterface(ServiceManager.getService(
412                            Context.WIFI_SCANNING_SERVICE)),
413                    mWifiStateMachineHandlerThread.getLooper());
414        }
415        return mWifiScanner;
416    }
417
418    /**
419     * Obtain a new instance of WifiConnectivityManager.
420     *
421     * Create and return a new WifiConnectivityManager.
422     * @param wifiInfo WifiInfo object for updating wifi state.
423     * @param hasConnectionRequests boolean indicating if WifiConnectivityManager to start
424     * immediately based on connection requests.
425     */
426    public WifiConnectivityManager makeWifiConnectivityManager(WifiInfo wifiInfo,
427                                                               boolean hasConnectionRequests) {
428        return new WifiConnectivityManager(mContext, mWifiStateMachine, getWifiScanner(),
429                mWifiConfigManager, wifiInfo, mWifiNetworkSelector, mWifiConnectivityHelper,
430                mWifiLastResortWatchdog, mWifiMetrics, mWifiStateMachineHandlerThread.getLooper(),
431                mClock, mConnectivityLocalLog, hasConnectionRequests, mFrameworkFacade,
432                mSavedNetworkEvaluator, mScoredNetworkEvaluator, mPasspointNetworkEvaluator);
433    }
434
435    public WifiPermissionsUtil getWifiPermissionsUtil() {
436        return mWifiPermissionsUtil;
437    }
438
439    public WifiPermissionsWrapper getWifiPermissionsWrapper() {
440        return mWifiPermissionsWrapper;
441    }
442
443    /**
444     * Returns a singleton instance of a HandlerThread for injection. Uses lazy initialization.
445     *
446     * TODO: share worker thread with other Wi-Fi handlers (b/27924886)
447     */
448    public HandlerThread getWifiAwareHandlerThread() {
449        if (mWifiAwareHandlerThread == null) { // lazy initialization
450            mWifiAwareHandlerThread = new HandlerThread("wifiAwareService");
451            mWifiAwareHandlerThread.start();
452        }
453        return mWifiAwareHandlerThread;
454    }
455
456    /**
457     * Returns a single instance of HalDeviceManager for injection.
458     */
459    public HalDeviceManager getHalDeviceManager() {
460        return mHalDeviceManager;
461    }
462
463    public Runtime getJavaRuntime() {
464        return mJavaRuntime;
465    }
466
467    public WifiNative getWifiNative() {
468        return mWifiNative;
469    }
470
471    public WifiMonitor getWifiMonitor() {
472        return mWifiMonitor;
473    }
474
475    public WifiP2pNative getWifiP2pNative() {
476        return mWifiP2pNative;
477    }
478
479    public WifiP2pMonitor getWifiP2pMonitor() {
480        return mWifiP2pMonitor;
481    }
482
483    public SelfRecovery getSelfRecovery() {
484        return mSelfRecovery;
485    }
486}
487