WifiInjector.java revision 834fc3a1535214ec38c2186b50f0a20975c5f73c
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 =
156                new WifiVendorHal(mHalDeviceManager, mWifiStateMachineHandlerThread.getLooper());
157        mSupplicantStaIfaceHal = new SupplicantStaIfaceHal(mContext, mWifiMonitor);
158        mWificondControl = new WificondControl(this, mWifiMonitor);
159        mWifiNative = new WifiNative(SystemProperties.get("wifi.interface", "wlan0"),
160                mWifiVendorHal, mSupplicantStaIfaceHal, mWificondControl);
161        mWifiP2pMonitor = new WifiP2pMonitor(this);
162        mSupplicantP2pIfaceHal = new SupplicantP2pIfaceHal(mWifiP2pMonitor);
163        mWifiP2pNative = new WifiP2pNative(SystemProperties.get("wifi.direct.interface", "p2p0"),
164                mSupplicantP2pIfaceHal);
165
166        // Now get instances of all the objects that depend on the HandlerThreads
167        mTrafficPoller =  new WifiTrafficPoller(mContext, mWifiServiceHandlerThread.getLooper(),
168                mWifiNative.getInterfaceName());
169        mCountryCode = new WifiCountryCode(mWifiNative,
170                SystemProperties.get(BOOT_DEFAULT_WIFI_COUNTRY_CODE),
171                mContext.getResources()
172                        .getBoolean(R.bool.config_wifi_revert_country_code_on_cellular_loss));
173        mWifiApConfigStore = new WifiApConfigStore(mContext, mBackupManagerProxy);
174
175        // WifiConfigManager/Store objects and their dependencies.
176        // New config store
177        mWifiKeyStore = new WifiKeyStore(mKeyStore);
178        mWifiConfigStore = new WifiConfigStore(
179                mContext, wifiStateMachineLooper, mClock,
180                WifiConfigStore.createSharedFile());
181        // Legacy config store
182        DelayedDiskWrite writer = new DelayedDiskWrite();
183        mWifiNetworkHistory = new WifiNetworkHistory(mContext, writer);
184        mIpConfigStore = new IpConfigStore(writer);
185        mWifiConfigStoreLegacy = new WifiConfigStoreLegacy(
186                mWifiNetworkHistory, mWifiNative, mIpConfigStore,
187                new LegacyPasspointConfigParser());
188        // Config Manager
189        mWifiConfigManager = new WifiConfigManager(mContext, mClock,
190                UserManager.get(mContext), TelephonyManager.from(mContext),
191                mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy, mWifiPermissionsUtil,
192                mWifiPermissionsWrapper, new NetworkListStoreData(),
193                new DeletedEphemeralSsidsStoreData());
194        mWifiNetworkSelector = new WifiNetworkSelector(mContext, mWifiConfigManager, mClock);
195        LocalLog localLog = mWifiNetworkSelector.getLocalLog();
196        mSavedNetworkEvaluator = new SavedNetworkEvaluator(mContext,
197                mWifiConfigManager, mClock, localLog, wifiStateMachineLooper, mFrameworkFacade);
198        mRecommendedNetworkEvaluator = new RecommendedNetworkEvaluator(context,
199                context.getContentResolver(), wifiStateMachineLooper, mFrameworkFacade,
200                mNetworkScoreManager, mWifiConfigManager, localLog);
201        mSimAccessor = new SIMAccessor(mContext);
202        mPasspointManager = new PasspointManager(mContext, mWifiNative, mWifiKeyStore, mClock,
203                mSimAccessor, new PasspointObjectFactory(), mWifiConfigManager, mWifiConfigStore);
204        mPasspointNetworkEvaluator = new PasspointNetworkEvaluator(
205                mPasspointManager, mWifiConfigManager, localLog);
206        // mWifiStateMachine has an implicit dependency on mJavaRuntime due to WifiDiagnostics.
207        mJavaRuntime = Runtime.getRuntime();
208        mWifiStateMachine = new WifiStateMachine(mContext, mFrameworkFacade,
209                wifiStateMachineLooper, UserManager.get(mContext),
210                this, mBackupManagerProxy, mCountryCode, mWifiNative);
211        mCertManager = new WifiCertManager(mContext);
212        mLockManager = new WifiLockManager(mContext, BatteryStatsService.getService());
213        mWifiController = new WifiController(mContext, mWifiStateMachine, mSettingsStore,
214                mLockManager, mWifiServiceHandlerThread.getLooper(), mFrameworkFacade);
215        mWifiLastResortWatchdog = new WifiLastResortWatchdog(mWifiController, mWifiMetrics);
216        mWifiMulticastLockManager = new WifiMulticastLockManager(mWifiStateMachine,
217                BatteryStatsService.getService());
218    }
219
220    /**
221     *  Obtain an instance of the WifiInjector class.
222     *
223     *  This is the generic method to get an instance of the class. The first instance should be
224     *  retrieved using the getInstanceWithContext method.
225     */
226    public static WifiInjector getInstance() {
227        if (sWifiInjector == null) {
228            throw new IllegalStateException(
229                    "Attempted to retrieve a WifiInjector instance before constructor was called.");
230        }
231        return sWifiInjector;
232    }
233
234    public UserManager getUserManager() {
235        return UserManager.get(mContext);
236    }
237
238    public WifiMetrics getWifiMetrics() {
239        return mWifiMetrics;
240    }
241
242    public SupplicantStaIfaceHal getSupplicantStaIfaceHal() {
243        return mSupplicantStaIfaceHal;
244    }
245
246    public BackupManagerProxy getBackupManagerProxy() {
247        return mBackupManagerProxy;
248    }
249
250    public FrameworkFacade getFrameworkFacade() {
251        return mFrameworkFacade;
252    }
253
254    public HandlerThread getWifiServiceHandlerThread() {
255        return mWifiServiceHandlerThread;
256    }
257
258    public HandlerThread getWifiStateMachineHandlerThread() {
259        return mWifiStateMachineHandlerThread;
260    }
261
262    public WifiTrafficPoller getWifiTrafficPoller() {
263        return mTrafficPoller;
264    }
265
266    public WifiCountryCode getWifiCountryCode() {
267        return mCountryCode;
268    }
269
270    public WifiApConfigStore getWifiApConfigStore() {
271        return mWifiApConfigStore;
272    }
273
274    public WifiStateMachine getWifiStateMachine() {
275        return mWifiStateMachine;
276    }
277
278    public WifiSettingsStore getWifiSettingsStore() {
279        return mSettingsStore;
280    }
281
282    public WifiCertManager getWifiCertManager() {
283        return mCertManager;
284    }
285
286    public WifiLockManager getWifiLockManager() {
287        return mLockManager;
288    }
289
290    public WifiController getWifiController() {
291        return mWifiController;
292    }
293
294    public WifiLastResortWatchdog getWifiLastResortWatchdog() {
295        return mWifiLastResortWatchdog;
296    }
297
298    public Clock getClock() {
299        return mClock;
300    }
301
302    public PropertyService getPropertyService() {
303        return mPropertyService;
304    }
305
306    public BuildProperties getBuildProperties() {
307        return mBuildProperties;
308    }
309
310    public KeyStore getKeyStore() {
311        return mKeyStore;
312    }
313
314    public WifiBackupRestore getWifiBackupRestore() {
315        return mWifiBackupRestore;
316    }
317
318    public WifiMulticastLockManager getWifiMulticastLockManager() {
319        return mWifiMulticastLockManager;
320    }
321
322    public WifiConfigManager getWifiConfigManager() {
323        return mWifiConfigManager;
324    }
325
326    public PasspointManager getPasspointManager() {
327        return mPasspointManager;
328    }
329
330    public TelephonyManager makeTelephonyManager() {
331        // may not be available when WiFi starts
332        return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
333    }
334
335    public WifiStateTracker getWifiStateTracker() {
336        return mWifiStateTracker;
337    }
338
339    public IWificond makeWificond() {
340        // We depend on being able to refresh our binder in WifiStateMachine, so don't cache it.
341        IBinder binder = ServiceManager.getService(WIFICOND_SERVICE_NAME);
342        return IWificond.Stub.asInterface(binder);
343    }
344
345    /**
346     * Create a SoftApManager.
347     * @param nmService NetworkManagementService allowing SoftApManager to listen for interface
348     * changes
349     * @param listener listener for SoftApManager
350     * @param apInterface network interface to start hostapd against
351     * @param config softAp WifiConfiguration
352     * @return an instance of SoftApManager
353     */
354    public SoftApManager makeSoftApManager(INetworkManagementService nmService,
355                                           SoftApManager.Listener listener,
356                                           IApInterface apInterface,
357                                           WifiConfiguration config) {
358        return new SoftApManager(mWifiServiceHandlerThread.getLooper(),
359                                 mWifiNative, mCountryCode.getCountryCode(),
360                                 listener, apInterface, nmService,
361                                 mWifiApConfigStore, config, mWifiMetrics);
362    }
363
364    /**
365     * Create a WifiLog instance.
366     * @param tag module name to include in all log messages
367     */
368    public WifiLog makeLog(String tag) {
369        return new LogcatLog(tag);
370    }
371
372    public BaseWifiDiagnostics makeWifiDiagnostics(WifiNative wifiNative) {
373        if (mUseRealLogger) {
374            return new WifiDiagnostics(
375                    mContext, this, mWifiStateMachine, wifiNative, mBuildProperties,
376                    new LastMileLogger(this));
377        } else {
378            return new BaseWifiDiagnostics(wifiNative);
379        }
380    }
381
382    /**
383     * Obtain an instance of WifiScanner.
384     * If it was not already created, then obtain an instance.  Note, this must be done lazily since
385     * WifiScannerService is separate and created later.
386     */
387    public synchronized WifiScanner getWifiScanner() {
388        if (mWifiScanner == null) {
389            mWifiScanner = new WifiScanner(mContext,
390                    IWifiScanner.Stub.asInterface(ServiceManager.getService(
391                            Context.WIFI_SCANNING_SERVICE)),
392                    mWifiStateMachineHandlerThread.getLooper());
393        }
394        return mWifiScanner;
395    }
396
397    /**
398     * Obtain an instance of WifiNetworkSelector.
399     */
400    public WifiNetworkSelector getWifiNetworkSelector() {
401        return mWifiNetworkSelector;
402    }
403
404    /**
405     * Obtain a new instance of WifiConnectivityManager.
406     *
407     * Create and return a new WifiConnectivityManager.
408     * @param wifiInfo WifiInfo object for updating wifi state.
409     * @param hasConnectionRequests boolean indicating if WifiConnectivityManager to start
410     * immediately based on connection requests.
411     */
412    public WifiConnectivityManager makeWifiConnectivityManager(WifiInfo wifiInfo,
413                                                               boolean hasConnectionRequests) {
414        return new WifiConnectivityManager(mContext, mWifiStateMachine, getWifiScanner(),
415                mWifiConfigManager, wifiInfo, mWifiNetworkSelector, mWifiLastResortWatchdog,
416                mWifiMetrics, mWifiStateMachineHandlerThread.getLooper(), mClock,
417                hasConnectionRequests, mFrameworkFacade, mSavedNetworkEvaluator,
418                mRecommendedNetworkEvaluator, mPasspointNetworkEvaluator);
419    }
420
421    public WifiPermissionsUtil getWifiPermissionsUtil() {
422        return mWifiPermissionsUtil;
423    }
424
425    public WifiPermissionsWrapper getWifiPermissionsWrapper() {
426        return mWifiPermissionsWrapper;
427    }
428
429    /**
430     * Returns a singleton instance of a HandlerThread for injection. Uses lazy initialization.
431     *
432     * TODO: share worker thread with other Wi-Fi handlers (b/27924886)
433     */
434    public HandlerThread getWifiAwareHandlerThread() {
435        if (mWifiAwareHandlerThread == null) { // lazy initialization
436            mWifiAwareHandlerThread = new HandlerThread("wifiAwareService");
437            mWifiAwareHandlerThread.start();
438        }
439        return mWifiAwareHandlerThread;
440    }
441
442    /**
443     * Returns a single instance of HalDeviceManager for injection.
444     */
445    public HalDeviceManager getHalDeviceManager() {
446        return mHalDeviceManager;
447    }
448
449    public Runtime getJavaRuntime() {
450        return mJavaRuntime;
451    }
452
453    public WifiNative getWifiNative() {
454        return mWifiNative;
455    }
456
457    public WifiMonitor getWifiMonitor() {
458        return mWifiMonitor;
459    }
460
461    public WifiP2pNative getWifiP2pNative() {
462        return mWifiP2pNative;
463    }
464
465    public WifiP2pMonitor getWifiP2pMonitor() {
466        return mWifiP2pMonitor;
467    }
468}
469