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