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