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