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