• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 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 
17 package com.android.internal.telephony.data;
18 
19 import android.annotation.CallbackExecutor;
20 import android.annotation.NonNull;
21 import android.annotation.StringDef;
22 import android.content.res.Resources;
23 import android.net.LinkProperties;
24 import android.net.NetworkCapabilities;
25 import android.os.Handler;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.os.PersistableBundle;
29 import android.provider.DeviceConfig;
30 import android.telephony.Annotation.ApnType;
31 import android.telephony.Annotation.NetCapability;
32 import android.telephony.Annotation.NetworkType;
33 import android.telephony.CarrierConfigManager;
34 import android.telephony.ServiceState;
35 import android.telephony.SignalStrength;
36 import android.telephony.SubscriptionManager;
37 import android.telephony.TelephonyDisplayInfo;
38 import android.telephony.TelephonyManager;
39 import android.telephony.data.ApnSetting;
40 import android.text.TextUtils;
41 import android.util.ArraySet;
42 import android.util.IndentingPrintWriter;
43 
44 import com.android.internal.annotations.VisibleForTesting;
45 import com.android.internal.telephony.Phone;
46 import com.android.internal.telephony.data.DataNetworkController.HandoverRule;
47 import com.android.internal.telephony.data.DataRetryManager.DataHandoverRetryRule;
48 import com.android.internal.telephony.data.DataRetryManager.DataSetupRetryRule;
49 import com.android.telephony.Rlog;
50 
51 import java.io.FileDescriptor;
52 import java.io.PrintWriter;
53 import java.lang.annotation.Retention;
54 import java.lang.annotation.RetentionPolicy;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.Collections;
58 import java.util.HashSet;
59 import java.util.List;
60 import java.util.Locale;
61 import java.util.Map;
62 import java.util.Set;
63 import java.util.concurrent.ConcurrentHashMap;
64 import java.util.concurrent.Executor;
65 import java.util.stream.Collectors;
66 
67 /**
68  * DataConfigManager is the source of all data related configuration from carrier config and
69  * resource overlay. DataConfigManager is created to reduce the excessive access to the
70  * {@link CarrierConfigManager}. All the data config will be loaded once and stored here.
71  */
72 public class DataConfigManager extends Handler {
73     /** The default timeout in ms for data network stuck in a transit state. */
74     private static final int DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS = 300000;
75 
76     /** Event for carrier config changed. */
77     private static final int EVENT_CARRIER_CONFIG_CHANGED = 1;
78 
79     /** Event for device config changed. */
80     private static final int EVENT_DEVICE_CONFIG_CHANGED = 2;
81 
82     /** Indicates the bandwidth estimation source is from the modem. */
83     private static final String BANDWIDTH_SOURCE_MODEM_STRING_VALUE = "modem";
84 
85     /** Indicates the bandwidth estimation source is from the static carrier config. */
86     private static final String BANDWIDTH_SOURCE_CARRIER_CONFIG_STRING_VALUE = "carrier_config";
87 
88     /** Indicates the bandwidth estimation source is from {@link LinkBandwidthEstimator}. */
89     private static final String BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR_STRING_VALUE =
90             "bandwidth_estimator";
91 
92     /** Default downlink and uplink bandwidth value in kbps. */
93     private static final int DEFAULT_BANDWIDTH = 14;
94 
95     /** Network type GPRS. Should not be used outside of DataConfigManager. */
96     private static final String DATA_CONFIG_NETWORK_TYPE_GPRS = "GPRS";
97 
98     /** Network type EDGE. Should not be used outside of DataConfigManager. */
99     private static final String DATA_CONFIG_NETWORK_TYPE_EDGE = "EDGE";
100 
101     /** Network type UMTS. Should not be used outside of DataConfigManager. */
102     private static final String DATA_CONFIG_NETWORK_TYPE_UMTS = "UMTS";
103 
104     /** Network type CDMA. Should not be used outside of DataConfigManager. */
105     private static final String DATA_CONFIG_NETWORK_TYPE_CDMA = "CDMA";
106 
107     /** Network type 1xRTT. Should not be used outside of DataConfigManager. */
108     private static final String DATA_CONFIG_NETWORK_TYPE_1xRTT = "1xRTT";
109 
110     /** Network type EvDo Rev 0. Should not be used outside of DataConfigManager. */
111     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_0 = "EvDo_0";
112 
113     /** Network type EvDo Rev A. Should not be used outside of DataConfigManager. */
114     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_A = "EvDo_A";
115 
116     /** Network type HSDPA. Should not be used outside of DataConfigManager. */
117     private static final String DATA_CONFIG_NETWORK_TYPE_HSDPA = "HSDPA";
118 
119     /** Network type HSUPA. Should not be used outside of DataConfigManager. */
120     private static final String DATA_CONFIG_NETWORK_TYPE_HSUPA = "HSUPA";
121 
122     /** Network type HSPA. Should not be used outside of DataConfigManager. */
123     private static final String DATA_CONFIG_NETWORK_TYPE_HSPA = "HSPA";
124 
125     /** Network type EvDo Rev B. Should not be used outside of DataConfigManager. */
126     private static final String DATA_CONFIG_NETWORK_TYPE_EVDO_B = "EvDo_B";
127 
128     /** Network type eHRPD. Should not be used outside of DataConfigManager. */
129     private static final String DATA_CONFIG_NETWORK_TYPE_EHRPD = "eHRPD";
130 
131     /** Network type iDEN. Should not be used outside of DataConfigManager. */
132     private static final String DATA_CONFIG_NETWORK_TYPE_IDEN = "iDEN";
133 
134     /** Network type LTE. Should not be used outside of DataConfigManager. */
135     private static final String DATA_CONFIG_NETWORK_TYPE_LTE = "LTE";
136 
137     /** Network type HSPA+. Should not be used outside of DataConfigManager. */
138     private static final String DATA_CONFIG_NETWORK_TYPE_HSPAP = "HSPA+";
139 
140     /** Network type GSM. Should not be used outside of DataConfigManager. */
141     private static final String DATA_CONFIG_NETWORK_TYPE_GSM = "GSM";
142 
143     /** Network type IWLAN. Should not be used outside of DataConfigManager. */
144     private static final String DATA_CONFIG_NETWORK_TYPE_IWLAN = "IWLAN";
145 
146     /** Network type TD_SCDMA. Should not be used outside of DataConfigManager. */
147     private static final String DATA_CONFIG_NETWORK_TYPE_TD_SCDMA = "TD_SCDMA";
148 
149     /** Network type LTE_CA. Should not be used outside of DataConfigManager. */
150     private static final String DATA_CONFIG_NETWORK_TYPE_LTE_CA = "LTE_CA";
151 
152     /** Network type NR_NSA. Should not be used outside of DataConfigManager. */
153     private static final String DATA_CONFIG_NETWORK_TYPE_NR_NSA = "NR_NSA";
154 
155     /** Network type NR_NSA_MMWAVE. Should not be used outside of DataConfigManager. */
156     private static final String DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE = "NR_NSA_MMWAVE";
157 
158     /** Network type NR_SA. Should not be used outside of DataConfigManager. */
159     private static final String DATA_CONFIG_NETWORK_TYPE_NR_SA = "NR_SA";
160 
161     /** Network type NR_SA_MMWAVE. Should not be used outside of DataConfigManager. */
162     private static final String DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE = "NR_SA_MMWAVE";
163 
164     @StringDef(prefix = {"DATA_CONFIG_NETWORK_TYPE_"}, value = {
165             DATA_CONFIG_NETWORK_TYPE_GPRS,
166             DATA_CONFIG_NETWORK_TYPE_EDGE,
167             DATA_CONFIG_NETWORK_TYPE_UMTS,
168             DATA_CONFIG_NETWORK_TYPE_CDMA,
169             DATA_CONFIG_NETWORK_TYPE_1xRTT,
170             DATA_CONFIG_NETWORK_TYPE_EVDO_0,
171             DATA_CONFIG_NETWORK_TYPE_EVDO_A,
172             DATA_CONFIG_NETWORK_TYPE_HSDPA,
173             DATA_CONFIG_NETWORK_TYPE_HSUPA,
174             DATA_CONFIG_NETWORK_TYPE_HSPA,
175             DATA_CONFIG_NETWORK_TYPE_EVDO_B,
176             DATA_CONFIG_NETWORK_TYPE_EHRPD,
177             DATA_CONFIG_NETWORK_TYPE_IDEN,
178             DATA_CONFIG_NETWORK_TYPE_LTE,
179             DATA_CONFIG_NETWORK_TYPE_HSPAP,
180             DATA_CONFIG_NETWORK_TYPE_GSM,
181             DATA_CONFIG_NETWORK_TYPE_IWLAN,
182             DATA_CONFIG_NETWORK_TYPE_TD_SCDMA,
183             DATA_CONFIG_NETWORK_TYPE_LTE_CA,
184             DATA_CONFIG_NETWORK_TYPE_NR_NSA,
185             DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE,
186             DATA_CONFIG_NETWORK_TYPE_NR_SA,
187             DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE,
188     })
189     @Retention(RetentionPolicy.SOURCE)
190     private @interface DataConfigNetworkType {}
191 
192     /** Data config update callbacks. */
193     private final @NonNull Set<DataConfigManagerCallback> mDataConfigManagerCallbacks =
194             new ArraySet<>();
195 
196     /** DeviceConfig key of anomaly report threshold for back to back ims release-request. */
197     private static final String KEY_ANOMALY_IMS_RELEASE_REQUEST = "anomaly_ims_release_request";
198     /** DeviceConfig key of anomaly report threshold for frequent setup data failure. */
199     private static final String KEY_ANOMALY_SETUP_DATA_CALL_FAILURE =
200             "anomaly_setup_data_call_failure";
201     /** DeviceConfig key of anomaly report threshold for frequent network-unwanted call. */
202     private static final String KEY_ANOMALY_NETWORK_UNWANTED = "anomaly_network_unwanted";
203     /** DeviceConfig key of anomaly report threshold for invalid QNS params. */
204     private static final String KEY_ANOMALY_QNS_PARAM = "anomaly_qns_param";
205     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in connecting state. */
206     private static final String KEY_ANOMALY_NETWORK_CONNECTING_TIMEOUT =
207             "anomaly_network_connecting_timeout";
208     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in disconnecting state.*/
209     private static final String KEY_ANOMALY_NETWORK_DISCONNECTING_TIMEOUT =
210             "anomaly_network_disconnecting_timeout";
211     /** DeviceConfig key of anomaly report threshold for DataNetwork stuck in handover state. */
212     private static final String KEY_ANOMALY_NETWORK_HANDOVER_TIMEOUT =
213             "anomaly_network_handover_timeout";
214     /** DeviceConfig key of anomaly report: True for enabling APN config invalidity detection */
215     private static final String KEY_ANOMALY_APN_CONFIG_ENABLED = "anomaly_apn_config_enabled";
216     /** Invalid auto data switch score. */
217     private static final int INVALID_AUTO_DATA_SWITCH_SCORE = -1;
218     /** Anomaly report thresholds for frequent setup data call failure. */
219     private EventFrequency mSetupDataCallAnomalyReportThreshold;
220 
221     /** Anomaly report thresholds for back to back release-request of IMS. */
222     private EventFrequency mImsReleaseRequestAnomalyReportThreshold;
223 
224     /**
225      * Anomaly report thresholds for frequent network unwanted call
226      * at {@link TelephonyNetworkAgent#onNetworkUnwanted}
227      */
228     private EventFrequency mNetworkUnwantedAnomalyReportThreshold;
229 
230     /**
231      * {@code true} if enabled anomaly detection for param when QNS wants to change preferred
232      * network at {@link AccessNetworksManager}.
233      */
234     private boolean mIsInvalidQnsParamAnomalyReportEnabled;
235 
236     /**
237      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
238      * {@link DataNetwork.ConnectingState}.
239      */
240     private int mNetworkConnectingTimeout;
241 
242     /**
243      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
244      * {@link DataNetwork.DisconnectingState}.
245      */
246     private int mNetworkDisconnectingTimeout;
247 
248     /**
249      * Timeout in ms before creating an anomaly report for a DataNetwork stuck in
250      * {@link DataNetwork.HandoverState}.
251      */
252     private int mNetworkHandoverTimeout;
253 
254     /**
255      * True if enabled anomaly detection for APN config that's read from {@link DataProfileManager}
256      */
257     private boolean mIsApnConfigAnomalyReportEnabled;
258 
259     private @NonNull final Phone mPhone;
260     private @NonNull final String mLogTag;
261 
262     private @NonNull final CarrierConfigManager mCarrierConfigManager;
263     private @NonNull PersistableBundle mCarrierConfig = null;
264     private @NonNull Resources mResources = null;
265 
266     /** The network capability priority map */
267     private @NonNull final Map<Integer, Integer> mNetworkCapabilityPriorityMap =
268             new ConcurrentHashMap<>();
269     /** The data setup retry rules */
270     private @NonNull final List<DataSetupRetryRule> mDataSetupRetryRules = new ArrayList<>();
271     /** The data handover retry rules */
272     private @NonNull final List<DataHandoverRetryRule> mDataHandoverRetryRules = new ArrayList<>();
273     /** The metered APN types for home network */
274     private @NonNull final @ApnType Set<Integer> mMeteredApnTypes = new HashSet<>();
275     /** The metered APN types for roaming network */
276     private @NonNull final @ApnType Set<Integer> mRoamingMeteredApnTypes = new HashSet<>();
277     /** The network types that only support single data networks */
278     private @NonNull final @NetworkType List<Integer> mSingleDataNetworkTypeList =
279             new ArrayList<>();
280     private @NonNull final @NetCapability Set<Integer> mCapabilitiesExemptFromSingleDataList =
281             new HashSet<>();
282     /** The network types that support temporarily not metered */
283     private @NonNull final @DataConfigNetworkType Set<String> mUnmeteredNetworkTypes =
284             new HashSet<>();
285     /** The network types that support temporarily not metered when roaming */
286     private @NonNull final @DataConfigNetworkType Set<String> mRoamingUnmeteredNetworkTypes =
287             new HashSet<>();
288     /** A map of network types to the downlink and uplink bandwidth values for that network type */
289     private @NonNull final @DataConfigNetworkType Map<String, DataNetwork.NetworkBandwidth>
290             mBandwidthMap = new ConcurrentHashMap<>();
291     /** A map of network types to the TCP buffer sizes for that network type */
292     private @NonNull final @DataConfigNetworkType Map<String, String> mTcpBufferSizeMap =
293             new ConcurrentHashMap<>();
294     /** Rules for handover between IWLAN and cellular network. */
295     private @NonNull final List<HandoverRule> mHandoverRuleList = new ArrayList<>();
296     /** {@code True} keep IMS network in case of moving to non VOPS area; {@code false} otherwise.*/
297     private boolean mShouldKeepNetworkUpInNonVops = false;
298     /**
299      * A map of network types to the estimated downlink values by signal strength 0 - 4 for that
300      * network type
301      */
302     private @NonNull final @DataConfigNetworkType Map<String, int[]>
303             mAutoDataSwitchNetworkTypeSignalMap = new ConcurrentHashMap<>();
304 
305     /**
306      * Constructor
307      *
308      * @param phone The phone instance.
309      * @param looper The looper to be used by the handler. Currently the handler thread is the
310      * phone process's main thread.
311      */
DataConfigManager(@onNull Phone phone, @NonNull Looper looper)312     public DataConfigManager(@NonNull Phone phone, @NonNull Looper looper) {
313         super(looper);
314         mPhone = phone;
315         mLogTag = "DCM-" + mPhone.getPhoneId();
316         log("DataConfigManager created.");
317 
318         mCarrierConfigManager = mPhone.getContext().getSystemService(CarrierConfigManager.class);
319         // Callback send msg to handler thread, so callback itself can be executed in binder thread.
320         mCarrierConfigManager.registerCarrierConfigChangeListener(Runnable::run,
321                 (slotIndex, subId, carrierId, specificCarrierId) -> {
322                     if (slotIndex == mPhone.getPhoneId()) {
323                         sendEmptyMessage(EVENT_CARRIER_CONFIG_CHANGED);
324                     }
325                 });
326 
327         // Register for device config update
328         DeviceConfig.addOnPropertiesChangedListener(
329                 DeviceConfig.NAMESPACE_TELEPHONY, this::post,
330                 properties -> {
331                     if (TextUtils.equals(DeviceConfig.NAMESPACE_TELEPHONY,
332                             properties.getNamespace())) {
333                         sendEmptyMessage(EVENT_DEVICE_CONFIG_CHANGED);
334                     }
335                 });
336 
337         // Must be called to set mCarrierConfig and mResources to non-null values
338         updateCarrierConfig();
339         // Must be called to set anomaly report threshold to non-null values
340         updateDeviceConfig();
341     }
342 
343     /**
344      * The data config callback.
345      */
346     public static class DataConfigManagerCallback extends DataCallback {
347         /**
348          * Constructor
349          *
350          * @param executor The executor of the callback.
351          */
DataConfigManagerCallback(@onNull @allbackExecutor Executor executor)352         public DataConfigManagerCallback(@NonNull @CallbackExecutor Executor executor) {
353             super(executor);
354         }
355 
356         /** Callback on carrier config update.*/
onCarrierConfigChanged()357         public void onCarrierConfigChanged() {}
358 
359         /** Callback on device config update.*/
onDeviceConfigChanged()360         public void onDeviceConfigChanged() {}
361     }
362 
363     /**
364      * Register the callback for receiving information from {@link DataConfigManager}.
365      *
366      * @param callback The callback.
367      */
registerCallback(@onNull DataConfigManagerCallback callback)368     public void registerCallback(@NonNull DataConfigManagerCallback callback) {
369         mDataConfigManagerCallbacks.add(callback);
370     }
371 
372     /**
373      * Unregister the callback.
374      *
375      * @param callback The previously registered callback.
376      */
unregisterCallback(@onNull DataConfigManagerCallback callback)377     public void unregisterCallback(@NonNull DataConfigManagerCallback callback) {
378         mDataConfigManagerCallbacks.remove(callback);
379     }
380 
381     @Override
handleMessage(Message msg)382     public void handleMessage(Message msg) {
383         switch (msg.what) {
384             case EVENT_CARRIER_CONFIG_CHANGED:
385                 log("EVENT_CARRIER_CONFIG_CHANGED");
386                 updateCarrierConfig();
387                 mDataConfigManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
388                         callback::onCarrierConfigChanged));
389                 break;
390             case EVENT_DEVICE_CONFIG_CHANGED:
391                 log("EVENT_DEVICE_CONFIG_CHANGED");
392                 updateDeviceConfig();
393                 mDataConfigManagerCallbacks.forEach(callback -> callback.invokeFromExecutor(
394                         callback::onDeviceConfigChanged));
395                 break;
396             default:
397                 loge("Unexpected message " + msg.what);
398         }
399     }
400 
401     /** Update local properties from {@link DeviceConfig} */
updateDeviceConfig()402     private void updateDeviceConfig() {
403         DeviceConfig.Properties properties = //read all telephony properties
404                 DeviceConfig.getProperties(DeviceConfig.NAMESPACE_TELEPHONY);
405 
406         mImsReleaseRequestAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
407                 properties.getString(KEY_ANOMALY_IMS_RELEASE_REQUEST, null), 0, 2);
408         mNetworkUnwantedAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
409                 properties.getString(KEY_ANOMALY_NETWORK_UNWANTED, null), 0, 12);
410         mSetupDataCallAnomalyReportThreshold = parseSlidingWindowCounterThreshold(
411                 properties.getString(KEY_ANOMALY_SETUP_DATA_CALL_FAILURE, null), 0, 12);
412         mIsInvalidQnsParamAnomalyReportEnabled = properties.getBoolean(
413                 KEY_ANOMALY_QNS_PARAM, false);
414         mNetworkConnectingTimeout = properties.getInt(
415                 KEY_ANOMALY_NETWORK_CONNECTING_TIMEOUT, DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
416         mNetworkDisconnectingTimeout = properties.getInt(
417                 KEY_ANOMALY_NETWORK_DISCONNECTING_TIMEOUT,
418                 DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
419         mNetworkHandoverTimeout = properties.getInt(
420                 KEY_ANOMALY_NETWORK_HANDOVER_TIMEOUT, DEFAULT_NETWORK_TRANSIT_STATE_TIMEOUT_MS);
421         mIsApnConfigAnomalyReportEnabled = properties.getBoolean(
422                 KEY_ANOMALY_APN_CONFIG_ENABLED, false);
423     }
424 
425     /**
426      * @return {@code true} if the configuration is carrier specific. {@code false} if the
427      * configuration is the default (i.e. SIM not inserted).
428      */
isConfigCarrierSpecific()429     public boolean isConfigCarrierSpecific() {
430         return mCarrierConfig.getBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL);
431     }
432 
433     /**
434      * Update the configuration from carrier configs and resources.
435      */
updateCarrierConfig()436     private void updateCarrierConfig() {
437         if (mCarrierConfigManager != null) {
438             mCarrierConfig = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId());
439         }
440         if (mCarrierConfig == null) {
441             mCarrierConfig = CarrierConfigManager.getDefaultConfig();
442         }
443         mResources = SubscriptionManager.getResourcesForSubId(mPhone.getContext(),
444                 mPhone.getSubId());
445 
446         updateNetworkCapabilityPriority();
447         updateDataRetryRules();
448         updateMeteredApnTypes();
449         updateSingleDataNetworkTypeAndCapabilityExemption();
450         updateVopsConfig();
451         updateUnmeteredNetworkTypes();
452         updateBandwidths();
453         updateTcpBuffers();
454         updateHandoverRules();
455         updateAutoDataSwitchConfig();
456 
457         log("Carrier config updated. Config is " + (isConfigCarrierSpecific() ? "" : "not ")
458                 + "carrier specific.");
459     }
460 
461     /**
462      * Update the network capability priority from carrier config.
463      */
updateNetworkCapabilityPriority()464     private void updateNetworkCapabilityPriority() {
465         synchronized (this) {
466             mNetworkCapabilityPriorityMap.clear();
467             String[] capabilityPriorityStrings = mCarrierConfig.getStringArray(
468                     CarrierConfigManager.KEY_TELEPHONY_NETWORK_CAPABILITY_PRIORITIES_STRING_ARRAY);
469             if (capabilityPriorityStrings != null) {
470                 for (String capabilityPriorityString : capabilityPriorityStrings) {
471                     capabilityPriorityString =
472                             capabilityPriorityString.trim().toUpperCase(Locale.ROOT);
473                     String[] tokens = capabilityPriorityString.split(":");
474                     if (tokens.length != 2) {
475                         loge("Invalid config \"" + capabilityPriorityString + "\"");
476                         continue;
477                     }
478 
479                     int netCap = DataUtils.getNetworkCapabilityFromString(tokens[0]);
480                     if (netCap < 0) {
481                         loge("Invalid config \"" + capabilityPriorityString + "\"");
482                         continue;
483                     }
484 
485                     int priority = Integer.parseInt(tokens[1]);
486                     mNetworkCapabilityPriorityMap.put(netCap, priority);
487                 }
488             }
489         }
490     }
491 
492     /**
493      * Get the priority of a network capability.
494      *
495      * @param capability The network capability
496      * @return The priority range from 0 ~ 100. 100 is the highest priority.
497      */
getNetworkCapabilityPriority(@etCapability int capability)498     public int getNetworkCapabilityPriority(@NetCapability int capability) {
499         if (mNetworkCapabilityPriorityMap.containsKey(capability)) {
500             return mNetworkCapabilityPriorityMap.get(capability);
501         }
502         return 0;
503     }
504 
505     /**
506      * Update the data retry rules from the carrier config.
507      */
updateDataRetryRules()508     private void updateDataRetryRules() {
509         synchronized (this) {
510             mDataSetupRetryRules.clear();
511             String[] dataRetryRulesStrings = mCarrierConfig.getStringArray(
512                     CarrierConfigManager.KEY_TELEPHONY_DATA_SETUP_RETRY_RULES_STRING_ARRAY);
513             if (dataRetryRulesStrings != null) {
514                 for (String ruleString : dataRetryRulesStrings) {
515                     try {
516                         mDataSetupRetryRules.add(new DataSetupRetryRule(ruleString));
517                     } catch (IllegalArgumentException e) {
518                         loge("updateDataRetryRules: " + e.getMessage());
519                     }
520                 }
521             }
522 
523             mDataHandoverRetryRules.clear();
524             dataRetryRulesStrings = mCarrierConfig.getStringArray(
525                     CarrierConfigManager.KEY_TELEPHONY_DATA_HANDOVER_RETRY_RULES_STRING_ARRAY);
526             if (dataRetryRulesStrings != null) {
527                 for (String ruleString : dataRetryRulesStrings) {
528                     try {
529                         mDataHandoverRetryRules.add(new DataHandoverRetryRule(ruleString));
530                     } catch (IllegalArgumentException e) {
531                         loge("updateDataRetryRules: " + e.getMessage());
532                     }
533                 }
534             }
535         }
536     }
537 
538     /**
539      * @return The data setup retry rules from carrier config.
540      */
getDataSetupRetryRules()541     public @NonNull List<DataSetupRetryRule> getDataSetupRetryRules() {
542         return Collections.unmodifiableList(mDataSetupRetryRules);
543     }
544 
545     /**
546      * @return The data handover retry rules from carrier config.
547      */
getDataHandoverRetryRules()548     public @NonNull List<DataHandoverRetryRule> getDataHandoverRetryRules() {
549         return Collections.unmodifiableList(mDataHandoverRetryRules);
550     }
551 
552     /**
553      * @return Whether data roaming is enabled by default in carrier config.
554      */
isDataRoamingEnabledByDefault()555     public boolean isDataRoamingEnabledByDefault() {
556         return mCarrierConfig.getBoolean(
557                 CarrierConfigManager.KEY_CARRIER_DEFAULT_DATA_ROAMING_ENABLED_BOOL);
558     }
559 
560     /**
561      * Update the home and roaming metered APN types from the carrier config.
562      */
updateMeteredApnTypes()563     private void updateMeteredApnTypes() {
564         synchronized (this) {
565             mMeteredApnTypes.clear();
566             String[] meteredApnTypes = mCarrierConfig.getStringArray(
567                     CarrierConfigManager.KEY_CARRIER_METERED_APN_TYPES_STRINGS);
568             if (meteredApnTypes != null) {
569                 Arrays.stream(meteredApnTypes)
570                         .map(ApnSetting::getApnTypeInt)
571                         .forEach(mMeteredApnTypes::add);
572             }
573             mRoamingMeteredApnTypes.clear();
574             String[] roamingMeteredApns = mCarrierConfig.getStringArray(
575                     CarrierConfigManager.KEY_CARRIER_METERED_ROAMING_APN_TYPES_STRINGS);
576             if (roamingMeteredApns != null) {
577                 Arrays.stream(roamingMeteredApns)
578                         .map(ApnSetting::getApnTypeInt)
579                         .forEach(mRoamingMeteredApnTypes::add);
580             }
581         }
582     }
583 
584     /**
585      * Get the metered network capabilities.
586      *
587      * @param isRoaming {@code true} for roaming scenario.
588      *
589      * @return The metered network capabilities when connected to a home network.
590      */
getMeteredNetworkCapabilities(boolean isRoaming)591     public @NonNull @NetCapability Set<Integer> getMeteredNetworkCapabilities(boolean isRoaming) {
592         Set<Integer> meteredApnTypes = isRoaming ? mRoamingMeteredApnTypes : mMeteredApnTypes;
593         return meteredApnTypes.stream()
594                 .map(DataUtils::apnTypeToNetworkCapability)
595                 .filter(cap -> cap >= 0)
596                 .collect(Collectors.toUnmodifiableSet());
597     }
598 
599     /**
600      * @return {@code true} if tethering profile should not be used when the device is roaming.
601      */
isTetheringProfileDisabledForRoaming()602     public boolean isTetheringProfileDisabledForRoaming() {
603         return mCarrierConfig.getBoolean(
604                 CarrierConfigManager.KEY_DISABLE_DUN_APN_WHILE_ROAMING_WITH_PRESET_APN_BOOL);
605     }
606 
607     /**
608      * Check if the network capability metered.
609      *
610      * @param networkCapability The network capability.
611      * @param isRoaming {@code true} for roaming scenario.
612      * @return {@code true} if the network capability is metered.
613      */
isMeteredCapability(@etCapability int networkCapability, boolean isRoaming)614     public boolean isMeteredCapability(@NetCapability int networkCapability, boolean isRoaming) {
615         return getMeteredNetworkCapabilities(isRoaming).contains(networkCapability);
616     }
617 
618     /**
619      * Check if the network capabilities are metered. If one of the capabilities is metered, then
620      * the capabilities are metered.
621      *
622      * @param networkCapabilities The network capabilities.
623      * @param isRoaming {@code true} for roaming scenario.
624      * @return {@code true} if the capabilities are metered.
625      */
isAnyMeteredCapability(@onNull @etCapability int[] networkCapabilities, boolean isRoaming)626     public boolean isAnyMeteredCapability(@NonNull @NetCapability int[] networkCapabilities,
627             boolean isRoaming) {
628         return Arrays.stream(networkCapabilities).boxed()
629                 .anyMatch(cap -> isMeteredCapability(cap, isRoaming));
630     }
631 
632     /**
633      * @return Whether to use data activity for RRC detection
634      */
shouldUseDataActivityForRrcDetection()635     public boolean shouldUseDataActivityForRrcDetection() {
636         return mCarrierConfig.getBoolean(
637                 CarrierConfigManager.KEY_LTE_ENDC_USING_USER_DATA_FOR_RRC_DETECTION_BOOL);
638     }
639 
640     /**
641      * Update the network types for only single data networks from the carrier config.
642      */
updateSingleDataNetworkTypeAndCapabilityExemption()643     private void updateSingleDataNetworkTypeAndCapabilityExemption() {
644         synchronized (this) {
645             mSingleDataNetworkTypeList.clear();
646             mCapabilitiesExemptFromSingleDataList.clear();
647             int[] singleDataNetworkTypeList = mCarrierConfig.getIntArray(
648                     CarrierConfigManager.KEY_ONLY_SINGLE_DC_ALLOWED_INT_ARRAY);
649             if (singleDataNetworkTypeList != null) {
650                 Arrays.stream(singleDataNetworkTypeList).forEach(mSingleDataNetworkTypeList::add);
651             }
652 
653             int[] singleDataCapabilitiesExemptList = mCarrierConfig.getIntArray(
654                     CarrierConfigManager.KEY_CAPABILITIES_EXEMPT_FROM_SINGLE_DC_CHECK_INT_ARRAY);
655             if (singleDataCapabilitiesExemptList != null) {
656                 Arrays.stream(singleDataCapabilitiesExemptList)
657                         .forEach(mCapabilitiesExemptFromSingleDataList::add);
658             }
659         }
660     }
661 
662     /**
663      * Update the voice over PS related config from the carrier config.
664      */
updateVopsConfig()665     private void updateVopsConfig() {
666         synchronized (this) {
667             mShouldKeepNetworkUpInNonVops = mCarrierConfig.getBoolean(CarrierConfigManager
668                     .Ims.KEY_KEEP_PDN_UP_IN_NO_VOPS_BOOL);
669         }
670     }
671 
672     /**
673      * @return The list of {@link NetworkType} that only supports single data networks
674      */
getNetworkTypesOnlySupportSingleDataNetwork()675     public @NonNull @NetworkType List<Integer> getNetworkTypesOnlySupportSingleDataNetwork() {
676         return Collections.unmodifiableList(mSingleDataNetworkTypeList);
677     }
678 
679     /**
680      * @return The list of {@link android.net.NetworkCapabilities.NetCapability} that every of which
681      * is exempt from the single PDN check.
682      */
getCapabilitiesExemptFromSingleDataNetwork()683     public @NonNull @NetCapability Set<Integer> getCapabilitiesExemptFromSingleDataNetwork() {
684         return Collections.unmodifiableSet(mCapabilitiesExemptFromSingleDataList);
685     }
686 
687     /** {@code True} keep IMS network in case of moving to non VOPS area; {@code false} otherwise.*/
shouldKeepNetworkUpInNonVops()688     public boolean shouldKeepNetworkUpInNonVops() {
689         return mShouldKeepNetworkUpInNonVops;
690     }
691 
692     /** {@code True} requires ping test to pass on the target slot before switching to it.*/
isPingTestBeforeAutoDataSwitchRequired()693     public boolean isPingTestBeforeAutoDataSwitchRequired() {
694         return mResources.getBoolean(com.android.internal.R.bool
695                 .auto_data_switch_ping_test_before_switch);
696     }
697 
698     /**
699      * @return Whether {@link NetworkCapabilities#NET_CAPABILITY_TEMPORARILY_NOT_METERED}
700      * is supported by the carrier.
701      */
isTempNotMeteredSupportedByCarrier()702     public boolean isTempNotMeteredSupportedByCarrier() {
703         return mCarrierConfig.getBoolean(
704                 CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL);
705     }
706 
707     /**
708      * Update the network types that are temporarily not metered from the carrier config.
709      */
updateUnmeteredNetworkTypes()710     private void updateUnmeteredNetworkTypes() {
711         synchronized (this) {
712             mUnmeteredNetworkTypes.clear();
713             String[] unmeteredNetworkTypes = mCarrierConfig.getStringArray(
714                     CarrierConfigManager.KEY_UNMETERED_NETWORK_TYPES_STRING_ARRAY);
715             if (unmeteredNetworkTypes != null) {
716                 mUnmeteredNetworkTypes.addAll(Arrays.asList(unmeteredNetworkTypes));
717             }
718             mRoamingUnmeteredNetworkTypes.clear();
719             String[] roamingUnmeteredNetworkTypes = mCarrierConfig.getStringArray(
720                     CarrierConfigManager.KEY_ROAMING_UNMETERED_NETWORK_TYPES_STRING_ARRAY);
721             if (roamingUnmeteredNetworkTypes != null) {
722                 mRoamingUnmeteredNetworkTypes.addAll(Arrays.asList(roamingUnmeteredNetworkTypes));
723             }
724         }
725     }
726 
727     /**
728      * Get whether the network type is unmetered from the carrier configs.
729      *
730      * @param displayInfo The {@link TelephonyDisplayInfo} to check meteredness for.
731      * @param serviceState The {@link ServiceState}, used to determine roaming state.
732      * @return Whether the carrier considers the given display info unmetered.
733      */
isNetworkTypeUnmetered(@onNull TelephonyDisplayInfo displayInfo, @NonNull ServiceState serviceState)734     public boolean isNetworkTypeUnmetered(@NonNull TelephonyDisplayInfo displayInfo,
735             @NonNull ServiceState serviceState) {
736         String dataConfigNetworkType = getDataConfigNetworkType(displayInfo);
737         return serviceState.getDataRoaming()
738                 ? mRoamingUnmeteredNetworkTypes.contains(dataConfigNetworkType)
739                 : mUnmeteredNetworkTypes.contains(dataConfigNetworkType);
740     }
741 
742     /**
743      * Update the downlink and uplink bandwidth values from the carrier config.
744      */
updateBandwidths()745     private void updateBandwidths() {
746         synchronized (this) {
747             mBandwidthMap.clear();
748             String[] bandwidths = mCarrierConfig.getStringArray(
749                     CarrierConfigManager.KEY_BANDWIDTH_STRING_ARRAY);
750             boolean useLte = mCarrierConfig.getBoolean(CarrierConfigManager
751                     .KEY_BANDWIDTH_NR_NSA_USE_LTE_VALUE_FOR_UPLINK_BOOL);
752             if (bandwidths != null) {
753                 for (String bandwidth : bandwidths) {
754                     // split1[0] = network type as string
755                     // split1[1] = downlink,uplink
756                     String[] split1 = bandwidth.split(":");
757                     if (split1.length != 2) {
758                         loge("Invalid bandwidth: " + bandwidth);
759                         continue;
760                     }
761                     // split2[0] = downlink bandwidth in kbps
762                     // split2[1] = uplink bandwidth in kbps
763                     String[] split2 = split1[1].split(",");
764                     if (split2.length != 2) {
765                         loge("Invalid bandwidth values: " + Arrays.toString(split2));
766                         continue;
767                     }
768                     int downlink, uplink;
769                     try {
770                         downlink = Integer.parseInt(split2[0]);
771                         uplink = Integer.parseInt(split2[1]);
772                     } catch (NumberFormatException e) {
773                         loge("Exception parsing bandwidth values for network type " + split1[0]
774                                 + ": " + e);
775                         continue;
776                     }
777                     if (useLte && split1[0].startsWith("NR")) {
778                         // We can get it directly from mBandwidthMap because LTE is defined before
779                         // the NR values in CarrierConfigManager#KEY_BANDWIDTH_STRING_ARRAY.
780                         uplink = mBandwidthMap.get(DATA_CONFIG_NETWORK_TYPE_LTE)
781                                 .uplinkBandwidthKbps;
782                     }
783                     mBandwidthMap.put(split1[0],
784                             new DataNetwork.NetworkBandwidth(downlink, uplink));
785                 }
786             }
787         }
788     }
789 
790     /**
791      * Get the bandwidth estimate from the carrier config.
792      *
793      * @param displayInfo The {@link TelephonyDisplayInfo} to get the bandwidth for.
794      * @return The pre-configured bandwidth estimate from carrier config.
795      */
getBandwidthForNetworkType( @onNull TelephonyDisplayInfo displayInfo)796     public @NonNull DataNetwork.NetworkBandwidth getBandwidthForNetworkType(
797             @NonNull TelephonyDisplayInfo displayInfo) {
798         DataNetwork.NetworkBandwidth bandwidth = mBandwidthMap.get(
799                 getDataConfigNetworkType(displayInfo));
800         if (bandwidth != null) {
801             return bandwidth;
802         }
803         return new DataNetwork.NetworkBandwidth(DEFAULT_BANDWIDTH, DEFAULT_BANDWIDTH);
804     }
805 
806     /**
807      * @return Whether data throttling should be reset when the TAC changes from the carrier config.
808      */
shouldResetDataThrottlingWhenTacChanges()809     public boolean shouldResetDataThrottlingWhenTacChanges() {
810         return mCarrierConfig.getBoolean(
811                 CarrierConfigManager.KEY_UNTHROTTLE_DATA_RETRY_WHEN_TAC_CHANGES_BOOL);
812     }
813 
814     /**
815      * @return The data service package override string from the carrier config.
816      */
getDataServicePackageName()817     public String getDataServicePackageName() {
818         return mCarrierConfig.getString(
819                 CarrierConfigManager.KEY_CARRIER_DATA_SERVICE_WWAN_PACKAGE_OVERRIDE_STRING);
820     }
821 
822     /**
823      * @return The default MTU value in bytes from the carrier config.
824      */
getDefaultMtu()825     public int getDefaultMtu() {
826         return mCarrierConfig.getInt(CarrierConfigManager.KEY_DEFAULT_MTU_INT);
827     }
828 
829     /**
830      * Update the TCP buffer sizes from the resource overlays.
831      */
updateTcpBuffers()832     private void updateTcpBuffers() {
833         synchronized (this) {
834             mTcpBufferSizeMap.clear();
835             String[] configs = mResources.getStringArray(
836                     com.android.internal.R.array.config_network_type_tcp_buffers);
837             if (configs != null) {
838                 for (String config : configs) {
839                     // split[0] = network type as string
840                     // split[1] = rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max
841                     String[] split = config.split(":");
842                     if (split.length != 2) {
843                         loge("Invalid TCP buffer sizes entry: " + config);
844                         continue;
845                     }
846                     if (split[1].split(",").length != 6) {
847                         loge("Invalid TCP buffer sizes for " + split[0] + ": " + split[1]);
848                         continue;
849                     }
850                     mTcpBufferSizeMap.put(split[0], split[1]);
851                 }
852             }
853         }
854     }
855 
856     /**
857      * Anomaly report thresholds for frequent setup data call failure.
858      * @return EventFrequency to trigger the anomaly report
859      */
getAnomalySetupDataCallThreshold()860     public @NonNull EventFrequency getAnomalySetupDataCallThreshold() {
861         return mSetupDataCallAnomalyReportThreshold;
862     }
863 
864     /**
865      * Anomaly report thresholds for frequent network unwanted call
866      * at {@link TelephonyNetworkAgent#onNetworkUnwanted}
867      * @return EventFrequency to trigger the anomaly report
868      */
getAnomalyNetworkUnwantedThreshold()869     public @NonNull EventFrequency getAnomalyNetworkUnwantedThreshold() {
870         return mNetworkUnwantedAnomalyReportThreshold;
871     }
872 
873     /**
874      * Anomaly report thresholds for back to back release-request of IMS.
875      * @return EventFrequency to trigger the anomaly report
876      */
getAnomalyImsReleaseRequestThreshold()877     public @NonNull EventFrequency getAnomalyImsReleaseRequestThreshold() {
878         return mImsReleaseRequestAnomalyReportThreshold;
879     }
880 
881     /**
882      * @return {@code true} if enabled anomaly report for invalid param when QNS wants to change
883      * preferred network at {@link AccessNetworksManager}.
884      */
isInvalidQnsParamAnomalyReportEnabled()885     public boolean isInvalidQnsParamAnomalyReportEnabled() {
886         return mIsInvalidQnsParamAnomalyReportEnabled;
887     }
888 
889     /**
890      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
891      * {@link DataNetwork.ConnectingState}.
892      */
getAnomalyNetworkConnectingTimeoutMs()893     public int getAnomalyNetworkConnectingTimeoutMs() {
894         return mNetworkConnectingTimeout;
895     }
896 
897     /**
898      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
899      * {@link DataNetwork.DisconnectingState}.
900      */
getAnomalyNetworkDisconnectingTimeoutMs()901     public int getAnomalyNetworkDisconnectingTimeoutMs() {
902         return mNetworkDisconnectingTimeout;
903     }
904 
905     /**
906      * @return Timeout in ms before creating an anomaly report for a DataNetwork stuck in
907      * {@link DataNetwork.HandoverState}.
908      */
getNetworkHandoverTimeoutMs()909     public int getNetworkHandoverTimeoutMs() {
910         return mNetworkHandoverTimeout;
911     }
912 
913     /**
914      * @return {@code true} if enabled anomaly report for invalid APN config
915      * at {@link DataProfileManager}
916      */
isApnConfigAnomalyReportEnabled()917     public boolean isApnConfigAnomalyReportEnabled() {
918         return mIsApnConfigAnomalyReportEnabled;
919     }
920 
921     /**
922      * Update the network type and signal strength score table for auto data switch decisions.
923      */
updateAutoDataSwitchConfig()924     private void updateAutoDataSwitchConfig() {
925         synchronized (this) {
926             mAutoDataSwitchNetworkTypeSignalMap.clear();
927             final PersistableBundle table = mCarrierConfig.getPersistableBundle(
928                     CarrierConfigManager.KEY_AUTO_DATA_SWITCH_RAT_SIGNAL_SCORE_BUNDLE);
929             String[] networkTypeKeys = {
930                     DATA_CONFIG_NETWORK_TYPE_GPRS,
931                     DATA_CONFIG_NETWORK_TYPE_EDGE,
932                     DATA_CONFIG_NETWORK_TYPE_UMTS,
933                     DATA_CONFIG_NETWORK_TYPE_CDMA,
934                     DATA_CONFIG_NETWORK_TYPE_1xRTT,
935                     DATA_CONFIG_NETWORK_TYPE_EVDO_0,
936                     DATA_CONFIG_NETWORK_TYPE_EVDO_A,
937                     DATA_CONFIG_NETWORK_TYPE_HSDPA,
938                     DATA_CONFIG_NETWORK_TYPE_HSUPA,
939                     DATA_CONFIG_NETWORK_TYPE_HSPA,
940                     DATA_CONFIG_NETWORK_TYPE_EVDO_B,
941                     DATA_CONFIG_NETWORK_TYPE_EHRPD,
942                     DATA_CONFIG_NETWORK_TYPE_IDEN,
943                     DATA_CONFIG_NETWORK_TYPE_LTE,
944                     DATA_CONFIG_NETWORK_TYPE_HSPAP,
945                     DATA_CONFIG_NETWORK_TYPE_GSM,
946                     DATA_CONFIG_NETWORK_TYPE_TD_SCDMA,
947                     DATA_CONFIG_NETWORK_TYPE_NR_NSA,
948                     DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE,
949                     DATA_CONFIG_NETWORK_TYPE_NR_SA,
950                     DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE
951             };
952             if (table != null) {
953                 for (String networkType : networkTypeKeys) {
954                     int[] scores = table.getIntArray(networkType);
955                     if (scores != null
956                             && scores.length == SignalStrength.NUM_SIGNAL_STRENGTH_BINS) {
957                         for (int i = 0; i < scores.length; i++) {
958                             if (scores[i] < 0) {
959                                 loge("Auto switch score must not < 0 for network type "
960                                         + networkType);
961                                 break;
962                             }
963                             if (i == scores.length - 1) {
964                                 mAutoDataSwitchNetworkTypeSignalMap.put(networkType, scores);
965                             }
966                         }
967                     } else {
968                         loge("Auto switch score table should specify "
969                                 + SignalStrength.NUM_SIGNAL_STRENGTH_BINS
970                                 + " signal strength for network type " + networkType);
971                     }
972                 }
973             }
974         }
975     }
976 
977     /**
978      * @param displayInfo The displayed network info.
979      * @param signalStrength The signal strength.
980      * @return Score base on network type and signal strength to inform auto data switch decision.
981      */
getAutoDataSwitchScore(@onNull TelephonyDisplayInfo displayInfo, @NonNull SignalStrength signalStrength)982     public int getAutoDataSwitchScore(@NonNull TelephonyDisplayInfo displayInfo,
983             @NonNull SignalStrength signalStrength) {
984         int[] scores = mAutoDataSwitchNetworkTypeSignalMap.get(
985                 getDataConfigNetworkType(displayInfo));
986         return scores != null ? scores[signalStrength.getLevel()] : INVALID_AUTO_DATA_SWITCH_SCORE;
987     }
988 
989     /**
990      * @return The tolerated gap of score for auto data switch decision, larger than which the
991      * device will switch to the SIM with higher score. If 0, the device always switch to the higher
992      * score SIM. If < 0, the network type and signal strength based auto switch is disabled.
993      */
getAutoDataSwitchScoreTolerance()994     public int getAutoDataSwitchScoreTolerance() {
995         return mResources.getInteger(com.android.internal.R.integer
996                 .auto_data_switch_score_tolerance);
997     }
998 
999     /**
1000      * @return The maximum number of retries when a validation for switching failed.
1001      */
getAutoDataSwitchValidationMaxRetry()1002     public int getAutoDataSwitchValidationMaxRetry() {
1003         return mResources.getInteger(com.android.internal.R.integer
1004                 .auto_data_switch_validation_max_retry);
1005     }
1006 
1007     /**
1008      * @return Time threshold in ms to define a internet connection status to be stable
1009      * (e.g. out of service, in service, wifi is the default active network.etc), while -1 indicates
1010      * auto switch feature disabled.
1011      */
getAutoDataSwitchAvailabilityStabilityTimeThreshold()1012     public long getAutoDataSwitchAvailabilityStabilityTimeThreshold() {
1013         return mResources.getInteger(com.android.internal.R.integer
1014                 .auto_data_switch_availability_stability_time_threshold_millis);
1015     }
1016 
1017     /**
1018      * Get the TCP config string, used by {@link LinkProperties#setTcpBufferSizes(String)}.
1019      * The config string will have the following form, with values in bytes:
1020      * "read_min,read_default,read_max,write_min,write_default,write_max"
1021      *
1022      * @param displayInfo The {@link TelephonyDisplayInfo} to get the TCP config string for.
1023      * @return The TCP configuration string for the given display info or the default value from
1024      *         {@code config_tcp_buffers} if unavailable.
1025      */
getTcpConfigString(@onNull TelephonyDisplayInfo displayInfo)1026     public @NonNull String getTcpConfigString(@NonNull TelephonyDisplayInfo displayInfo) {
1027         String config = mTcpBufferSizeMap.get(getDataConfigNetworkType(displayInfo));
1028         if (TextUtils.isEmpty(config)) {
1029             config = getDefaultTcpConfigString();
1030         }
1031         return config;
1032     }
1033 
1034     /**
1035      * @return The fixed TCP buffer size configured based on the device's memory and performance.
1036      */
getDefaultTcpConfigString()1037     public @NonNull String getDefaultTcpConfigString() {
1038         return mResources.getString(com.android.internal.R.string.config_tcp_buffers);
1039     }
1040 
1041     /**
1042      * @return The delay in millisecond for IMS graceful tear down. If IMS/RCS de-registration
1043      * does not complete within the window, the data network will be torn down after timeout.
1044      */
getImsDeregistrationDelay()1045     public long getImsDeregistrationDelay() {
1046         return mResources.getInteger(
1047                 com.android.internal.R.integer.config_delay_for_ims_dereg_millis);
1048     }
1049 
1050     /**
1051      * @return {@code true} if PDN should persist when IWLAN data service restarted/crashed.
1052      * {@code false} will cause all data networks on IWLAN torn down if IWLAN data service crashes.
1053      */
shouldPersistIwlanDataNetworksWhenDataServiceRestarted()1054     public boolean shouldPersistIwlanDataNetworksWhenDataServiceRestarted() {
1055         return mResources.getBoolean(com.android.internal.R.bool
1056                 .config_wlan_data_service_conn_persistence_on_restart);
1057     }
1058 
1059     /**
1060      * @return {@code true} if adopt predefined IWLAN handover policy. If {@code false}, handover is
1061      * allowed by default.
1062      */
isIwlanHandoverPolicyEnabled()1063     public boolean isIwlanHandoverPolicyEnabled() {
1064         return mResources.getBoolean(com.android.internal.R.bool
1065                 .config_enable_iwlan_handover_policy);
1066     }
1067 
1068     /**
1069      * @return {@code true} if tearing down IMS data network should be delayed until the voice call
1070      * ends.
1071      */
isImsDelayTearDownUntilVoiceCallEndEnabled()1072     public boolean isImsDelayTearDownUntilVoiceCallEndEnabled() {
1073         return mCarrierConfig.getBoolean(
1074                 CarrierConfigManager.KEY_DELAY_IMS_TEAR_DOWN_UNTIL_CALL_END_BOOL);
1075     }
1076 
1077     /**
1078      * @return The bandwidth estimation source.
1079      */
getBandwidthEstimateSource()1080     public @DataNetwork.BandwidthEstimationSource int getBandwidthEstimateSource() {
1081         String source = mResources.getString(
1082                 com.android.internal.R.string.config_bandwidthEstimateSource);
1083         switch (source) {
1084             case BANDWIDTH_SOURCE_MODEM_STRING_VALUE:
1085                 return DataNetwork.BANDWIDTH_SOURCE_MODEM;
1086             case BANDWIDTH_SOURCE_CARRIER_CONFIG_STRING_VALUE:
1087                 return DataNetwork.BANDWIDTH_SOURCE_CARRIER_CONFIG;
1088             case BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR_STRING_VALUE:
1089                 return DataNetwork.BANDWIDTH_SOURCE_BANDWIDTH_ESTIMATOR;
1090             default:
1091                 loge("Invalid bandwidth estimation source config: " + source);
1092                 return DataNetwork.BANDWIDTH_SOURCE_UNKNOWN;
1093         }
1094     }
1095 
1096     /**
1097      * Get the {@link DataConfigNetworkType} based on the given {@link TelephonyDisplayInfo}.
1098      *
1099      * @param displayInfo The {@link TelephonyDisplayInfo} used to determine the type.
1100      * @return The equivalent {@link DataConfigNetworkType}.
1101      */
getDataConfigNetworkType( @onNull TelephonyDisplayInfo displayInfo)1102     private static @NonNull @DataConfigNetworkType String getDataConfigNetworkType(
1103             @NonNull TelephonyDisplayInfo displayInfo) {
1104         int networkType = displayInfo.getNetworkType();
1105         switch (displayInfo.getOverrideNetworkType()) {
1106             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED:
1107                 if (networkType == TelephonyManager.NETWORK_TYPE_NR) {
1108                     return DATA_CONFIG_NETWORK_TYPE_NR_SA_MMWAVE;
1109                 } else {
1110                     return DATA_CONFIG_NETWORK_TYPE_NR_NSA_MMWAVE;
1111                 }
1112             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_NSA:
1113                 return DATA_CONFIG_NETWORK_TYPE_NR_NSA;
1114             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO:
1115             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_CA:
1116                 return DATA_CONFIG_NETWORK_TYPE_LTE_CA;
1117             case TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE:
1118             default:
1119                 return networkTypeToDataConfigNetworkType(networkType);
1120         }
1121     }
1122 
1123     /** Update handover rules from carrier config. */
updateHandoverRules()1124     private void updateHandoverRules() {
1125         synchronized (this) {
1126             mHandoverRuleList.clear();
1127             String[] handoverRulesStrings = mCarrierConfig.getStringArray(
1128                     CarrierConfigManager.KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY);
1129             if (handoverRulesStrings != null) {
1130                 for (String ruleString : handoverRulesStrings) {
1131                     try {
1132                         mHandoverRuleList.add(new HandoverRule(ruleString));
1133                     } catch (IllegalArgumentException e) {
1134                         loge("updateHandoverRules: " + e.getMessage());
1135                     }
1136                 }
1137             }
1138         }
1139     }
1140 
1141     /**
1142      * Describe an event occurs eventNumOccurrence within a time span timeWindow
1143      */
1144     public static class EventFrequency {
1145         /** The time window in ms within which event occurs. */
1146         public final long timeWindow;
1147 
1148         /** The number of time the event occurs. */
1149         public final int eventNumOccurrence;
1150 
1151         /**
1152          * Constructor
1153          *
1154          * @param timeWindow The time window in ms within which event occurs.
1155          * @param eventNumOccurrence The number of time the event occurs.
1156          */
EventFrequency(long timeWindow, int eventNumOccurrence)1157         public EventFrequency(long timeWindow, int eventNumOccurrence) {
1158             this.timeWindow = timeWindow;
1159             this.eventNumOccurrence = eventNumOccurrence;
1160         }
1161 
1162         @Override
toString()1163         public String toString() {
1164             return String.format("EventFrequency=[timeWindow=%d, eventNumOccurrence=%d]",
1165                     timeWindow, eventNumOccurrence);
1166         }
1167     }
1168 
1169     /**
1170      * Parse a pair of event throttle thresholds of the form "time window in ms,occurrences"
1171      * into {@link EventFrequency}
1172      * @param s String to be parsed in the form of "time window in ms,occurrences"
1173      * @param defaultTimeWindow The time window to return if parsing failed.
1174      * @param defaultOccurrences The occurrence to return if parsing failed.
1175      * @return timeWindow and occurrence wrapped in EventFrequency
1176      */
1177     @VisibleForTesting
parseSlidingWindowCounterThreshold(String s, long defaultTimeWindow, int defaultOccurrences)1178     public EventFrequency parseSlidingWindowCounterThreshold(String s,
1179             long defaultTimeWindow, int defaultOccurrences) {
1180         EventFrequency defaultValue = new EventFrequency(defaultTimeWindow, defaultOccurrences);
1181         if (TextUtils.isEmpty(s)) return defaultValue;
1182 
1183         final String[] pair = s.split(",");
1184         if (pair.length != 2) {
1185             loge("Invalid format: " + s
1186                     + "Format should be in \"time window in ms,occurrences\". "
1187                     + "Using default instead.");
1188             return defaultValue;
1189         }
1190         long windowSpan;
1191         int occurrence;
1192         try {
1193             windowSpan = Long.parseLong(pair[0].trim());
1194         } catch (NumberFormatException e) {
1195             loge("Exception parsing SlidingWindow window span " + pair[0] + ": " + e);
1196             return defaultValue;
1197         }
1198         try {
1199             occurrence = Integer.parseInt(pair[1].trim());
1200         } catch (NumberFormatException e) {
1201             loge("Exception parsing SlidingWindow occurrence as integer " + pair[1] + ": " + e);
1202             return defaultValue;
1203         }
1204         return new EventFrequency(windowSpan, occurrence);
1205     }
1206 
1207     /**
1208      * @return Get rules for handover between IWLAN and cellular networks.
1209      *
1210      * @see CarrierConfigManager#KEY_IWLAN_HANDOVER_POLICY_STRING_ARRAY
1211      */
getHandoverRules()1212     public @NonNull List<HandoverRule> getHandoverRules() {
1213         return Collections.unmodifiableList(mHandoverRuleList);
1214     }
1215 
1216     /**
1217      * @return Get the delay in milliseconds for re-evaluating unsatisfied network requests.
1218      */
getRetrySetupAfterDisconnectMillis()1219     public long getRetrySetupAfterDisconnectMillis() {
1220         return mCarrierConfig.getLong(CarrierConfigManager
1221                 .KEY_CARRIER_DATA_CALL_APN_RETRY_AFTER_DISCONNECT_LONG);
1222     }
1223 
1224     /**
1225      * Get the data config network type for the given network type
1226      *
1227      * @param networkType The network type
1228      * @return The equivalent data config network type
1229      */
networkTypeToDataConfigNetworkType( @etworkType int networkType)1230     private static @NonNull @DataConfigNetworkType String networkTypeToDataConfigNetworkType(
1231             @NetworkType int networkType) {
1232         switch (networkType) {
1233             case TelephonyManager.NETWORK_TYPE_GPRS:
1234                 return DATA_CONFIG_NETWORK_TYPE_GPRS;
1235             case TelephonyManager.NETWORK_TYPE_EDGE:
1236                 return DATA_CONFIG_NETWORK_TYPE_EDGE;
1237             case TelephonyManager.NETWORK_TYPE_UMTS:
1238                 return DATA_CONFIG_NETWORK_TYPE_UMTS;
1239             case TelephonyManager.NETWORK_TYPE_HSDPA:
1240                 return DATA_CONFIG_NETWORK_TYPE_HSDPA;
1241             case TelephonyManager.NETWORK_TYPE_HSUPA:
1242                 return DATA_CONFIG_NETWORK_TYPE_HSUPA;
1243             case TelephonyManager.NETWORK_TYPE_HSPA:
1244                 return DATA_CONFIG_NETWORK_TYPE_HSPA;
1245             case TelephonyManager.NETWORK_TYPE_CDMA:
1246                 return DATA_CONFIG_NETWORK_TYPE_CDMA;
1247             case TelephonyManager.NETWORK_TYPE_EVDO_0:
1248                 return DATA_CONFIG_NETWORK_TYPE_EVDO_0;
1249             case TelephonyManager.NETWORK_TYPE_EVDO_A:
1250                 return DATA_CONFIG_NETWORK_TYPE_EVDO_A;
1251             case TelephonyManager.NETWORK_TYPE_EVDO_B:
1252                 return DATA_CONFIG_NETWORK_TYPE_EVDO_B;
1253             case TelephonyManager.NETWORK_TYPE_1xRTT:
1254                 return DATA_CONFIG_NETWORK_TYPE_1xRTT;
1255             case TelephonyManager.NETWORK_TYPE_LTE:
1256                 return DATA_CONFIG_NETWORK_TYPE_LTE;
1257             case TelephonyManager.NETWORK_TYPE_EHRPD:
1258                 return DATA_CONFIG_NETWORK_TYPE_EHRPD;
1259             case TelephonyManager.NETWORK_TYPE_IDEN:
1260                 return DATA_CONFIG_NETWORK_TYPE_IDEN;
1261             case TelephonyManager.NETWORK_TYPE_HSPAP:
1262                 return DATA_CONFIG_NETWORK_TYPE_HSPAP;
1263             case TelephonyManager.NETWORK_TYPE_GSM:
1264                 return DATA_CONFIG_NETWORK_TYPE_GSM;
1265             case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
1266                 return DATA_CONFIG_NETWORK_TYPE_TD_SCDMA;
1267             case TelephonyManager.NETWORK_TYPE_IWLAN:
1268                 return DATA_CONFIG_NETWORK_TYPE_IWLAN;
1269             case TelephonyManager.NETWORK_TYPE_LTE_CA:
1270                 return DATA_CONFIG_NETWORK_TYPE_LTE_CA;
1271             case TelephonyManager.NETWORK_TYPE_NR:
1272                 return DATA_CONFIG_NETWORK_TYPE_NR_SA;
1273             default:
1274                 return "";
1275         }
1276     }
1277 
1278     /**
1279      * @return Get recovery action delay in milliseconds between recovery actions.
1280      *
1281      * @see CarrierConfigManager#KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY
1282      */
getDataStallRecoveryDelayMillis()1283     public @NonNull long[] getDataStallRecoveryDelayMillis() {
1284         return mCarrierConfig.getLongArray(
1285             CarrierConfigManager.KEY_DATA_STALL_RECOVERY_TIMERS_LONG_ARRAY);
1286     }
1287 
1288     /**
1289      * @return Get the data stall recovery should skip boolean array.
1290      *
1291      * @see CarrierConfigManager#KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY
1292      */
getDataStallRecoveryShouldSkipArray()1293     public @NonNull boolean[] getDataStallRecoveryShouldSkipArray() {
1294         return mCarrierConfig.getBooleanArray(
1295             CarrierConfigManager.KEY_DATA_STALL_RECOVERY_SHOULD_SKIP_BOOL_ARRAY);
1296     }
1297 
1298     /**
1299      * @return The default preferred APN. An empty string if not configured. This is used for the
1300      * first time boot up where preferred APN is not set.
1301      */
getDefaultPreferredApn()1302     public @NonNull String getDefaultPreferredApn() {
1303         return TextUtils.emptyIfNull(mCarrierConfig.getString(
1304                 CarrierConfigManager.KEY_DEFAULT_PREFERRED_APN_NAME_STRING));
1305     }
1306 
1307     /**
1308      * @return The PCO id used for determine if data networks are using NR advanced networks. 0
1309      * indicates this feature is disabled.
1310      */
getNrAdvancedCapablePcoId()1311     public int getNrAdvancedCapablePcoId() {
1312         return mCarrierConfig.getInt(CarrierConfigManager.KEY_NR_ADVANCED_CAPABLE_PCO_ID_INT);
1313     }
1314 
1315     /**
1316      * @return The allowed APN types for initial attach. The order in the list determines the
1317      * priority of it being considered as IA APN. Note this should be only used for some exception
1318      * cases that we need to use "user-added" APN for initial attach. The regular way to configure
1319      * IA APN is by adding "IA" type to the APN in APN config.
1320      */
getAllowedInitialAttachApnTypes()1321     public @NonNull @ApnType List<Integer> getAllowedInitialAttachApnTypes() {
1322         String[] apnTypesArray = mCarrierConfig.getStringArray(
1323                 CarrierConfigManager.KEY_ALLOWED_INITIAL_ATTACH_APN_TYPES_STRING_ARRAY);
1324         if (apnTypesArray != null) {
1325             return Arrays.stream(apnTypesArray)
1326                     .map(ApnSetting::getApnTypesBitmaskFromString)
1327                     .collect(Collectors.toList());
1328         }
1329 
1330         return Collections.emptyList();
1331     }
1332 
1333     /**
1334      * @return {@code true} if enhanced IWLAN handover check is enabled. If enabled, telephony
1335      * frameworks will not perform handover if the target transport is out of service, or VoPS not
1336      * supported. The network will be torn down on the source transport, and will be
1337      * re-established on the target transport when condition is allowed for bringing up a new
1338      * network.
1339      */
isEnhancedIwlanHandoverCheckEnabled()1340     public boolean isEnhancedIwlanHandoverCheckEnabled() {
1341         return mResources.getBoolean(
1342                 com.android.internal.R.bool.config_enhanced_iwlan_handover_check);
1343     }
1344 
1345     /**
1346      * @return {@code true} if allow sending null data profile to ask modem to clear the initial
1347      * attach data profile.
1348      */
allowClearInitialAttachDataProfile()1349     public boolean allowClearInitialAttachDataProfile() {
1350         return mResources.getBoolean(
1351                 com.android.internal.R.bool.allow_clear_initial_attach_data_profile);
1352     }
1353 
1354     /**
1355      * Log debug messages.
1356      * @param s debug messages
1357      */
log(@onNull String s)1358     private void log(@NonNull String s) {
1359         Rlog.d(mLogTag, s);
1360     }
1361 
1362     /**
1363      * Log error messages.
1364      * @param s error messages
1365      */
loge(@onNull String s)1366     private void loge(@NonNull String s) {
1367         Rlog.e(mLogTag, s);
1368     }
1369 
1370     /**
1371      * Dump the state of DataConfigManager
1372      *
1373      * @param fd File descriptor
1374      * @param printWriter Print writer
1375      * @param args Arguments
1376      */
dump(FileDescriptor fd, PrintWriter printWriter, String[] args)1377     public void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
1378         IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ");
1379         pw.println(DataConfigManager.class.getSimpleName() + "-" + mPhone.getPhoneId() + ":");
1380         pw.increaseIndent();
1381         pw.println("isConfigCarrierSpecific=" + isConfigCarrierSpecific());
1382         pw.println("Network capability priority:");
1383         pw.increaseIndent();
1384         mNetworkCapabilityPriorityMap.forEach((key, value) -> pw.print(
1385                 DataUtils.networkCapabilityToString(key) + ":" + value + " "));
1386         pw.decreaseIndent();
1387         pw.println();
1388         pw.println("Data setup retry rules:");
1389         pw.increaseIndent();
1390         mDataSetupRetryRules.forEach(pw::println);
1391         pw.decreaseIndent();
1392         pw.println("isIwlanHandoverPolicyEnabled=" + isIwlanHandoverPolicyEnabled());
1393         pw.println("Data handover retry rules:");
1394         pw.increaseIndent();
1395         mDataHandoverRetryRules.forEach(pw::println);
1396         pw.decreaseIndent();
1397         pw.println("mSetupDataCallAnomalyReport=" + mSetupDataCallAnomalyReportThreshold);
1398         pw.println("mNetworkUnwantedAnomalyReport=" + mNetworkUnwantedAnomalyReportThreshold);
1399         pw.println("mImsReleaseRequestAnomalyReport=" + mImsReleaseRequestAnomalyReportThreshold);
1400         pw.println("mIsInvalidQnsParamAnomalyReportEnabled="
1401                 + mIsInvalidQnsParamAnomalyReportEnabled);
1402         pw.println("mNetworkConnectingTimeout=" + mNetworkConnectingTimeout);
1403         pw.println("mNetworkDisconnectingTimeout=" + mNetworkDisconnectingTimeout);
1404         pw.println("mNetworkHandoverTimeout=" + mNetworkHandoverTimeout);
1405         pw.println("mIsApnConfigAnomalyReportEnabled=" + mIsApnConfigAnomalyReportEnabled);
1406         pw.println("Auto data switch:");
1407         pw.increaseIndent();
1408         pw.println("getAutoDataSwitchScoreTolerance=" + getAutoDataSwitchScoreTolerance());
1409         mAutoDataSwitchNetworkTypeSignalMap.forEach((key, value) -> pw.println(key + ":"
1410                 + Arrays.toString(value)));
1411         pw.println("getAutoDataSwitchAvailabilityStabilityTimeThreshold="
1412                 + getAutoDataSwitchAvailabilityStabilityTimeThreshold());
1413         pw.println("getAutoDataSwitchValidationMaxRetry=" + getAutoDataSwitchValidationMaxRetry());
1414         pw.decreaseIndent();
1415         pw.println("Metered APN types=" + mMeteredApnTypes.stream()
1416                 .map(ApnSetting::getApnTypeString).collect(Collectors.joining(",")));
1417         pw.println("Roaming metered APN types=" + mRoamingMeteredApnTypes.stream()
1418                 .map(ApnSetting::getApnTypeString).collect(Collectors.joining(",")));
1419         pw.println("Single data network types=" + mSingleDataNetworkTypeList.stream()
1420                 .map(TelephonyManager::getNetworkTypeName).collect(Collectors.joining(",")));
1421         pw.println("Capabilities exempt from single PDN=" + mCapabilitiesExemptFromSingleDataList
1422                 .stream().map(DataUtils::networkCapabilityToString)
1423                 .collect(Collectors.joining(",")));
1424         pw.println("mShouldKeepNetworkUpInNoVops=" + mShouldKeepNetworkUpInNonVops);
1425         pw.println("isPingTestBeforeAutoDataSwitchRequired="
1426                 + isPingTestBeforeAutoDataSwitchRequired());
1427         pw.println("Unmetered network types=" + String.join(",", mUnmeteredNetworkTypes));
1428         pw.println("Roaming unmetered network types="
1429                 + String.join(",", mRoamingUnmeteredNetworkTypes));
1430         pw.println("Bandwidths:");
1431         pw.increaseIndent();
1432         mBandwidthMap.forEach((key, value) -> pw.println(key + ":" + value));
1433         pw.decreaseIndent();
1434         pw.println("shouldUseDataActivityForRrcDetection="
1435                 + shouldUseDataActivityForRrcDetection());
1436         pw.println("isTempNotMeteredSupportedByCarrier=" + isTempNotMeteredSupportedByCarrier());
1437         pw.println("shouldResetDataThrottlingWhenTacChanges="
1438                 + shouldResetDataThrottlingWhenTacChanges());
1439         pw.println("Data service package name=" + getDataServicePackageName());
1440         pw.println("Default MTU=" + getDefaultMtu());
1441         pw.println("TCP buffer sizes by RAT:");
1442         pw.increaseIndent();
1443         mTcpBufferSizeMap.forEach((key, value) -> pw.println(key + ":" + value));
1444         pw.decreaseIndent();
1445         pw.println("Default TCP buffer sizes=" + getDefaultTcpConfigString());
1446         pw.println("getImsDeregistrationDelay=" + getImsDeregistrationDelay());
1447         pw.println("shouldPersistIwlanDataNetworksWhenDataServiceRestarted="
1448                 + shouldPersistIwlanDataNetworksWhenDataServiceRestarted());
1449         pw.println("Bandwidth estimation source=" + mResources.getString(
1450                 com.android.internal.R.string.config_bandwidthEstimateSource));
1451         pw.println("isImsDelayTearDownUntilVoiceCallEndEnabled="
1452                 + isImsDelayTearDownUntilVoiceCallEndEnabled());
1453         pw.println("isEnhancedIwlanHandoverCheckEnabled=" + isEnhancedIwlanHandoverCheckEnabled());
1454         pw.println("isTetheringProfileDisabledForRoaming="
1455                 + isTetheringProfileDisabledForRoaming());
1456         pw.println("allowClearInitialAttachDataProfile=" + allowClearInitialAttachDataProfile());
1457         pw.decreaseIndent();
1458     }
1459 }
1460