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