c6b4708f631c8e8db01a206b5703d23b58d97e19
[android/platform/frameworks/opt/telephony.git] / src / java / com / android / internal / telephony / dataconnection / DcTracker.java
1 /*
2  * Copyright (C) 2006 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.dataconnection;
18
19 import android.app.AlarmManager;
20 import android.app.PendingIntent;
21 import android.app.ProgressDialog;
22 import android.content.ActivityNotFoundException;
23 import android.content.BroadcastReceiver;
24 import android.content.ContentResolver;
25 import android.content.ContentValues;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.IntentFilter;
29 import android.content.res.Resources;
30 import android.database.ContentObserver;
31 import android.database.Cursor;
32 import android.net.ConnectivityManager;
33 import android.net.LinkProperties;
34 import android.net.NetworkCapabilities;
35 import android.net.NetworkConfig;
36 import android.net.NetworkUtils;
37 import android.net.ProxyInfo;
38 import android.net.Uri;
39 import android.os.AsyncResult;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.Handler;
43 import android.os.Message;
44 import android.os.RegistrantList;
45 import android.os.ServiceManager;
46 import android.os.SystemClock;
47 import android.os.SystemProperties;
48 import android.os.UserHandle;
49 import android.provider.Settings;
50 import android.provider.Telephony;
51 import android.telephony.CellLocation;
52 import android.telephony.ServiceState;
53 import android.telephony.TelephonyManager;
54 import android.telephony.SubscriptionManager;
55 import android.telephony.cdma.CdmaCellLocation;
56 import android.telephony.gsm.GsmCellLocation;
57 import android.text.TextUtils;
58 import android.util.EventLog;
59 import android.view.WindowManager;
60 import android.telephony.Rlog;
61
62 import com.android.internal.telephony.cdma.CDMALTEPhone;
63 import com.android.internal.telephony.Phone;
64 import com.android.internal.telephony.PhoneBase;
65 import com.android.internal.telephony.DctConstants;
66 import com.android.internal.telephony.EventLogTags;
67 import com.android.internal.telephony.ITelephony;
68 import com.android.internal.telephony.TelephonyIntents;
69 import com.android.internal.telephony.gsm.GSMPhone;
70 import com.android.internal.telephony.PhoneConstants;
71 import com.android.internal.telephony.RILConstants;
72 import com.android.internal.telephony.uicc.IccRecords;
73 import com.android.internal.telephony.uicc.UiccController;
74 import com.android.internal.util.AsyncChannel;
75 import com.android.internal.util.ArrayUtils;
76
77 import java.io.FileDescriptor;
78 import java.io.PrintWriter;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.concurrent.atomic.AtomicBoolean;
82 import java.util.Objects;
83 import java.lang.StringBuilder;
84
85 import com.android.internal.telephony.ServiceStateTracker;
86 /**
87  * {@hide}
88  */
89 public final class DcTracker extends DcTrackerBase {
90     protected final String LOG_TAG = "DCT";
91
92     /**
93      * List of messages that are waiting to be posted, when data call disconnect
94      * is complete
95      */
96     private ArrayList<Message> mDisconnectAllCompleteMsgList = new ArrayList<Message>();
97
98     private RegistrantList mAllDataDisconnectedRegistrants = new RegistrantList();
99
100     protected int mDisconnectPendingCount = 0;
101
102     /**
103      * Handles changes to the APN db.
104      */
105     private class ApnChangeObserver extends ContentObserver {
106         public ApnChangeObserver () {
107             super(mDataConnectionTracker);
108         }
109
110         @Override
111         public void onChange(boolean selfChange) {
112             sendMessage(obtainMessage(DctConstants.EVENT_APN_CHANGED));
113         }
114     }
115
116     //***** Instance Variables
117
118     private boolean mReregisterOnReconnectFailure = false;
119
120
121     //***** Constants
122
123     // Used by puppetmaster/*/radio_stress.py
124     private static final String PUPPET_MASTER_RADIO_STRESS_TEST = "gsm.defaultpdpcontext.active";
125
126     private static final int POLL_PDP_MILLIS = 5 * 1000;
127
128     private static final int PROVISIONING_SPINNER_TIMEOUT_MILLIS = 120 * 1000;
129
130     static final Uri PREFERAPN_NO_UPDATE_URI_USING_SUBID =
131                         Uri.parse("content://telephony/carriers/preferapn_no_update/subId/");
132     static final String APN_ID = "apn_id";
133
134     private boolean mCanSetPreferApn = false;
135
136     private AtomicBoolean mAttached = new AtomicBoolean(false);
137
138     /** Watches for changes to the APN db. */
139     private ApnChangeObserver mApnObserver;
140
141     private final String mProvisionActionName;
142     private BroadcastReceiver mProvisionBroadcastReceiver;
143     private ProgressDialog mProvisioningSpinner;
144
145     public boolean mImsRegistrationState = false;
146     private ApnContext mWaitCleanUpApnContext = null;
147     private boolean mDeregistrationAlarmState = false;
148     private PendingIntent mImsDeregistrationDelayIntent = null;
149
150     //***** Constructor
151     public DcTracker(PhoneBase p) {
152         super(p);
153         if (DBG) log("GsmDCT.constructor");
154
155         mDataConnectionTracker = this;
156         update();
157         mApnObserver = new ApnChangeObserver();
158         p.getContext().getContentResolver().registerContentObserver(
159                 Telephony.Carriers.CONTENT_URI, true, mApnObserver);
160
161         initApnContexts();
162
163         for (ApnContext apnContext : mApnContexts.values()) {
164             // Register the reconnect and restart actions.
165             IntentFilter filter = new IntentFilter();
166             filter.addAction(INTENT_RECONNECT_ALARM + '.' + apnContext.getApnType());
167             filter.addAction(INTENT_RESTART_TRYSETUP_ALARM + '.' + apnContext.getApnType());
168             mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
169         }
170
171         // Add Emergency APN to APN setting list by default to support EPDN in sim absent cases
172         initEmergencyApnSetting();
173         addEmergencyApnSetting();
174
175         mProvisionActionName = "com.android.internal.telephony.PROVISION" + p.getPhoneId();
176     }
177
178     protected void registerForAllEvents() {
179         mPhone.mCi.registerForAvailable(this, DctConstants.EVENT_RADIO_AVAILABLE, null);
180         mPhone.mCi.registerForOffOrNotAvailable(this,
181                DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
182         mPhone.mCi.registerForDataNetworkStateChanged(this,
183                DctConstants.EVENT_DATA_STATE_CHANGED, null);
184         // Note, this is fragile - the Phone is now presenting a merged picture
185         // of PS (volte) & CS and by diving into its internals you're just seeing
186         // the CS data.  This works well for the purposes this is currently used for
187         // but that may not always be the case.  Should probably be redesigned to
188         // accurately reflect what we're really interested in (registerForCSVoiceCallEnded).
189         mPhone.getCallTracker().registerForVoiceCallEnded (this,
190                DctConstants.EVENT_VOICE_CALL_ENDED, null);
191         mPhone.getCallTracker().registerForVoiceCallStarted (this,
192                DctConstants.EVENT_VOICE_CALL_STARTED, null);
193         mPhone.getServiceStateTracker().registerForDataConnectionAttached(this,
194                DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null);
195         mPhone.getServiceStateTracker().registerForDataConnectionDetached(this,
196                DctConstants.EVENT_DATA_CONNECTION_DETACHED, null);
197         mPhone.getServiceStateTracker().registerForDataRoamingOn(this,
198                DctConstants.EVENT_ROAMING_ON, null);
199         mPhone.getServiceStateTracker().registerForDataRoamingOff(this,
200                DctConstants.EVENT_ROAMING_OFF, null);
201         mPhone.getServiceStateTracker().registerForPsRestrictedEnabled(this,
202                 DctConstants.EVENT_PS_RESTRICT_ENABLED, null);
203         mPhone.getServiceStateTracker().registerForPsRestrictedDisabled(this,
204                 DctConstants.EVENT_PS_RESTRICT_DISABLED, null);
205      //   SubscriptionManager.registerForDdsSwitch(this,
206      //          DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS, null);
207         mPhone.getServiceStateTracker().registerForDataRegStateOrRatChanged(this,
208                 DctConstants.EVENT_DATA_RAT_CHANGED, null);
209     }
210     @Override
211     public void dispose() {
212         if (DBG) log("DcTracker.dispose");
213
214         if (mProvisionBroadcastReceiver != null) {
215             mPhone.getContext().unregisterReceiver(mProvisionBroadcastReceiver);
216             mProvisionBroadcastReceiver = null;
217         }
218         if (mProvisioningSpinner != null) {
219             mProvisioningSpinner.dismiss();
220             mProvisioningSpinner = null;
221         }
222
223         cleanUpAllConnections(true, null);
224
225         super.dispose();
226
227         mPhone.getContext().getContentResolver().unregisterContentObserver(mApnObserver);
228         mApnContexts.clear();
229         mPrioritySortedApnContexts.clear();
230
231         destroyDataConnections();
232     }
233     protected void unregisterForAllEvents() {
234          //Unregister for all events
235         mPhone.mCi.unregisterForAvailable(this);
236         mPhone.mCi.unregisterForOffOrNotAvailable(this);
237         IccRecords r = mIccRecords.get();
238         if (r != null) {
239             r.unregisterForRecordsLoaded(this);
240             mIccRecords.set(null);
241         }
242         mPhone.mCi.unregisterForDataNetworkStateChanged(this);
243         mPhone.getCallTracker().unregisterForVoiceCallEnded(this);
244         mPhone.getCallTracker().unregisterForVoiceCallStarted(this);
245         mPhone.getServiceStateTracker().unregisterForDataConnectionAttached(this);
246         mPhone.getServiceStateTracker().unregisterForDataConnectionDetached(this);
247         mPhone.getServiceStateTracker().unregisterForDataRoamingOn(this);
248         mPhone.getServiceStateTracker().unregisterForDataRoamingOff(this);
249         mPhone.getServiceStateTracker().unregisterForPsRestrictedEnabled(this);
250         mPhone.getServiceStateTracker().unregisterForPsRestrictedDisabled(this);
251         //SubscriptionManager.unregisterForDdsSwitch(this);
252     }
253
254     @Override
255     public void incApnRefCount(String name) {
256         ApnContext apnContext = mApnContexts.get(name);
257         if (apnContext != null) {
258             apnContext.incRefCount();
259         }
260     }
261
262     @Override
263     public void decApnRefCount(String name) {
264         ApnContext apnContext = mApnContexts.get(name);
265         if (apnContext != null) {
266             apnContext.decRefCount();
267         }
268     }
269
270     @Override
271     public boolean isApnSupported(String name) {
272         if (name == null) {
273             loge("isApnSupported: name=null");
274             return false;
275         }
276         ApnContext apnContext = mApnContexts.get(name);
277         if (apnContext == null) {
278             loge("Request for unsupported mobile name: " + name);
279             return false;
280         }
281         return true;
282     }
283
284     @Override
285     public int getApnPriority(String name) {
286         ApnContext apnContext = mApnContexts.get(name);
287         if (apnContext == null) {
288             loge("Request for unsupported mobile name: " + name);
289         }
290         return apnContext.priority;
291     }
292
293     // Turn telephony radio on or off.
294     private void setRadio(boolean on) {
295         final ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
296         try {
297             phone.setRadio(on);
298         } catch (Exception e) {
299             // Ignore.
300         }
301     }
302
303     // Class to handle Intent dispatched with user selects the "Sign-in to network"
304     // notification.
305     private class ProvisionNotificationBroadcastReceiver extends BroadcastReceiver {
306         private final String mNetworkOperator;
307         // Mobile provisioning URL.  Valid while provisioning notification is up.
308         // Set prior to notification being posted as URL contains ICCID which
309         // disappears when radio is off (which is the case when notification is up).
310         private final String mProvisionUrl;
311
312         public ProvisionNotificationBroadcastReceiver(String provisionUrl, String networkOperator) {
313             mNetworkOperator = networkOperator;
314             mProvisionUrl = provisionUrl;
315         }
316
317         private void setEnableFailFastMobileData(int enabled) {
318             sendMessage(obtainMessage(DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA, enabled, 0));
319         }
320
321         private void enableMobileProvisioning() {
322             final Message msg = obtainMessage(DctConstants.CMD_ENABLE_MOBILE_PROVISIONING);
323             msg.setData(Bundle.forPair(DctConstants.PROVISIONING_URL_KEY, mProvisionUrl));
324             sendMessage(msg);
325         }
326
327         @Override
328         public void onReceive(Context context, Intent intent) {
329             // Turning back on the radio can take time on the order of a minute, so show user a
330             // spinner so they know something is going on.
331             mProvisioningSpinner = new ProgressDialog(context);
332             mProvisioningSpinner.setTitle(mNetworkOperator);
333             mProvisioningSpinner.setMessage(
334                     // TODO: Don't borrow "Connecting..." i18n string; give Telephony a version.
335                     context.getText(com.android.internal.R.string.media_route_status_connecting));
336             mProvisioningSpinner.setIndeterminate(true);
337             mProvisioningSpinner.setCancelable(true);
338             // Allow non-Activity Service Context to create a View.
339             mProvisioningSpinner.getWindow().setType(
340                     WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
341             mProvisioningSpinner.show();
342             // After timeout, hide spinner so user can at least use their device.
343             // TODO: Indicate to user that it is taking an unusually long time to connect?
344             sendMessageDelayed(obtainMessage(DctConstants.CMD_CLEAR_PROVISIONING_SPINNER,
345                     mProvisioningSpinner), PROVISIONING_SPINNER_TIMEOUT_MILLIS);
346             // This code is almost identical to the old
347             // ConnectivityService.handleMobileProvisioningAction code.
348             setRadio(true);
349             setEnableFailFastMobileData(DctConstants.ENABLED);
350             enableMobileProvisioning();
351         }
352     }
353
354     @Override
355     public boolean isApnTypeActive(String type) {
356         ApnContext apnContext = mApnContexts.get(type);
357         if (apnContext == null) return false;
358
359         return (apnContext.getDcAc() != null);
360     }
361
362     @Override
363     public boolean isDataPossible(String apnType) {
364         ApnContext apnContext = mApnContexts.get(apnType);
365         if (apnContext == null) {
366             return false;
367         }
368         boolean apnContextIsEnabled = apnContext.isEnabled();
369         DctConstants.State apnContextState = apnContext.getState();
370         boolean apnTypePossible = !(apnContextIsEnabled &&
371                 (apnContextState == DctConstants.State.FAILED));
372         boolean isEmergencyApn = apnContext.getApnType().equals(PhoneConstants.APN_TYPE_EMERGENCY);
373         // Set the emergency APN availability status as TRUE irrespective of conditions checked in
374         // isDataAllowed() like IN_SERVICE, MOBILE DATA status etc.
375         boolean dataAllowed = isEmergencyApn || isDataAllowed();
376         boolean possible = dataAllowed && apnTypePossible;
377
378         if ((apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
379                     || apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IA))
380                 && (mPhone.getServiceState().getRilDataRadioTechnology()
381                 == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN)) {
382             log("Default data call activation not possible in iwlan.");
383             possible = false;
384         }
385
386         if (VDBG) {
387             log(String.format("isDataPossible(%s): possible=%b isDataAllowed=%b " +
388                     "apnTypePossible=%b apnContextisEnabled=%b apnContextState()=%s",
389                     apnType, possible, dataAllowed, apnTypePossible,
390                     apnContextIsEnabled, apnContextState));
391         }
392         return possible;
393     }
394
395     @Override
396     protected void finalize() {
397         if(DBG) log("finalize");
398     }
399
400     private ApnContext addApnContext(String type, NetworkConfig networkConfig) {
401         ApnContext apnContext = new ApnContext(mPhone.getContext(), type, LOG_TAG, networkConfig,
402                 this);
403         mApnContexts.put(type, apnContext);
404         mPrioritySortedApnContexts.add(apnContext);
405         return apnContext;
406     }
407
408     protected void initApnContexts() {
409         log("initApnContexts: E");
410         // Load device network attributes from resources
411         String[] networkConfigStrings = mPhone.getContext().getResources().getStringArray(
412                 com.android.internal.R.array.networkAttributes);
413         for (String networkConfigString : networkConfigStrings) {
414             NetworkConfig networkConfig = new NetworkConfig(networkConfigString);
415             ApnContext apnContext = null;
416
417             switch (networkConfig.type) {
418             case ConnectivityManager.TYPE_MOBILE:
419                 apnContext = addApnContext(PhoneConstants.APN_TYPE_DEFAULT, networkConfig);
420                 break;
421             case ConnectivityManager.TYPE_MOBILE_MMS:
422                 apnContext = addApnContext(PhoneConstants.APN_TYPE_MMS, networkConfig);
423                 break;
424             case ConnectivityManager.TYPE_MOBILE_SUPL:
425                 apnContext = addApnContext(PhoneConstants.APN_TYPE_SUPL, networkConfig);
426                 break;
427             case ConnectivityManager.TYPE_MOBILE_DUN:
428                 apnContext = addApnContext(PhoneConstants.APN_TYPE_DUN, networkConfig);
429                 break;
430             case ConnectivityManager.TYPE_MOBILE_HIPRI:
431                 apnContext = addApnContext(PhoneConstants.APN_TYPE_HIPRI, networkConfig);
432                 break;
433             case ConnectivityManager.TYPE_MOBILE_FOTA:
434                 apnContext = addApnContext(PhoneConstants.APN_TYPE_FOTA, networkConfig);
435                 break;
436             case ConnectivityManager.TYPE_MOBILE_IMS:
437                 apnContext = addApnContext(PhoneConstants.APN_TYPE_IMS, networkConfig);
438                 break;
439             case ConnectivityManager.TYPE_MOBILE_CBS:
440                 apnContext = addApnContext(PhoneConstants.APN_TYPE_CBS, networkConfig);
441                 break;
442             case ConnectivityManager.TYPE_MOBILE_IA:
443                 apnContext = addApnContext(PhoneConstants.APN_TYPE_IA, networkConfig);
444                 break;
445             case ConnectivityManager.TYPE_MOBILE_EMERGENCY:
446                 apnContext = addApnContext(PhoneConstants.APN_TYPE_EMERGENCY, networkConfig);
447                 break;
448             default:
449                 log("initApnContexts: skipping unknown type=" + networkConfig.type);
450                 continue;
451             }
452             log("initApnContexts: apnContext=" + apnContext);
453         }
454         log("initApnContexts: X mApnContexts=" + mApnContexts);
455     }
456
457     @Override
458     public LinkProperties getLinkProperties(String apnType) {
459         ApnContext apnContext = mApnContexts.get(apnType);
460         if (apnContext != null) {
461             DcAsyncChannel dcac = apnContext.getDcAc();
462             if (dcac != null) {
463                 if (DBG) log("return link properites for " + apnType);
464                 return dcac.getLinkPropertiesSync();
465             }
466         }
467         if (DBG) log("return new LinkProperties");
468         return new LinkProperties();
469     }
470
471     @Override
472     public NetworkCapabilities getNetworkCapabilities(String apnType) {
473         ApnContext apnContext = mApnContexts.get(apnType);
474         if (apnContext!=null) {
475             DcAsyncChannel dataConnectionAc = apnContext.getDcAc();
476             if (dataConnectionAc != null) {
477                 if (DBG) {
478                     log("get active pdp is not null, return NetworkCapabilities for " + apnType);
479                 }
480                 return dataConnectionAc.getNetworkCapabilitiesSync();
481             }
482         }
483         if (DBG) log("return new NetworkCapabilities");
484         return new NetworkCapabilities();
485     }
486
487     @Override
488     // Return all active apn types
489     public String[] getActiveApnTypes() {
490         if (DBG) log("get all active apn types");
491         ArrayList<String> result = new ArrayList<String>();
492
493         for (ApnContext apnContext : mApnContexts.values()) {
494             if (mAttached.get() && apnContext.isReady()) {
495                 result.add(apnContext.getApnType());
496             }
497         }
498
499         return result.toArray(new String[0]);
500     }
501
502     @Override
503     // Return active apn of specific apn type
504     public String getActiveApnString(String apnType) {
505         if (VDBG) log( "get active apn string for type:" + apnType);
506         ApnContext apnContext = mApnContexts.get(apnType);
507         if (apnContext != null) {
508             ApnSetting apnSetting = apnContext.getApnSetting();
509             if (apnSetting != null) {
510                 return apnSetting.apn;
511             }
512         }
513         return null;
514     }
515
516     @Override
517     public boolean isApnTypeEnabled(String apnType) {
518         ApnContext apnContext = mApnContexts.get(apnType);
519         if (apnContext == null) {
520             return false;
521         }
522         return apnContext.isEnabled();
523     }
524
525     @Override
526     protected void setState(DctConstants.State s) {
527         if (DBG) log("setState should not be used in GSM" + s);
528     }
529
530     // Return state of specific apn type
531     @Override
532     public DctConstants.State getState(String apnType) {
533         ApnContext apnContext = mApnContexts.get(apnType);
534         if (apnContext != null) {
535             return apnContext.getState();
536         }
537         return DctConstants.State.FAILED;
538     }
539
540     // Return if apn type is a provisioning apn.
541     @Override
542     protected boolean isProvisioningApn(String apnType) {
543         ApnContext apnContext = mApnContexts.get(apnType);
544         if (apnContext != null) {
545             return apnContext.isProvisioningApn();
546         }
547         return false;
548     }
549
550     // Return state of overall
551     @Override
552     public DctConstants.State getOverallState() {
553         boolean isConnecting = false;
554         boolean isFailed = true; // All enabled Apns should be FAILED.
555         boolean isAnyEnabled = false;
556
557         for (ApnContext apnContext : mApnContexts.values()) {
558             if (apnContext.isEnabled()) {
559                 isAnyEnabled = true;
560                 switch (apnContext.getState()) {
561                 case CONNECTED:
562                 case DISCONNECTING:
563                     if (DBG) log("overall state is CONNECTED");
564                     return DctConstants.State.CONNECTED;
565                 case RETRYING:
566                 case CONNECTING:
567                     isConnecting = true;
568                     isFailed = false;
569                     break;
570                 case IDLE:
571                 case SCANNING:
572                     isFailed = false;
573                     break;
574                 default:
575                     isAnyEnabled = true;
576                     break;
577                 }
578             }
579         }
580
581         if (!isAnyEnabled) { // Nothing enabled. return IDLE.
582             if (DBG) log( "overall state is IDLE");
583             return DctConstants.State.IDLE;
584         }
585
586         if (isConnecting) {
587             if (DBG) log( "overall state is CONNECTING");
588             return DctConstants.State.CONNECTING;
589         } else if (!isFailed) {
590             if (DBG) log( "overall state is IDLE");
591             return DctConstants.State.IDLE;
592         } else {
593             if (DBG) log( "overall state is FAILED");
594             return DctConstants.State.FAILED;
595         }
596     }
597
598     @Override
599     protected boolean isApnTypeAvailable(String type) {
600         if (type.equals(PhoneConstants.APN_TYPE_DUN) && fetchDunApn() != null) {
601             return true;
602         }
603
604         if (mAllApnSettings != null) {
605             for (ApnSetting apn : mAllApnSettings) {
606                 if (apn.canHandleType(type)) {
607                     return true;
608                 }
609             }
610         }
611         return false;
612     }
613
614     /**
615      * Report on whether data connectivity is enabled for any APN.
616      * @return {@code false} if data connectivity has been explicitly disabled,
617      * {@code true} otherwise.
618      */
619     @Override
620     public boolean getAnyDataEnabled() {
621         synchronized (mDataEnabledLock) {
622             if (!(mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled)) return false;
623             for (ApnContext apnContext : mApnContexts.values()) {
624                 // Make sure we don't have a context that is going down
625                 // and is explicitly disabled.
626                 if (isDataAllowed(apnContext)) {
627                     return true;
628                 }
629             }
630             return false;
631         }
632     }
633
634     public boolean getAnyDataEnabled(boolean checkUserDataEnabled) {
635         synchronized (mDataEnabledLock) {
636             if (!(mInternalDataEnabled && (!checkUserDataEnabled || mUserDataEnabled)
637                         && (!checkUserDataEnabled || sPolicyDataEnabled)))
638                 return false;
639
640             for (ApnContext apnContext : mApnContexts.values()) {
641                 // Make sure we dont have a context that going down
642                 // and is explicitly disabled.
643                 if (isDataAllowed(apnContext)) {
644                     return true;
645                 }
646             }
647             return false;
648         }
649     }
650
651     private boolean isDataAllowed(ApnContext apnContext) {
652         //If RAT is iwlan then dont allow default/IA PDP at all.
653         //Rest of APN types can be evaluated for remaining conditions.
654         if ((apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
655                     || apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IA))
656                 && (mPhone.getServiceState().getRilDataRadioTechnology()
657                 == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN)) {
658             log("Default data call activation not allowed in iwlan.");
659             return false;
660         } else {
661             return apnContext.isReady() && isDataAllowed();
662         }
663     }
664
665     //****** Called from ServiceStateTracker
666     /**
667      * Invoked when ServiceStateTracker observes a transition from GPRS
668      * attach to detach.
669      */
670     protected void onDataConnectionDetached() {
671         /*
672          * We presently believe it is unnecessary to tear down the PDP context
673          * when GPRS detaches, but we should stop the network polling.
674          */
675         if (DBG) log ("onDataConnectionDetached: stop polling and notify detached");
676         stopNetStatPoll();
677         stopDataStallAlarm();
678         notifyDataConnection(Phone.REASON_DATA_DETACHED);
679         mAttached.set(false);
680     }
681
682     private void onDataConnectionAttached() {
683         if (DBG) log("onDataConnectionAttached");
684         mAttached.set(true);
685         if (getOverallState() == DctConstants.State.CONNECTED) {
686             if (DBG) log("onDataConnectionAttached: start polling notify attached");
687             startNetStatPoll();
688             startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
689             notifyDataConnection(Phone.REASON_DATA_ATTACHED);
690         } else {
691             // update APN availability so that APN can be enabled.
692             notifyOffApnsOfAvailability(Phone.REASON_DATA_ATTACHED);
693         }
694         if (mAutoAttachOnCreationConfig) {
695             mAutoAttachOnCreation = true;
696         }
697         setupDataOnConnectableApns(Phone.REASON_DATA_ATTACHED);
698     }
699
700     @Override
701     protected boolean isDataAllowed() {
702         final boolean internalDataEnabled;
703         synchronized (mDataEnabledLock) {
704             internalDataEnabled = mInternalDataEnabled;
705         }
706
707         boolean attachedState = mAttached.get();
708         boolean desiredPowerState = mPhone.getServiceStateTracker().getDesiredPowerState();
709         int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
710         if (radioTech == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN) {
711             desiredPowerState = true;
712         }
713
714         IccRecords r = mIccRecords.get();
715         boolean recordsLoaded = false;
716         if (r != null) {
717             recordsLoaded = r.getRecordsLoaded();
718             if (DBG) log("isDataAllowed getRecordsLoaded=" + recordsLoaded);
719         }
720
721         //FIXME always attach
722         boolean psRestricted = mIsPsRestricted;
723         int phoneNum = TelephonyManager.getDefault().getPhoneCount();
724         if (phoneNum > 1) {
725             attachedState = true;
726             psRestricted = false;
727         }
728         int dataSub = SubscriptionManager.getDefaultDataSubId();
729         boolean defaultDataSelected = SubscriptionManager.isValidSubscriptionId(dataSub);
730         PhoneConstants.State state = PhoneConstants.State.IDLE;
731         // Note this is explicitly not using mPhone.getState.  See b/19090488.
732         // mPhone.getState reports the merge of CS and PS (volte) voice call state
733         // but we only care about CS calls here for data/voice concurrency issues.
734         // Calling getCallTracker currently gives you just the CS side where the
735         // ImsCallTracker is held internally where applicable.
736         // This should be redesigned to ask explicitly what we want:
737         // voiceCallStateAllowDataCall, or dataCallAllowed or something similar.
738         if (mPhone.getCallTracker() != null) {
739             state = mPhone.getCallTracker().getState();
740         }
741         boolean allowed =
742                     (attachedState || mAutoAttachOnCreation) &&
743                     recordsLoaded &&
744                     (state == PhoneConstants.State.IDLE ||
745                      mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) &&
746                     internalDataEnabled &&
747                     defaultDataSelected &&
748                     (!mPhone.getServiceState().getDataRoaming() || getDataOnRoamingEnabled()) &&
749                     //!mIsPsRestricted &&
750                     !psRestricted &&
751                     desiredPowerState;
752         if (!allowed && DBG) {
753             String reason = "";
754             if (!(attachedState || mAutoAttachOnCreation)) {
755                 reason += " - Attached= " + attachedState;
756             }
757             if (!recordsLoaded) reason += " - SIM not loaded";
758             if (state != PhoneConstants.State.IDLE &&
759                     !mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
760                 reason += " - PhoneState= " + state;
761                 reason += " - Concurrent voice and data not allowed";
762             }
763             if (!internalDataEnabled) reason += " - mInternalDataEnabled= false";
764             if (!defaultDataSelected) reason += " - defaultDataSelected= false";
765             if (mPhone.getServiceState().getDataRoaming() && !getDataOnRoamingEnabled()) {
766                 reason += " - Roaming and data roaming not enabled";
767             }
768             if (mIsPsRestricted) reason += " - mIsPsRestricted= true";
769             if (!desiredPowerState) reason += " - desiredPowerState= false";
770             if (DBG) log("isDataAllowed: not allowed due to" + reason);
771         }
772         return allowed;
773     }
774
775     // arg for setupDataOnConnectableApns
776     private enum RetryFailures {
777         // retry failed networks always (the old default)
778         ALWAYS,
779         // retry only when a substantial change has occured.  Either:
780         // 1) we were restricted by voice/data concurrency and aren't anymore
781         // 2) our apn list has change
782         ONLY_ON_CHANGE
783     };
784
785     private void setupDataOnConnectableApns(String reason) {
786         setupDataOnConnectableApns(reason, RetryFailures.ALWAYS);
787     }
788
789     private void setupDataOnConnectableApns(String reason, RetryFailures retryFailures) {
790         if (DBG) log("setupDataOnConnectableApns: " + reason);
791
792         for (ApnContext apnContext : mPrioritySortedApnContexts) {
793             ArrayList<ApnSetting> waitingApns = null;
794
795             if (DBG) log("setupDataOnConnectableApns: apnContext " + apnContext);
796             if (apnContext.getState() == DctConstants.State.FAILED
797                     || apnContext.getState() == DctConstants.State.RETRYING) {
798                 if (retryFailures == RetryFailures.ALWAYS) {
799                     apnContext.setState(DctConstants.State.IDLE);
800                 } else if (apnContext.isConcurrentVoiceAndDataAllowed() == false &&
801                          mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
802                     // RetryFailures.ONLY_ON_CHANGE - check if voice concurrency has changed
803                     apnContext.setState(DctConstants.State.IDLE);
804                 } else {
805                     // RetryFailures.ONLY_ON_CHANGE - check if the apns have changed
806                     int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
807                     ArrayList<ApnSetting> originalApns = apnContext.getOriginalWaitingApns();
808                     if (originalApns != null && originalApns.isEmpty() == false) {
809                         waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
810                         if (originalApns.size() != waitingApns.size() ||
811                                 originalApns.containsAll(waitingApns) == false) {
812                             apnContext.setState(DctConstants.State.IDLE);
813                         }
814                     }
815                 }
816             }
817             if (apnContext.isConnectable()) {
818                 log("setupDataOnConnectableApns: isConnectable() call trySetupData");
819                 apnContext.setReason(reason);
820                 trySetupData(apnContext, waitingApns);
821             }
822         }
823     }
824
825     private boolean trySetupData(ApnContext apnContext) {
826         return trySetupData(apnContext, null);
827     }
828
829     private boolean trySetupData(ApnContext apnContext, ArrayList<ApnSetting> waitingApns) {
830         if (DBG) {
831             log("trySetupData for type:" + apnContext.getApnType() +
832                     " due to " + apnContext.getReason() + " apnContext=" + apnContext);
833             log("trySetupData with mIsPsRestricted=" + mIsPsRestricted);
834         }
835
836         if (mPhone.getSimulatedRadioControl() != null) {
837             // Assume data is connected on the simulator
838             // FIXME  this can be improved
839             apnContext.setState(DctConstants.State.CONNECTED);
840             mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
841
842             log("trySetupData: X We're on the simulator; assuming connected retValue=true");
843             return true;
844         }
845
846         // Allow SETUP_DATA request for E-APN to be completed during emergency call
847         // and MOBILE DATA On/Off cases as well.
848         boolean isEmergencyApn = apnContext.getApnType().equals(PhoneConstants.APN_TYPE_EMERGENCY);
849         final ServiceStateTracker sst = mPhone.getServiceStateTracker();
850         boolean desiredPowerState = sst.getDesiredPowerState();
851         boolean checkUserDataEnabled =
852                     !(apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IMS));
853
854         if (apnContext.isConnectable() && (isEmergencyApn ||
855                 (isDataAllowed(apnContext) &&
856                 getAnyDataEnabled(checkUserDataEnabled) && !isEmergency()))) {
857             if (apnContext.getState() == DctConstants.State.FAILED) {
858                 if (DBG) log("trySetupData: make a FAILED ApnContext IDLE so its reusable");
859                 apnContext.setState(DctConstants.State.IDLE);
860             }
861             int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
862             apnContext.setConcurrentVoiceAndDataAllowed(sst.isConcurrentVoiceAndDataAllowed());
863             if (apnContext.getState() == DctConstants.State.IDLE) {
864                 if (waitingApns == null) {
865                     waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
866                 }
867                 if (waitingApns.isEmpty()) {
868                     notifyNoData(DcFailCause.MISSING_UNKNOWN_APN, apnContext);
869                     notifyOffApnsOfAvailability(apnContext.getReason());
870                     if (DBG) log("trySetupData: X No APN found retValue=false");
871                     return false;
872                 } else {
873                     apnContext.setWaitingApns(waitingApns);
874                     if (DBG) {
875                         log ("trySetupData: Create from mAllApnSettings : "
876                                     + apnListToString(mAllApnSettings));
877                     }
878                 }
879             }
880
881             if (DBG) {
882                 log("trySetupData: call setupData, waitingApns : "
883                         + apnListToString(apnContext.getWaitingApns()));
884             }
885             boolean retValue = setupData(apnContext, radioTech);
886             notifyOffApnsOfAvailability(apnContext.getReason());
887
888             if (DBG) log("trySetupData: X retValue=" + retValue);
889             return retValue;
890         } else {
891             if (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
892                     && apnContext.isConnectable()) {
893                 mPhone.notifyDataConnectionFailed(apnContext.getReason(), apnContext.getApnType());
894             }
895             notifyOffApnsOfAvailability(apnContext.getReason());
896             if (DBG) log ("trySetupData: X apnContext not 'ready' retValue=false");
897             return false;
898         }
899     }
900
901     @Override
902     // Disabled apn's still need avail/unavail notificiations - send them out
903     protected void notifyOffApnsOfAvailability(String reason) {
904         for (ApnContext apnContext : mApnContexts.values()) {
905             if (!mAttached.get() || !apnContext.isReady()) {
906                 if (VDBG) log("notifyOffApnOfAvailability type:" + apnContext.getApnType());
907                 mPhone.notifyDataConnection(reason != null ? reason : apnContext.getReason(),
908                                             apnContext.getApnType(),
909                                             PhoneConstants.DataState.DISCONNECTED);
910             } else {
911                 if (VDBG) {
912                     log("notifyOffApnsOfAvailability skipped apn due to attached && isReady " +
913                             apnContext.toString());
914                 }
915             }
916         }
917     }
918
919     /**
920      * If tearDown is true, this only tears down a CONNECTED session. Presently,
921      * there is no mechanism for abandoning an CONNECTING session,
922      * but would likely involve cancelling pending async requests or
923      * setting a flag or new state to ignore them when they came in
924      * @param tearDown true if the underlying DataConnection should be
925      * disconnected.
926      * @param reason reason for the clean up.
927      * @return boolean - true if we did cleanup any connections, false if they
928      *                   were already all disconnected.
929      */
930     protected boolean cleanUpAllConnections(boolean tearDown, String reason) {
931         if (DBG) log("cleanUpAllConnections: tearDown=" + tearDown + " reason=" + reason);
932         boolean didDisconnect = false;
933         boolean specificdisable = false;
934
935         if (!TextUtils.isEmpty(reason)) {
936             specificdisable = reason.equals(Phone.REASON_DATA_SPECIFIC_DISABLED);
937         }
938
939         for (ApnContext apnContext : mApnContexts.values()) {
940             if (apnContext.isDisconnected() == false) didDisconnect = true;
941             if (specificdisable) {
942                 if (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IMS)) {
943                     if (DBG) log("ApnConextType: " + apnContext.getApnType());
944                     apnContext.setReason(reason);
945                     cleanUpConnection(tearDown, apnContext);
946                 }
947             } else {
948                 // TODO - only do cleanup if not disconnected
949                 apnContext.setReason(reason);
950                 cleanUpConnection(tearDown, apnContext);
951             }
952         }
953
954         stopNetStatPoll();
955         stopDataStallAlarm();
956
957         // TODO: Do we need mRequestedApnType?
958         mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
959
960         log("cleanUpConnection: mDisconnectPendingCount = " + mDisconnectPendingCount);
961         if (tearDown && mDisconnectPendingCount == 0) {
962             notifyDataDisconnectComplete();
963             notifyAllDataDisconnected();
964         }
965
966         return didDisconnect;
967     }
968
969     /**
970      * Cleanup all connections.
971      *
972      * TODO: Cleanup only a specified connection passed as a parameter.
973      *       Also, make sure when you clean up a conn, if it is last apply
974      *       logic as though it is cleanupAllConnections
975      *
976      * @param cause for the clean up.
977      */
978
979     @Override
980     protected void onCleanUpAllConnections(String cause) {
981         cleanUpAllConnections(true, cause);
982     }
983
984     protected void cleanUpConnection(boolean tearDown, ApnContext apnContext) {
985
986         if (apnContext == null) {
987             if (DBG) log("cleanUpConnection: apn context is null");
988             return;
989         }
990
991         DcAsyncChannel dcac = apnContext.getDcAc();
992         if (DBG) {
993             log("cleanUpConnection: E tearDown=" + tearDown + " reason=" + apnContext.getReason() +
994                     " apnContext=" + apnContext);
995         }
996         if (tearDown) {
997             if (apnContext.isDisconnected()) {
998                 // The request is tearDown and but ApnContext is not connected.
999                 // If apnContext is not enabled anymore, break the linkage to the DCAC/DC.
1000                 apnContext.setState(DctConstants.State.IDLE);
1001                 if (!apnContext.isReady()) {
1002                     if (dcac != null) {
1003                         if (DBG) {
1004                             log("cleanUpConnection: teardown, disconnected, !ready apnContext="
1005                                     + apnContext);
1006                         }
1007                         dcac.tearDown(apnContext, "", null);
1008                     }
1009                     apnContext.setDataConnectionAc(null);
1010                 }
1011             } else {
1012                 // Connection is still there. Try to clean up.
1013                 if (dcac != null) {
1014                     if (apnContext.getState() != DctConstants.State.DISCONNECTING) {
1015                         boolean disconnectAll = false;
1016                         if (PhoneConstants.APN_TYPE_DUN.equals(apnContext.getApnType())) {
1017                             // CAF_MSIM is this below condition required.
1018                             // if (PhoneConstants.APN_TYPE_DUN.equals(PhoneConstants.APN_TYPE_DEFAULT)) {
1019                             if (teardownForDun()) {
1020                                 if (DBG) {
1021                                     log("cleanUpConnection: disconnectAll DUN connection");
1022                                 }
1023                                 // we need to tear it down - we brought it up just for dun and
1024                                 // other people are camped on it and now dun is done.  We need
1025                                 // to stop using it and let the normal apn list get used to find
1026                                 // connections for the remaining desired connections
1027                                 disconnectAll = true;
1028                             }
1029                         }
1030                         if (DBG) {
1031                             log("cleanUpConnection: tearing down" + (disconnectAll ? " all" :"")
1032                                     + "apnContext=" + apnContext);
1033                         }
1034                         Message msg = obtainMessage(DctConstants.EVENT_DISCONNECT_DONE, apnContext);
1035                         if (disconnectAll) {
1036                             apnContext.getDcAc().tearDownAll(apnContext.getReason(), msg);
1037                         } else {
1038                             apnContext.getDcAc()
1039                                 .tearDown(apnContext, apnContext.getReason(), msg);
1040                         }
1041                         apnContext.setState(DctConstants.State.DISCONNECTING);
1042                         mDisconnectPendingCount++;
1043                     }
1044                 } else {
1045                     // apn is connected but no reference to dcac.
1046                     // Should not be happen, but reset the state in case.
1047                     apnContext.setState(DctConstants.State.IDLE);
1048                     mPhone.notifyDataConnection(apnContext.getReason(),
1049                                                 apnContext.getApnType());
1050                 }
1051             }
1052         } else {
1053             // force clean up the data connection.
1054             if (dcac != null) dcac.reqReset();
1055             apnContext.setState(DctConstants.State.IDLE);
1056             mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1057             apnContext.setDataConnectionAc(null);
1058         }
1059
1060         // Make sure reconnection alarm is cleaned up if there is no ApnContext
1061         // associated to the connection.
1062         if (dcac != null) {
1063             cancelReconnectAlarm(apnContext);
1064         }
1065         if (DBG) {
1066             log("cleanUpConnection: X tearDown=" + tearDown + " reason=" + apnContext.getReason() +
1067                     " apnContext=" + apnContext + " dcac=" + apnContext.getDcAc());
1068         }
1069     }
1070
1071     /**
1072      * Determine if DUN connection is special and we need to teardown on start/stop
1073      */
1074     private boolean teardownForDun() {
1075         // CDMA always needs to do this the profile id is correct
1076         final int rilRat = mPhone.getServiceState().getRilDataRadioTechnology();
1077         if (ServiceState.isCdma(rilRat)) return true;
1078
1079         return (fetchDunApn() != null);
1080     }
1081
1082     /**
1083      * Cancels the alarm associated with apnContext.
1084      *
1085      * @param apnContext on which the alarm should be stopped.
1086      */
1087     private void cancelReconnectAlarm(ApnContext apnContext) {
1088         if (apnContext == null) return;
1089
1090         PendingIntent intent = apnContext.getReconnectIntent();
1091
1092         if (intent != null) {
1093                 AlarmManager am =
1094                     (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
1095                 am.cancel(intent);
1096                 apnContext.setReconnectIntent(null);
1097         }
1098     }
1099
1100     /**
1101      * @param types comma delimited list of APN types
1102      * @return array of APN types
1103      */
1104     private String[] parseTypes(String types) {
1105         String[] result;
1106         // If unset, set to DEFAULT.
1107         if (types == null || types.equals("")) {
1108             result = new String[1];
1109             result[0] = PhoneConstants.APN_TYPE_ALL;
1110         } else {
1111             result = types.split(",");
1112         }
1113         return result;
1114     }
1115
1116     @Override
1117     protected boolean isPermanentFail(DcFailCause dcFailCause) {
1118         return (dcFailCause.isPermanentFail() &&
1119                 (mAttached.get() == false || dcFailCause != DcFailCause.SIGNAL_LOST));
1120     }
1121
1122     private ApnSetting makeApnSetting(Cursor cursor) {
1123         String[] types = parseTypes(
1124                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
1125         ApnSetting apn = new ApnSetting(
1126                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
1127                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
1128                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)),
1129                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
1130                 NetworkUtils.trimV4AddrZeros(
1131                         cursor.getString(
1132                         cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY))),
1133                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)),
1134                 NetworkUtils.trimV4AddrZeros(
1135                         cursor.getString(
1136                         cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC))),
1137                 NetworkUtils.trimV4AddrZeros(
1138                         cursor.getString(
1139                         cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY))),
1140                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)),
1141                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
1142                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
1143                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
1144                 types,
1145                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROTOCOL)),
1146                 cursor.getString(cursor.getColumnIndexOrThrow(
1147                         Telephony.Carriers.ROAMING_PROTOCOL)),
1148                 cursor.getInt(cursor.getColumnIndexOrThrow(
1149                         Telephony.Carriers.CARRIER_ENABLED)) == 1,
1150                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER)),
1151                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER_BITMASK)),
1152                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROFILE_ID)),
1153                 cursor.getInt(cursor.getColumnIndexOrThrow(
1154                         Telephony.Carriers.MODEM_COGNITIVE)) == 1,
1155                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MAX_CONNS)),
1156                 cursor.getInt(cursor.getColumnIndexOrThrow(
1157                         Telephony.Carriers.WAIT_TIME)),
1158                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MAX_CONNS_TIME)),
1159                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MTU)),
1160                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MVNO_TYPE)),
1161                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MVNO_MATCH_DATA)));
1162         return apn;
1163     }
1164
1165     private ArrayList<ApnSetting> createApnList(Cursor cursor) {
1166         ArrayList<ApnSetting> mnoApns = new ArrayList<ApnSetting>();
1167         ArrayList<ApnSetting> mvnoApns = new ArrayList<ApnSetting>();
1168         IccRecords r = mIccRecords.get();
1169
1170         if (cursor.moveToFirst()) {
1171             do {
1172                 ApnSetting apn = makeApnSetting(cursor);
1173                 if (apn == null) {
1174                     continue;
1175                 }
1176
1177                 if (apn.hasMvnoParams()) {
1178                     if (r != null && ApnSetting.mvnoMatches(r, apn.mvnoType, apn.mvnoMatchData)) {
1179                         mvnoApns.add(apn);
1180                     }
1181                 } else {
1182                     mnoApns.add(apn);
1183                 }
1184             } while (cursor.moveToNext());
1185         }
1186
1187         ArrayList<ApnSetting> result = mvnoApns.isEmpty() ? mnoApns : mvnoApns;
1188         if (DBG) log("createApnList: X result=" + result);
1189         return result;
1190     }
1191
1192     private boolean dataConnectionNotInUse(DcAsyncChannel dcac) {
1193         if (DBG) log("dataConnectionNotInUse: check if dcac is inuse dcac=" + dcac);
1194         for (ApnContext apnContext : mApnContexts.values()) {
1195             if (apnContext.getDcAc() == dcac) {
1196                 if (DBG) log("dataConnectionNotInUse: in use by apnContext=" + apnContext);
1197                 return false;
1198             }
1199         }
1200         // TODO: Fix retry handling so free DataConnections have empty apnlists.
1201         // Probably move retry handling into DataConnections and reduce complexity
1202         // of DCT.
1203         if (DBG) log("dataConnectionNotInUse: tearDownAll");
1204         dcac.tearDownAll("No connection", null);
1205         if (DBG) log("dataConnectionNotInUse: not in use return true");
1206         return true;
1207     }
1208
1209     private DcAsyncChannel findFreeDataConnection() {
1210         for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
1211             if (dcac.isInactiveSync() && dataConnectionNotInUse(dcac)) {
1212                 if (DBG) {
1213                     log("findFreeDataConnection: found free DataConnection=" +
1214                         " dcac=" + dcac);
1215                 }
1216                 return dcac;
1217             }
1218         }
1219         log("findFreeDataConnection: NO free DataConnection");
1220         return null;
1221     }
1222
1223     private boolean setupData(ApnContext apnContext, int radioTech) {
1224         if (DBG) log("setupData: apnContext=" + apnContext);
1225         ApnSetting apnSetting;
1226         DcAsyncChannel dcac = null;
1227
1228         apnSetting = apnContext.getNextWaitingApn();
1229         if (apnSetting == null) {
1230             if (DBG) log("setupData: return for no apn found!");
1231             return false;
1232         }
1233
1234         int profileId = apnSetting.profileId;
1235         if (profileId == 0) {
1236             profileId = getApnProfileID(apnContext.getApnType());
1237         }
1238
1239         // On CDMA, if we're explicitly asking for DUN, we need have
1240         // a dun-profiled connection so we can't share an existing one
1241         // On GSM/LTE we can share existing apn connections provided they support
1242         // this type.
1243         if (apnContext.getApnType() != PhoneConstants.APN_TYPE_DUN ||
1244                 teardownForDun() == false) {
1245             dcac = checkForCompatibleConnectedApnContext(apnContext);
1246             if (dcac != null) {
1247                 // Get the dcacApnSetting for the connection we want to share.
1248                 ApnSetting dcacApnSetting = dcac.getApnSettingSync();
1249                 if (dcacApnSetting != null) {
1250                     // Setting is good, so use it.
1251                     apnSetting = dcacApnSetting;
1252                 }
1253             }
1254         }
1255         if (dcac == null) {
1256             if (isOnlySingleDcAllowed(radioTech)) {
1257                 if (isHigherPriorityApnContextActive(apnContext)) {
1258                     if (DBG) {
1259                         log("setupData: Higher priority ApnContext active.  Ignoring call");
1260                     }
1261                     return false;
1262                 }
1263
1264                 // Only lower priority calls left.  Disconnect them all in this single PDP case
1265                 // so that we can bring up the requested higher priority call (once we receive
1266                 // repsonse for deactivate request for the calls we are about to disconnect
1267                 if (cleanUpAllConnections(true, Phone.REASON_SINGLE_PDN_ARBITRATION)) {
1268                     // If any call actually requested to be disconnected, means we can't
1269                     // bring up this connection yet as we need to wait for those data calls
1270                     // to be disconnected.
1271                     if (DBG) log("setupData: Some calls are disconnecting first.  Wait and retry");
1272                     return false;
1273                 }
1274
1275                 // No other calls are active, so proceed
1276                 if (DBG) log("setupData: Single pdp. Continue setting up data call.");
1277             }
1278
1279             dcac = findFreeDataConnection();
1280
1281             if (dcac == null) {
1282                 dcac = createDataConnection();
1283             }
1284
1285             if (dcac == null) {
1286                 if (DBG) log("setupData: No free DataConnection and couldn't create one, WEIRD");
1287                 return false;
1288             }
1289         }
1290         if (DBG) log("setupData: dcac=" + dcac + " apnSetting=" + apnSetting);
1291
1292         apnContext.setDataConnectionAc(dcac);
1293         apnContext.setApnSetting(apnSetting);
1294         apnContext.setState(DctConstants.State.CONNECTING);
1295         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1296
1297         Message msg = obtainMessage();
1298         msg.what = DctConstants.EVENT_DATA_SETUP_COMPLETE;
1299         msg.obj = apnContext;
1300         dcac.bringUp(apnContext, getInitialMaxRetry(), profileId, radioTech, mAutoAttachOnCreation,
1301                 msg);
1302
1303         if (DBG) log("setupData: initing!");
1304         return true;
1305     }
1306
1307     /**
1308      * Handles changes to the APN database.
1309      */
1310     private void onApnChanged() {
1311         DctConstants.State overallState = getOverallState();
1312         boolean isDisconnected = (overallState == DctConstants.State.IDLE ||
1313                 overallState == DctConstants.State.FAILED);
1314
1315         if (mPhone instanceof GSMPhone) {
1316             // The "current" may no longer be valid.  MMS depends on this to send properly. TBD
1317             ((GSMPhone)mPhone).updateCurrentCarrierInProvider();
1318         }
1319
1320         // TODO: It'd be nice to only do this if the changed entrie(s)
1321         // match the current operator.
1322         if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections");
1323         createAllApnList();
1324         setInitialAttachApn();
1325         cleanUpConnectionsOnUpdatedApns(!isDisconnected);
1326
1327         // FIXME: See bug 17426028 maybe no conditional is needed.
1328         if (mPhone.getSubId() == SubscriptionManager.getDefaultDataSubId()) {
1329             setupDataOnConnectableApns(Phone.REASON_APN_CHANGED);
1330         }
1331     }
1332
1333     /**
1334      * @param cid Connection id provided from RIL.
1335      * @return DataConnectionAc associated with specified cid.
1336      */
1337     private DcAsyncChannel findDataConnectionAcByCid(int cid) {
1338         for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
1339             if (dcac.getCidSync() == cid) {
1340                 return dcac;
1341             }
1342         }
1343         return null;
1344     }
1345
1346     // TODO: For multiple Active APNs not exactly sure how to do this.
1347     @Override
1348     protected void gotoIdleAndNotifyDataConnection(String reason) {
1349         if (DBG) log("gotoIdleAndNotifyDataConnection: reason=" + reason);
1350         notifyDataConnection(reason);
1351         mActiveApn = null;
1352     }
1353
1354     /**
1355      * "Active" here means ApnContext isEnabled() and not in FAILED state
1356      * @param apnContext to compare with
1357      * @return true if higher priority active apn found
1358      */
1359     private boolean isHigherPriorityApnContextActive(ApnContext apnContext) {
1360         for (ApnContext otherContext : mPrioritySortedApnContexts) {
1361             if (apnContext.getApnType().equalsIgnoreCase(otherContext.getApnType())) return false;
1362             if (otherContext.isEnabled() && otherContext.getState() != DctConstants.State.FAILED) {
1363                 return true;
1364             }
1365         }
1366         return false;
1367     }
1368
1369     /**
1370      * Reports if we support multiple connections or not.
1371      * This is a combination of factors, based on carrier and RAT.
1372      * @param rilRadioTech the RIL Radio Tech currently in use
1373      * @return true if only single DataConnection is allowed
1374      */
1375     private boolean isOnlySingleDcAllowed(int rilRadioTech) {
1376         int[] singleDcRats = mPhone.getContext().getResources().getIntArray(
1377                 com.android.internal.R.array.config_onlySingleDcAllowed);
1378         boolean onlySingleDcAllowed = false;
1379         if (Build.IS_DEBUGGABLE &&
1380                 SystemProperties.getBoolean("persist.telephony.test.singleDc", false)) {
1381             onlySingleDcAllowed = true;
1382         }
1383         if (singleDcRats != null) {
1384             for (int i=0; i < singleDcRats.length && onlySingleDcAllowed == false; i++) {
1385                 if (rilRadioTech == singleDcRats[i]) onlySingleDcAllowed = true;
1386             }
1387         }
1388
1389         if (DBG) log("isOnlySingleDcAllowed(" + rilRadioTech + "): " + onlySingleDcAllowed);
1390         return onlySingleDcAllowed;
1391     }
1392
1393     @Override
1394     protected void restartRadio() {
1395         if (DBG) log("restartRadio: ************TURN OFF RADIO**************");
1396         cleanUpAllConnections(true, Phone.REASON_RADIO_TURNED_OFF);
1397         mPhone.getServiceStateTracker().powerOffRadioSafely(this);
1398         /* Note: no need to call setRadioPower(true).  Assuming the desired
1399          * radio power state is still ON (as tracked by ServiceStateTracker),
1400          * ServiceStateTracker will call setRadioPower when it receives the
1401          * RADIO_STATE_CHANGED notification for the power off.  And if the
1402          * desired power state has changed in the interim, we don't want to
1403          * override it with an unconditional power on.
1404          */
1405
1406         int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0"));
1407         SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1));
1408     }
1409
1410     /**
1411      * Return true if data connection need to be setup after disconnected due to
1412      * reason.
1413      *
1414      * @param reason the reason why data is disconnected
1415      * @return true if try setup data connection is need for this reason
1416      */
1417     private boolean retryAfterDisconnected(ApnContext apnContext) {
1418         boolean retry = true;
1419         String reason = apnContext.getReason();
1420
1421         if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) ||
1422                 (isOnlySingleDcAllowed(mPhone.getServiceState().getRilDataRadioTechnology())
1423                  && isHigherPriorityApnContextActive(apnContext))) {
1424             retry = false;
1425         }
1426         return retry;
1427     }
1428
1429     private void startAlarmForReconnect(int delay, ApnContext apnContext) {
1430         String apnType = apnContext.getApnType();
1431
1432         Intent intent = new Intent(INTENT_RECONNECT_ALARM + "." + apnType);
1433         intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON, apnContext.getReason());
1434         intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE, apnType);
1435
1436         // Get current sub id.
1437         int subId = SubscriptionManager.getDefaultDataSubId();
1438         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
1439
1440         if (DBG) {
1441             log("startAlarmForReconnect: delay=" + delay + " action=" + intent.getAction()
1442                     + " apn=" + apnContext);
1443         }
1444
1445         PendingIntent alarmIntent = PendingIntent.getBroadcast (mPhone.getContext(), 0,
1446                                         intent, PendingIntent.FLAG_UPDATE_CURRENT);
1447         apnContext.setReconnectIntent(alarmIntent);
1448         mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1449                 SystemClock.elapsedRealtime() + delay, alarmIntent);
1450     }
1451
1452     private void startAlarmForRestartTrySetup(int delay, ApnContext apnContext) {
1453         String apnType = apnContext.getApnType();
1454         Intent intent = new Intent(INTENT_RESTART_TRYSETUP_ALARM + "." + apnType);
1455         intent.putExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE, apnType);
1456
1457         if (DBG) {
1458             log("startAlarmForRestartTrySetup: delay=" + delay + " action=" + intent.getAction()
1459                     + " apn=" + apnContext);
1460         }
1461         PendingIntent alarmIntent = PendingIntent.getBroadcast (mPhone.getContext(), 0,
1462                                         intent, PendingIntent.FLAG_UPDATE_CURRENT);
1463         apnContext.setReconnectIntent(alarmIntent);
1464         mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1465                 SystemClock.elapsedRealtime() + delay, alarmIntent);
1466     }
1467
1468     private void notifyNoData(DcFailCause lastFailCauseCode,
1469                               ApnContext apnContext) {
1470         if (DBG) log( "notifyNoData: type=" + apnContext.getApnType());
1471         if (isPermanentFail(lastFailCauseCode)
1472             && (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT))) {
1473             mPhone.notifyDataConnectionFailed(apnContext.getReason(), apnContext.getApnType());
1474         }
1475     }
1476
1477     private void onRecordsLoaded() {
1478         if (DBG) log("onRecordsLoaded: createAllApnList");
1479         mAutoAttachOnCreationConfig = mPhone.getContext().getResources()
1480                 .getBoolean(com.android.internal.R.bool.config_auto_attach_data_on_creation);
1481
1482         createAllApnList();
1483         setInitialAttachApn();
1484         if (mPhone.mCi.getRadioState().isOn()) {
1485             if (DBG) log("onRecordsLoaded: notifying data availability");
1486             notifyOffApnsOfAvailability(Phone.REASON_SIM_LOADED);
1487         }
1488         setupDataOnConnectableApns(Phone.REASON_SIM_LOADED);
1489     }
1490
1491     private void onSimNotReady() {
1492         if (DBG) log("onSimNotReady");
1493
1494         cleanUpAllConnections(true, Phone.REASON_SIM_NOT_READY);
1495         mAllApnSettings = null;
1496         mAutoAttachOnCreationConfig = false;
1497     }
1498
1499     @Override
1500     protected void onSetDependencyMet(String apnType, boolean met) {
1501         // don't allow users to tweak hipri to work around default dependency not met
1502         if (PhoneConstants.APN_TYPE_HIPRI.equals(apnType)) return;
1503
1504         ApnContext apnContext = mApnContexts.get(apnType);
1505         if (apnContext == null) {
1506             loge("onSetDependencyMet: ApnContext not found in onSetDependencyMet(" +
1507                     apnType + ", " + met + ")");
1508             return;
1509         }
1510         applyNewState(apnContext, apnContext.isEnabled(), met);
1511         if (PhoneConstants.APN_TYPE_DEFAULT.equals(apnType)) {
1512             // tie actions on default to similar actions on HIPRI regarding dependencyMet
1513             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_HIPRI);
1514             if (apnContext != null) applyNewState(apnContext, apnContext.isEnabled(), met);
1515         }
1516     }
1517
1518     private void applyNewState(ApnContext apnContext, boolean enabled, boolean met) {
1519         boolean cleanup = false;
1520         boolean trySetup = false;
1521         if (DBG) {
1522             log("applyNewState(" + apnContext.getApnType() + ", " + enabled +
1523                     "(" + apnContext.isEnabled() + "), " + met + "(" +
1524                     apnContext.getDependencyMet() +"))");
1525         }
1526         if (apnContext.isReady()) {
1527             cleanup = true;
1528             if (enabled && met) {
1529                 DctConstants.State state = apnContext.getState();
1530                 switch(state) {
1531                     case CONNECTING:
1532                     case SCANNING:
1533                     case CONNECTED:
1534                     case DISCONNECTING:
1535                         // We're "READY" and active so just return
1536                         if (DBG) log("applyNewState: 'ready' so return");
1537                         return;
1538                     case IDLE:
1539                         // fall through: this is unexpected but if it happens cleanup and try setup
1540                     case FAILED:
1541                     case RETRYING: {
1542                         // We're "READY" but not active so disconnect (cleanup = true) and
1543                         // connect (trySetup = true) to be sure we retry the connection.
1544                         trySetup = true;
1545                         apnContext.setReason(Phone.REASON_DATA_ENABLED);
1546                         break;
1547                     }
1548                 }
1549             } else if (met) {
1550                 apnContext.setReason(Phone.REASON_DATA_DISABLED);
1551                 // If ConnectivityService has disabled this network, stop trying to bring
1552                 // it up, but do not tear it down - ConnectivityService will do that
1553                 // directly by talking with the DataConnection.
1554                 //
1555                 // This doesn't apply to DUN, however.  Those connections have special
1556                 // requirements from carriers and we need stop using them when the dun
1557                 // request goes away.  This applies to both CDMA and GSM because they both
1558                 // can declare the DUN APN sharable by default traffic, thus still satisfying
1559                 // those requests and not torn down organically.
1560                 if (apnContext.getApnType() == PhoneConstants.APN_TYPE_DUN && teardownForDun()) {
1561                     cleanup = true;
1562                 } else {
1563                     cleanup = false;
1564                 }
1565             } else {
1566                 apnContext.setReason(Phone.REASON_DATA_DEPENDENCY_UNMET);
1567             }
1568         } else {
1569             if (enabled && met) {
1570                 if (apnContext.isEnabled()) {
1571                     apnContext.setReason(Phone.REASON_DATA_DEPENDENCY_MET);
1572                 } else {
1573                     apnContext.setReason(Phone.REASON_DATA_ENABLED);
1574                 }
1575                 if (apnContext.getState() == DctConstants.State.FAILED) {
1576                     apnContext.setState(DctConstants.State.IDLE);
1577                 }
1578                 trySetup = true;
1579             }
1580         }
1581         apnContext.setEnabled(enabled);
1582         apnContext.setDependencyMet(met);
1583         if (cleanup) cleanUpConnection(true, apnContext);
1584         if (trySetup) trySetupData(apnContext);
1585     }
1586
1587     private DcAsyncChannel checkForCompatibleConnectedApnContext(ApnContext apnContext) {
1588         String apnType = apnContext.getApnType();
1589         ApnSetting dunSetting = null;
1590
1591         if (PhoneConstants.APN_TYPE_DUN.equals(apnType)) {
1592             dunSetting = fetchDunApn();
1593         }
1594         if (DBG) {
1595             log("checkForCompatibleConnectedApnContext: apnContext=" + apnContext );
1596         }
1597
1598         DcAsyncChannel potentialDcac = null;
1599         ApnContext potentialApnCtx = null;
1600         for (ApnContext curApnCtx : mApnContexts.values()) {
1601             DcAsyncChannel curDcac = curApnCtx.getDcAc();
1602             log("curDcac: " + curDcac);
1603             if (curDcac != null) {
1604                 ApnSetting apnSetting = curApnCtx.getApnSetting();
1605                 log("apnSetting: " + apnSetting);
1606                 if (dunSetting != null) {
1607                     if (dunSetting.equals(apnSetting)) {
1608                         switch (curApnCtx.getState()) {
1609                             case CONNECTED:
1610                                 if (DBG) {
1611                                     log("checkForCompatibleConnectedApnContext:"
1612                                             + " found dun conn=" + curDcac
1613                                             + " curApnCtx=" + curApnCtx);
1614                                 }
1615                                 return curDcac;
1616                             case RETRYING:
1617                             case CONNECTING:
1618                                 potentialDcac = curDcac;
1619                                 potentialApnCtx = curApnCtx;
1620                             default:
1621                                 // Not connected, potential unchanged
1622                                 break;
1623                         }
1624                     }
1625                 } else if (apnSetting != null && apnSetting.canHandleType(apnType)) {
1626                     switch (curApnCtx.getState()) {
1627                         case CONNECTED:
1628                             if (DBG) {
1629                                 log("checkForCompatibleConnectedApnContext:"
1630                                         + " found canHandle conn=" + curDcac
1631                                         + " curApnCtx=" + curApnCtx);
1632                             }
1633                             return curDcac;
1634                         case RETRYING:
1635                         case CONNECTING:
1636                             potentialDcac = curDcac;
1637                             potentialApnCtx = curApnCtx;
1638                         default:
1639                             // Not connected, potential unchanged
1640                             break;
1641                     }
1642                 }
1643             } else {
1644                 if (VDBG) {
1645                     log("checkForCompatibleConnectedApnContext: not conn curApnCtx=" + curApnCtx);
1646                 }
1647             }
1648         }
1649         if (potentialDcac != null) {
1650             if (DBG) {
1651                 log("checkForCompatibleConnectedApnContext: found potential conn=" + potentialDcac
1652                         + " curApnCtx=" + potentialApnCtx);
1653             }
1654             return potentialDcac;
1655         }
1656
1657         if (DBG) log("checkForCompatibleConnectedApnContext: NO conn apnContext=" + apnContext);
1658         return null;
1659     }
1660
1661     @Override
1662     protected void onEnableApn(int apnId, int enabled) {
1663         ApnContext apnContext = mApnContexts.get(apnIdToType(apnId));
1664         if (apnContext == null) {
1665             loge("onEnableApn(" + apnId + ", " + enabled + "): NO ApnContext");
1666             return;
1667         }
1668         // TODO change our retry manager to use the appropriate numbers for the new APN
1669         if (DBG) log("onEnableApn: apnContext=" + apnContext + " call applyNewState");
1670         applyNewState(apnContext, enabled == DctConstants.ENABLED, apnContext.getDependencyMet());
1671     }
1672
1673     @Override
1674     // TODO: We shouldnt need this.
1675     protected boolean onTrySetupData(String reason) {
1676         if (DBG) log("onTrySetupData: reason=" + reason);
1677         setupDataOnConnectableApns(reason);
1678         return true;
1679     }
1680
1681     protected boolean onTrySetupData(ApnContext apnContext) {
1682         if (DBG) log("onTrySetupData: apnContext=" + apnContext);
1683         return trySetupData(apnContext);
1684     }
1685
1686     @Override
1687     protected void onRoamingOff() {
1688         if (DBG) log("onRoamingOff");
1689
1690         if (!mUserDataEnabled) return;
1691
1692         if (getDataOnRoamingEnabled() == false) {
1693             notifyOffApnsOfAvailability(Phone.REASON_ROAMING_OFF);
1694             setupDataOnConnectableApns(Phone.REASON_ROAMING_OFF);
1695         } else {
1696             notifyDataConnection(Phone.REASON_ROAMING_OFF);
1697         }
1698     }
1699
1700     @Override
1701     protected void onRoamingOn() {
1702         if (DBG) log("onRoamingOn");
1703
1704         if (!mUserDataEnabled) return;
1705
1706         if (getDataOnRoamingEnabled()) {
1707             if (DBG) log("onRoamingOn: setup data on roaming");
1708             setupDataOnConnectableApns(Phone.REASON_ROAMING_ON);
1709             notifyDataConnection(Phone.REASON_ROAMING_ON);
1710         } else {
1711             if (DBG) log("onRoamingOn: Tear down data connection on roaming.");
1712             cleanUpAllConnections(true, Phone.REASON_ROAMING_ON);
1713             notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1714         }
1715     }
1716
1717     @Override
1718     protected void onRadioAvailable() {
1719         if (DBG) log("onRadioAvailable");
1720         if (mPhone.getSimulatedRadioControl() != null) {
1721             // Assume data is connected on the simulator
1722             // FIXME  this can be improved
1723             // setState(DctConstants.State.CONNECTED);
1724             notifyDataConnection(null);
1725
1726             log("onRadioAvailable: We're on the simulator; assuming data is connected");
1727         }
1728
1729         IccRecords r = mIccRecords.get();
1730         if (r != null && r.getRecordsLoaded()) {
1731             notifyOffApnsOfAvailability(null);
1732         }
1733
1734         if (getOverallState() != DctConstants.State.IDLE) {
1735             cleanUpConnection(true, null);
1736         }
1737     }
1738
1739     @Override
1740     protected void onRadioOffOrNotAvailable() {
1741         // Make sure our reconnect delay starts at the initial value
1742         // next time the radio comes on
1743
1744         mReregisterOnReconnectFailure = false;
1745
1746         if (mPhone.getSimulatedRadioControl() != null) {
1747             // Assume data is connected on the simulator
1748             // FIXME  this can be improved
1749             log("We're on the simulator; assuming radio off is meaningless");
1750         } else {
1751             if (DBG) log("onRadioOffOrNotAvailable: is off and clean up all connections");
1752             cleanUpAllConnections(false, Phone.REASON_RADIO_TURNED_OFF);
1753         }
1754         notifyOffApnsOfAvailability(null);
1755     }
1756
1757     @Override
1758     protected void completeConnection(ApnContext apnContext) {
1759         boolean isProvApn = apnContext.isProvisioningApn();
1760
1761         if (DBG) log("completeConnection: successful, notify the world apnContext=" + apnContext);
1762
1763         if (mIsProvisioning && !TextUtils.isEmpty(mProvisioningUrl)) {
1764             if (DBG) {
1765                 log("completeConnection: MOBILE_PROVISIONING_ACTION url="
1766                         + mProvisioningUrl);
1767             }
1768             Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
1769                     Intent.CATEGORY_APP_BROWSER);
1770             newIntent.setData(Uri.parse(mProvisioningUrl));
1771             newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
1772                     Intent.FLAG_ACTIVITY_NEW_TASK);
1773             try {
1774                 mPhone.getContext().startActivity(newIntent);
1775             } catch (ActivityNotFoundException e) {
1776                 loge("completeConnection: startActivityAsUser failed" + e);
1777             }
1778         }
1779         mIsProvisioning = false;
1780         mProvisioningUrl = null;
1781         if (mProvisioningSpinner != null) {
1782             sendMessage(obtainMessage(DctConstants.CMD_CLEAR_PROVISIONING_SPINNER,
1783                     mProvisioningSpinner));
1784         }
1785
1786         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1787         startNetStatPoll();
1788         startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1789     }
1790
1791     /**
1792      * A SETUP (aka bringUp) has completed, possibly with an error. If
1793      * there is an error this method will call {@link #onDataSetupCompleteError}.
1794      */
1795     @Override
1796     protected void onDataSetupComplete(AsyncResult ar) {
1797
1798         DcFailCause cause = DcFailCause.UNKNOWN;
1799         boolean handleError = false;
1800         ApnContext apnContext = null;
1801
1802         if(ar.userObj instanceof ApnContext){
1803             apnContext = (ApnContext)ar.userObj;
1804         } else {
1805             throw new RuntimeException("onDataSetupComplete: No apnContext");
1806         }
1807
1808         if (ar.exception == null) {
1809             DcAsyncChannel dcac = apnContext.getDcAc();
1810
1811             if (RADIO_TESTS) {
1812                 // Note: To change radio.test.onDSC.null.dcac from command line you need to
1813                 // adb root and adb remount and from the command line you can only change the
1814                 // value to 1 once. To change it a second time you can reboot or execute
1815                 // adb shell stop and then adb shell start. The command line to set the value is:
1816                 // adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "insert into system (name,value) values ('radio.test.onDSC.null.dcac', '1');"
1817                 ContentResolver cr = mPhone.getContext().getContentResolver();
1818                 String radioTestProperty = "radio.test.onDSC.null.dcac";
1819                 if (Settings.System.getInt(cr, radioTestProperty, 0) == 1) {
1820                     log("onDataSetupComplete: " + radioTestProperty +
1821                             " is true, set dcac to null and reset property to false");
1822                     dcac = null;
1823                     Settings.System.putInt(cr, radioTestProperty, 0);
1824                     log("onDataSetupComplete: " + radioTestProperty + "=" +
1825                             Settings.System.getInt(mPhone.getContext().getContentResolver(),
1826                                     radioTestProperty, -1));
1827                 }
1828             }
1829             if (dcac == null) {
1830                 log("onDataSetupComplete: no connection to DC, handle as error");
1831                 cause = DcFailCause.CONNECTION_TO_DATACONNECTIONAC_BROKEN;
1832                 handleError = true;
1833             } else {
1834                 ApnSetting apn = apnContext.getApnSetting();
1835                 if (DBG) {
1836                     log("onDataSetupComplete: success apn=" + (apn == null ? "unknown" : apn.apn));
1837                 }
1838                 if (apn != null && apn.proxy != null && apn.proxy.length() != 0) {
1839                     try {
1840                         String port = apn.port;
1841                         if (TextUtils.isEmpty(port)) port = "8080";
1842                         ProxyInfo proxy = new ProxyInfo(apn.proxy,
1843                                 Integer.parseInt(port), null);
1844                         dcac.setLinkPropertiesHttpProxySync(proxy);
1845                     } catch (NumberFormatException e) {
1846                         loge("onDataSetupComplete: NumberFormatException making ProxyProperties (" +
1847                                 apn.port + "): " + e);
1848                     }
1849                 }
1850
1851                 // everything is setup
1852                 if(TextUtils.equals(apnContext.getApnType(),PhoneConstants.APN_TYPE_DEFAULT)) {
1853                     SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "true");
1854                     if (mCanSetPreferApn && mPreferredApn == null) {
1855                         if (DBG) log("onDataSetupComplete: PREFERED APN is null");
1856                         mPreferredApn = apn;
1857                         if (mPreferredApn != null) {
1858                             setPreferredApn(mPreferredApn.id);
1859                         }
1860                     }
1861                 } else {
1862                     SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "false");
1863                 }
1864
1865                 // A connection is setup
1866                 apnContext.setState(DctConstants.State.CONNECTED);
1867                 boolean isProvApn = apnContext.isProvisioningApn();
1868                 final ConnectivityManager cm = ConnectivityManager.from(mPhone.getContext());
1869                 if (mProvisionBroadcastReceiver != null) {
1870                     mPhone.getContext().unregisterReceiver(mProvisionBroadcastReceiver);
1871                     mProvisionBroadcastReceiver = null;
1872                 }
1873                 if ((!isProvApn) || mIsProvisioning) {
1874                     // Hide any provisioning notification.
1875                     cm.setProvisioningNotificationVisible(false, ConnectivityManager.TYPE_MOBILE,
1876                             mProvisionActionName);
1877                     // Complete the connection normally notifying the world we're connected.
1878                     // We do this if this isn't a special provisioning apn or if we've been
1879                     // told its time to provision.
1880                     completeConnection(apnContext);
1881                 } else {
1882                     // This is a provisioning APN that we're reporting as connected. Later
1883                     // when the user desires to upgrade this to a "default" connection,
1884                     // mIsProvisioning == true, we'll go through the code path above.
1885                     // mIsProvisioning becomes true when CMD_ENABLE_MOBILE_PROVISIONING
1886                     // is sent to the DCT.
1887                     if (DBG) {
1888                         log("onDataSetupComplete: successful, BUT send connected to prov apn as"
1889                                 + " mIsProvisioning:" + mIsProvisioning + " == false"
1890                                 + " && (isProvisioningApn:" + isProvApn + " == true");
1891                     }
1892
1893                     // While radio is up, grab provisioning URL.  The URL contains ICCID which
1894                     // disappears when radio is off.
1895                     mProvisionBroadcastReceiver = new ProvisionNotificationBroadcastReceiver(
1896                             cm.getMobileProvisioningUrl(),
1897                             TelephonyManager.getDefault().getNetworkOperatorName());
1898                     mPhone.getContext().registerReceiver(mProvisionBroadcastReceiver,
1899                             new IntentFilter(mProvisionActionName));
1900                     // Put up user notification that sign-in is required.
1901                     cm.setProvisioningNotificationVisible(true, ConnectivityManager.TYPE_MOBILE,
1902                             mProvisionActionName);
1903                     // Turn off radio to save battery and avoid wasting carrier resources.
1904                     // The network isn't usable and network validation will just fail anyhow.
1905                     setRadio(false);
1906
1907                     Intent intent = new Intent(
1908                             TelephonyIntents.ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN);
1909                     intent.putExtra(PhoneConstants.DATA_APN_KEY, apnContext.getApnSetting().apn);
1910                     intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnContext.getApnType());
1911
1912                     String apnType = apnContext.getApnType();
1913                     LinkProperties linkProperties = getLinkProperties(apnType);
1914                     if (linkProperties != null) {
1915                         intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
1916                         String iface = linkProperties.getInterfaceName();
1917                         if (iface != null) {
1918                             intent.putExtra(PhoneConstants.DATA_IFACE_NAME_KEY, iface);
1919                         }
1920                     }
1921                     NetworkCapabilities networkCapabilities = getNetworkCapabilities(apnType);
1922                     if (networkCapabilities != null) {
1923                         intent.putExtra(PhoneConstants.DATA_NETWORK_CAPABILITIES_KEY,
1924                                 networkCapabilities);
1925                     }
1926
1927                     mPhone.getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1928                 }
1929                 if (DBG) {
1930                     log("onDataSetupComplete: SETUP complete type=" + apnContext.getApnType()
1931                         + ", reason:" + apnContext.getReason());
1932                 }
1933             }
1934         } else {
1935             cause = (DcFailCause) (ar.result);
1936             if (DBG) {
1937                 ApnSetting apn = apnContext.getApnSetting();
1938                 log(String.format("onDataSetupComplete: error apn=%s cause=%s",
1939                         (apn == null ? "unknown" : apn.apn), cause));
1940             }
1941             if (cause.isEventLoggable()) {
1942                 // Log this failure to the Event Logs.
1943                 int cid = getCellLocationId();
1944                 EventLog.writeEvent(EventLogTags.PDP_SETUP_FAIL,
1945                         cause.ordinal(), cid, TelephonyManager.getDefault().getNetworkType());
1946             }
1947             ApnSetting apn = apnContext.getApnSetting();
1948             mPhone.notifyPreciseDataConnectionFailed(apnContext.getReason(),
1949                     apnContext.getApnType(), apn != null ? apn.apn : "unknown", cause.toString());
1950
1951             // Count permanent failures and remove the APN we just tried
1952             if (isPermanentFail(cause)) apnContext.decWaitingApnsPermFailCount();
1953
1954             apnContext.removeWaitingApn(apnContext.getApnSetting());
1955             if (DBG) {
1956                 log(String.format("onDataSetupComplete: WaitingApns.size=%d" +
1957                         " WaitingApnsPermFailureCountDown=%d",
1958                         apnContext.getWaitingApns().size(),
1959                         apnContext.getWaitingApnsPermFailCount()));
1960             }
1961             handleError = true;
1962         }
1963
1964         if (handleError) {
1965             onDataSetupCompleteError(ar);
1966         }
1967
1968         /* If flag is set to false after SETUP_DATA_CALL is invoked, we need
1969          * to clean data connections.
1970          */
1971         if (!mInternalDataEnabled) {
1972             cleanUpAllConnections(null);
1973         }
1974
1975     }
1976
1977     /**
1978      * @return number of milli-seconds to delay between trying apns'
1979      */
1980     private int getApnDelay() {
1981         if (mFailFast) {
1982             return SystemProperties.getInt("persist.radio.apn_ff_delay",
1983                     APN_FAIL_FAST_DELAY_DEFAULT_MILLIS);
1984         } else {
1985             return SystemProperties.getInt("persist.radio.apn_delay", APN_DELAY_DEFAULT_MILLIS);
1986         }
1987     }
1988
1989     /**
1990      * Error has occurred during the SETUP {aka bringUP} request and the DCT
1991      * should either try the next waiting APN or start over from the
1992      * beginning if the list is empty. Between each SETUP request there will
1993      * be a delay defined by {@link #getApnDelay()}.
1994      */
1995     @Override
1996     protected void onDataSetupCompleteError(AsyncResult ar) {
1997         String reason = "";
1998         ApnContext apnContext = null;
1999
2000         if(ar.userObj instanceof ApnContext){
2001             apnContext = (ApnContext)ar.userObj;
2002         } else {
2003             throw new RuntimeException("onDataSetupCompleteError: No apnContext");
2004         }
2005
2006         // See if there are more APN's to try
2007         if (apnContext.getWaitingApns().isEmpty()) {
2008             apnContext.setState(DctConstants.State.FAILED);
2009             mPhone.notifyDataConnection(Phone.REASON_APN_FAILED, apnContext.getApnType());
2010
2011             apnContext.setDataConnectionAc(null);
2012
2013             if (apnContext.getWaitingApnsPermFailCount() == 0) {
2014                 if (DBG) {
2015                     log("onDataSetupCompleteError: All APN's had permanent failures, stop retrying");
2016                 }
2017             } else {
2018                 int delay = getApnDelay();
2019                 if (DBG) {
2020                     log("onDataSetupCompleteError: Not all APN's had permanent failures delay="
2021                             + delay);
2022                 }
2023                 startAlarmForRestartTrySetup(delay, apnContext);
2024             }
2025         } else {
2026             if (DBG) log("onDataSetupCompleteError: Try next APN");
2027             apnContext.setState(DctConstants.State.SCANNING);
2028             // Wait a bit before trying the next APN, so that
2029             // we're not tying up the RIL command channel
2030             startAlarmForReconnect(getApnDelay(), apnContext);
2031         }
2032     }
2033
2034     /**
2035      * Called when EVENT_DISCONNECT_DONE is received.
2036      */
2037     @Override
2038     protected void onDisconnectDone(int connId, AsyncResult ar) {
2039         ApnContext apnContext = null;
2040
2041         if (ar.userObj instanceof ApnContext) {
2042             apnContext = (ApnContext) ar.userObj;
2043         } else {
2044             loge("onDisconnectDone: Invalid ar in onDisconnectDone, ignore");
2045             return;
2046         }
2047
2048         if(DBG) log("onDisconnectDone: EVENT_DISCONNECT_DONE apnContext=" + apnContext);
2049         apnContext.setState(DctConstants.State.IDLE);
2050
2051         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
2052
2053         // if all data connection are gone, check whether Airplane mode request was
2054         // pending.
2055         if (isDisconnected()) {
2056             if (mPhone.getServiceStateTracker().processPendingRadioPowerOffAfterDataOff()) {
2057                 if(DBG) log("onDisconnectDone: radio will be turned off, no retries");
2058                 // Radio will be turned off. No need to retry data setup
2059                 apnContext.setApnSetting(null);
2060                 apnContext.setDataConnectionAc(null);
2061
2062                 // Need to notify disconnect as well, in the case of switching Airplane mode.
2063                 // Otherwise, it would cause 30s delayed to turn on Airplane mode.
2064                 if (mDisconnectPendingCount > 0)
2065                     mDisconnectPendingCount--;
2066
2067                 if (mDisconnectPendingCount == 0) {
2068                     notifyDataDisconnectComplete();
2069                     notifyAllDataDisconnected();
2070                 }
2071                 return;
2072             }
2073         }
2074
2075         // If APN is still enabled, try to bring it back up automatically
2076         if (mAttached.get() && apnContext.isReady() && retryAfterDisconnected(apnContext)) {
2077             SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "false");
2078             // Wait a bit before trying the next APN, so that
2079             // we're not tying up the RIL command channel.
2080             // This also helps in any external dependency to turn off the context.
2081             if(DBG) log("onDisconnectDone: attached, ready and retry after disconnect");
2082             startAlarmForReconnect(getApnDelay(), apnContext);
2083         } else {
2084             boolean restartRadioAfterProvisioning = mPhone.getContext().getResources().getBoolean(
2085                     com.android.internal.R.bool.config_restartRadioAfterProvisioning);
2086
2087             if (apnContext.isProvisioningApn() && restartRadioAfterProvisioning) {
2088                 log("onDisconnectDone: restartRadio after provisioning");
2089                 restartRadio();
2090             }
2091             apnContext.setApnSetting(null);
2092             apnContext.setDataConnectionAc(null);
2093             if (isOnlySingleDcAllowed(mPhone.getServiceState().getRilDataRadioTechnology())) {
2094                 if(DBG) log("onDisconnectDone: isOnlySigneDcAllowed true so setup single apn");
2095                 setupDataOnConnectableApns(Phone.REASON_SINGLE_PDN_ARBITRATION);
2096             } else {
2097                 if(DBG) log("onDisconnectDone: not retrying");
2098             }
2099         }
2100
2101         if (mDisconnectPendingCount > 0)
2102             mDisconnectPendingCount--;
2103
2104         if (mDisconnectPendingCount == 0) {
2105             apnContext.setConcurrentVoiceAndDataAllowed(
2106                     mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed());
2107             notifyDataDisconnectComplete();
2108             notifyAllDataDisconnected();
2109         }
2110
2111     }
2112
2113     /**
2114      * Called when EVENT_DISCONNECT_DC_RETRYING is received.
2115      */
2116     @Override
2117     protected void onDisconnectDcRetrying(int connId, AsyncResult ar) {
2118         // We could just do this in DC!!!
2119         ApnContext apnContext = null;
2120
2121         if (ar.userObj instanceof ApnContext) {
2122             apnContext = (ApnContext) ar.userObj;
2123         } else {
2124             loge("onDisconnectDcRetrying: Invalid ar in onDisconnectDone, ignore");
2125             return;
2126         }
2127
2128         apnContext.setState(DctConstants.State.RETRYING);
2129         if(DBG) log("onDisconnectDcRetrying: apnContext=" + apnContext);
2130
2131         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
2132     }
2133
2134
2135     @Override
2136     protected void onVoiceCallStarted() {
2137         if (DBG) log("onVoiceCallStarted");
2138         mInVoiceCall = true;
2139         if (isConnected() && ! mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
2140             if (DBG) log("onVoiceCallStarted stop polling");
2141             stopNetStatPoll();
2142             stopDataStallAlarm();
2143             notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED);
2144         }
2145     }
2146
2147     @Override
2148     protected void onVoiceCallEnded() {
2149         if (DBG) log("onVoiceCallEnded");
2150         mInVoiceCall = false;
2151         if (isConnected()) {
2152             if (!mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
2153                 startNetStatPoll();
2154                 startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
2155                 notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED);
2156             } else {
2157                 // clean slate after call end.
2158                 resetPollStats();
2159             }
2160         }
2161         // reset reconnect timer
2162         setupDataOnConnectableApns(Phone.REASON_VOICE_CALL_ENDED);
2163     }
2164
2165     @Override
2166     protected void onCleanUpConnection(boolean tearDown, int apnId, String reason) {
2167         if (DBG) log("onCleanUpConnection");
2168         ApnContext apnContext = mApnContexts.get(apnIdToType(apnId));
2169         if (apnContext != null) {
2170             apnContext.setReason(reason);
2171             cleanUpConnection(tearDown, apnContext);
2172         }
2173     }
2174
2175     @Override
2176     protected boolean isConnected() {
2177         for (ApnContext apnContext : mApnContexts.values()) {
2178             if (apnContext.getState() == DctConstants.State.CONNECTED) {
2179                 // At least one context is connected, return true
2180                 return true;
2181             }
2182         }
2183         // There are not any contexts connected, return false
2184         return false;
2185     }
2186
2187     @Override
2188     public boolean isDisconnected() {
2189         for (ApnContext apnContext : mApnContexts.values()) {
2190             if (!apnContext.isDisconnected()) {
2191                 // At least one context was not disconnected return false
2192                 return false;
2193             }
2194         }
2195         // All contexts were disconnected so return true
2196         return true;
2197     }
2198
2199     @Override
2200     protected void notifyDataConnection(String reason) {
2201         if (DBG) log("notifyDataConnection: reason=" + reason);
2202         for (ApnContext apnContext : mApnContexts.values()) {
2203             if (mAttached.get() && apnContext.isReady()) {
2204                 if (DBG) log("notifyDataConnection: type:" + apnContext.getApnType());
2205                 mPhone.notifyDataConnection(reason != null ? reason : apnContext.getReason(),
2206                         apnContext.getApnType());
2207             }
2208         }
2209         notifyOffApnsOfAvailability(reason);
2210     }
2211
2212     /**
2213      * Based on the sim operator numeric, create a list for all possible
2214      * Data Connections and setup the preferredApn.
2215      */
2216     private void createAllApnList() {
2217         mAllApnSettings = new ArrayList<ApnSetting>();
2218         IccRecords r = mIccRecords.get();
2219         String operator = (r != null) ? r.getOperatorNumeric() : "";
2220         if (operator != null) {
2221             String selection = "numeric = '" + operator + "'";
2222             // query only enabled apn.
2223             // carrier_enabled : 1 means enabled apn, 0 disabled apn.
2224             // selection += " and carrier_enabled = 1";
2225             if (DBG) log("createAllApnList: selection=" + selection);
2226
2227             Cursor cursor = mPhone.getContext().getContentResolver().query(
2228                     Telephony.Carriers.CONTENT_URI, null, selection, null, null);
2229
2230             if (cursor != null) {
2231                 if (cursor.getCount() > 0) {
2232                     mAllApnSettings = createApnList(cursor);
2233                 }
2234                 cursor.close();
2235             }
2236         }
2237
2238         addEmergencyApnSetting();
2239
2240         dedupeApnSettings();
2241
2242         if (mAllApnSettings.isEmpty()) {
2243             if (DBG) log("createAllApnList: No APN found for carrier: " + operator);
2244             mPreferredApn = null;
2245             // TODO: What is the right behavior?
2246             //notifyNoData(DataConnection.FailCause.MISSING_UNKNOWN_APN);
2247         } else {
2248             mPreferredApn = getPreferredApn();
2249             if (mPreferredApn != null && !mPreferredApn.numeric.equals(operator)) {
2250                 mPreferredApn = null;
2251                 setPreferredApn(-1);
2252             }
2253             if (DBG) log("createAllApnList: mPreferredApn=" + mPreferredApn);
2254         }
2255         if (DBG) log("createAllApnList: X mAllApnSettings=" + mAllApnSettings);
2256
2257         setDataProfilesAsNeeded();
2258     }
2259
2260     private void dedupeApnSettings() {
2261         ArrayList<ApnSetting> resultApns = new ArrayList<ApnSetting>();
2262
2263         // coalesce APNs if they are similar enough to prevent
2264         // us from bringing up two data calls with the same interface
2265         int i = 0;
2266         while (i < mAllApnSettings.size() - 1) {
2267             ApnSetting first = mAllApnSettings.get(i);
2268             ApnSetting second = null;
2269             int j = i + 1;
2270             while (j < mAllApnSettings.size()) {
2271                 second = mAllApnSettings.get(j);
2272                 if (apnsSimilar(first, second)) {
2273                     ApnSetting newApn = mergeApns(first, second);
2274                     mAllApnSettings.set(i, newApn);
2275                     first = newApn;
2276                     mAllApnSettings.remove(j);
2277                 } else {
2278                     j++;
2279                 }
2280             }
2281             i++;
2282         }
2283     }
2284
2285     //check whether the types of two APN same (even only one type of each APN is same)
2286     private boolean apnTypeSameAny(ApnSetting first, ApnSetting second) {
2287         if(VDBG) {
2288             StringBuilder apnType1 = new StringBuilder(first.apn + ": ");
2289             for(int index1 = 0; index1 < first.types.length; index1++) {
2290                 apnType1.append(first.types[index1]);
2291                 apnType1.append(",");
2292             }
2293
2294             StringBuilder apnType2 = new StringBuilder(second.apn + ": ");
2295             for(int index1 = 0; index1 < second.types.length; index1++) {
2296                 apnType2.append(second.types[index1]);
2297                 apnType2.append(",");
2298             }
2299             log("APN1: is " + apnType1);
2300             log("APN2: is " + apnType2);
2301         }
2302
2303         for(int index1 = 0; index1 < first.types.length; index1++) {
2304             for(int index2 = 0; index2 < second.types.length; index2++) {
2305                 if(first.types[index1].equals(PhoneConstants.APN_TYPE_ALL) ||
2306                         second.types[index2].equals(PhoneConstants.APN_TYPE_ALL) ||
2307                         first.types[index1].equals(second.types[index2])) {
2308                     if(VDBG)log("apnTypeSameAny: return true");
2309                     return true;
2310                 }
2311             }
2312         }
2313
2314         if(VDBG)log("apnTypeSameAny: return false");
2315         return false;
2316     }
2317
2318     // Check if neither mention DUN and are substantially similar
2319     private boolean apnsSimilar(ApnSetting first, ApnSetting second) {
2320         return (first.canHandleType(PhoneConstants.APN_TYPE_DUN) == false &&
2321                 second.canHandleType(PhoneConstants.APN_TYPE_DUN) == false &&
2322                 Objects.equals(first.apn, second.apn) &&
2323                 !apnTypeSameAny(first, second) &&
2324                 xorEquals(first.proxy, second.proxy) &&
2325                 xorEquals(first.port, second.port) &&
2326                 first.carrierEnabled == second.carrierEnabled &&
2327                 first.bearerBitmask == second.bearerBitmask &&
2328                 first.profileId == second.profileId &&
2329                 Objects.equals(first.mvnoType, second.mvnoType) &&
2330                 Objects.equals(first.mvnoMatchData, second.mvnoMatchData) &&
2331                 xorEquals(first.mmsc, second.mmsc) &&
2332                 xorEquals(first.mmsProxy, second.mmsProxy) &&
2333                 xorEquals(first.mmsPort, second.mmsPort));
2334     }
2335
2336     // equal or one is not specified
2337     private boolean xorEquals(String first, String second) {
2338         return (Objects.equals(first, second) ||
2339                 TextUtils.isEmpty(first) ||
2340                 TextUtils.isEmpty(second));
2341     }
2342
2343     private ApnSetting mergeApns(ApnSetting dest, ApnSetting src) {
2344         ArrayList<String> resultTypes = new ArrayList<String>();
2345         resultTypes.addAll(Arrays.asList(dest.types));
2346         for (String srcType : src.types) {
2347             if (resultTypes.contains(srcType) == false) resultTypes.add(srcType);
2348         }
2349         String mmsc = (TextUtils.isEmpty(dest.mmsc) ? src.mmsc : dest.mmsc);
2350         String mmsProxy = (TextUtils.isEmpty(dest.mmsProxy) ? src.mmsProxy : dest.mmsProxy);
2351         String mmsPort = (TextUtils.isEmpty(dest.mmsPort) ? src.mmsPort : dest.mmsPort);
2352         String proxy = (TextUtils.isEmpty(dest.proxy) ? src.proxy : dest.proxy);
2353         String port = (TextUtils.isEmpty(dest.port) ? src.port : dest.port);
2354         String protocol = src.protocol.equals("IPV4V6") ? src.protocol : dest.protocol;
2355         String roamingProtocol = src.roamingProtocol.equals("IPV4V6") ? src.roamingProtocol :
2356                 dest.roamingProtocol;
2357         int bearerBitmask = (dest.bearerBitmask == 0 || src.bearerBitmask == 0) ?
2358                 0 : (dest.bearerBitmask | src.bearerBitmask);
2359
2360         return new ApnSetting(dest.id, dest.numeric, dest.carrier, dest.apn,
2361                 proxy, port, mmsc, mmsProxy, mmsPort, dest.user, dest.password,
2362                 dest.authType, resultTypes.toArray(new String[0]), protocol,
2363                 roamingProtocol, dest.carrierEnabled, 0, bearerBitmask, dest.profileId,
2364                 (dest.modemCognitive || src.modemCognitive), dest.maxConns, dest.waitTime,
2365                 dest.maxConnsTime, dest.mtu, dest.mvnoType, dest.mvnoMatchData);
2366     }
2367
2368     /** Return the DC AsyncChannel for the new data connection */
2369     private DcAsyncChannel createDataConnection() {
2370         if (DBG) log("createDataConnection E");
2371
2372         int id = mUniqueIdGenerator.getAndIncrement();
2373         DataConnection conn = DataConnection.makeDataConnection(mPhone, id,
2374                                                 this, mDcTesterFailBringUpAll, mDcc);
2375         mDataConnections.put(id, conn);
2376         DcAsyncChannel dcac = new DcAsyncChannel(conn, LOG_TAG);
2377         int status = dcac.fullyConnectSync(mPhone.getContext(), this, conn.getHandler());
2378         if (status == AsyncChannel.STATUS_SUCCESSFUL) {
2379             mDataConnectionAcHashMap.put(dcac.getDataConnectionIdSync(), dcac);
2380         } else {
2381             loge("createDataConnection: Could not connect to dcac=" + dcac + " status=" + status);
2382         }
2383
2384         if (DBG) log("createDataConnection() X id=" + id + " dc=" + conn);
2385         return dcac;
2386     }
2387
2388     private void destroyDataConnections() {
2389         if(mDataConnections != null) {
2390             if (DBG) log("destroyDataConnections: clear mDataConnectionList");
2391             mDataConnections.clear();
2392         } else {
2393             if (DBG) log("destroyDataConnections: mDataConnecitonList is empty, ignore");
2394         }
2395     }
2396
2397     /**
2398      * Build a list of APNs to be used to create PDP's.
2399      *
2400      * @param requestedApnType
2401      * @return waitingApns list to be used to create PDP
2402      *          error when waitingApns.isEmpty()
2403      */
2404     private ArrayList<ApnSetting> buildWaitingApns(String requestedApnType, int radioTech) {
2405         if (DBG) log("buildWaitingApns: E requestedApnType=" + requestedApnType);
2406         ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>();
2407
2408         if (requestedApnType.equals(PhoneConstants.APN_TYPE_DUN)) {
2409             ApnSetting dun = fetchDunApn();
2410             if (dun != null) {
2411                 apnList.add(dun);
2412                 if (DBG) log("buildWaitingApns: X added APN_TYPE_DUN apnList=" + apnList);
2413                 return apnList;
2414             }
2415         }
2416
2417         IccRecords r = mIccRecords.get();
2418         String operator = (r != null) ? r.getOperatorNumeric() : "";
2419
2420         // This is a workaround for a bug (7305641) where we don't failover to other
2421         // suitable APNs if our preferred APN fails.  On prepaid ATT sims we need to
2422         // failover to a provisioning APN, but once we've used their default data
2423         // connection we are locked to it for life.  This change allows ATT devices
2424         // to say they don't want to use preferred at all.
2425         boolean usePreferred = true;
2426         try {
2427             usePreferred = ! mPhone.getContext().getResources().getBoolean(com.android.
2428                     internal.R.bool.config_dontPreferApn);
2429         } catch (Resources.NotFoundException e) {
2430             if (DBG) log("buildWaitingApns: usePreferred NotFoundException set to true");
2431             usePreferred = true;
2432         }
2433         if (DBG) {
2434             log("buildWaitingApns: usePreferred=" + usePreferred
2435                     + " canSetPreferApn=" + mCanSetPreferApn
2436                     + " mPreferredApn=" + mPreferredApn
2437                     + " operator=" + operator + " radioTech=" + radioTech
2438                     + " IccRecords r=" + r);
2439         }
2440
2441         if (usePreferred && mCanSetPreferApn && mPreferredApn != null &&
2442                 mPreferredApn.canHandleType(requestedApnType)) {
2443             if (DBG) {
2444                 log("buildWaitingApns: Preferred APN:" + operator + ":"
2445                         + mPreferredApn.numeric + ":" + mPreferredApn);
2446             }
2447             if (mPreferredApn.numeric.equals(operator)) {
2448                 if (ServiceState.bitmaskHasTech(mPreferredApn.bearerBitmask, radioTech)) {
2449                     apnList.add(mPreferredApn);
2450                     if (DBG) log("buildWaitingApns: X added preferred apnList=" + apnList);
2451                     return apnList;
2452                 } else {
2453                     if (DBG) log("buildWaitingApns: no preferred APN");
2454                     setPreferredApn(-1);
2455                     mPreferredApn = null;
2456                 }
2457             } else {
2458                 if (DBG) log("buildWaitingApns: no preferred APN");
2459                 setPreferredApn(-1);
2460                 mPreferredApn = null;
2461             }
2462         }
2463         if (mAllApnSettings != null) {
2464             if (DBG) log("buildWaitingApns: mAllApnSettings=" + mAllApnSettings);
2465             for (ApnSetting apn : mAllApnSettings) {
2466                 if (DBG) log("buildWaitingApns: apn=" + apn);
2467                 if (apn.canHandleType(requestedApnType)) {
2468                     if (ServiceState.bitmaskHasTech(apn.bearerBitmask, radioTech)) {
2469                         if (DBG) log("buildWaitingApns: adding apn=" + apn.toString());
2470                         apnList.add(apn);
2471                     } else {
2472                         if (DBG) {
2473                             log("buildWaitingApns: bearerBitmask:" + apn.bearerBitmask + " does " +
2474                                     "not include radioTech:" + radioTech);
2475                         }
2476                     }
2477                 } else {
2478                 if (DBG) {
2479                     log("buildWaitingApns: couldn't handle requesedApnType="
2480                             + requestedApnType);
2481                 }
2482             }
2483             }
2484         } else {
2485             loge("mAllApnSettings is empty!");
2486         }
2487         if (DBG) log("buildWaitingApns: X apnList=" + apnList);
2488         return apnList;
2489     }
2490
2491     private String apnListToString (ArrayList<ApnSetting> apns) {
2492         StringBuilder result = new StringBuilder();
2493         for (int i = 0, size = apns.size(); i < size; i++) {
2494             result.append('[')
2495                   .append(apns.get(i).toString())
2496                   .append(']');
2497         }
2498         return result.toString();
2499     }
2500
2501     private void setPreferredApn(int pos) {
2502         if (!mCanSetPreferApn) {
2503             log("setPreferredApn: X !canSEtPreferApn");
2504             return;
2505         }
2506
2507         String subId = Long.toString(mPhone.getSubId());
2508         Uri uri = Uri.withAppendedPath(PREFERAPN_NO_UPDATE_URI_USING_SUBID, subId);
2509         log("setPreferredApn: delete");
2510         ContentResolver resolver = mPhone.getContext().getContentResolver();
2511         resolver.delete(uri, null, null);
2512
2513         if (pos >= 0) {
2514             log("setPreferredApn: insert");
2515             ContentValues values = new ContentValues();
2516             values.put(APN_ID, pos);
2517             resolver.insert(uri, values);
2518         }
2519     }
2520
2521     private ApnSetting getPreferredApn() {
2522         if (mAllApnSettings.isEmpty()) {
2523             log("getPreferredApn: X not found mAllApnSettings.isEmpty");
2524             return null;
2525         }
2526
2527         String subId = Long.toString(mPhone.getSubId());
2528         Uri uri = Uri.withAppendedPath(PREFERAPN_NO_UPDATE_URI_USING_SUBID, subId);
2529         Cursor cursor = mPhone.getContext().getContentResolver().query(
2530                 uri, new String[] { "_id", "name", "apn" },
2531                 null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
2532
2533         if (cursor != null) {
2534             mCanSetPreferApn = true;
2535         } else {
2536             mCanSetPreferApn = false;
2537         }
2538         log("getPreferredApn: mRequestedApnType=" + mRequestedApnType + " cursor=" + cursor
2539                 + " cursor.count=" + ((cursor != null) ? cursor.getCount() : 0));
2540
2541         if (mCanSetPreferApn && cursor.getCount() > 0) {
2542             int pos;
2543             cursor.moveToFirst();
2544             pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID));
2545             for(ApnSetting p : mAllApnSettings) {
2546                 log("getPreferredApn: apnSetting=" + p);
2547                 if (p.id == pos && p.canHandleType(mRequestedApnType)) {
2548                     log("getPreferredApn: X found apnSetting" + p);
2549                     cursor.close();
2550                     return p;
2551                 }
2552             }
2553         }
2554
2555         if (cursor != null) {
2556             cursor.close();
2557         }
2558
2559         log("getPreferredApn: X not found");
2560         return null;
2561     }
2562
2563     @Override
2564     public void handleMessage (Message msg) {
2565         if (DBG) log("handleMessage msg=" + msg);
2566
2567         if (!mPhone.mIsTheCurrentActivePhone || mIsDisposed) {
2568             loge("handleMessage: Ignore GSM msgs since GSM phone is inactive");
2569             return;
2570         }
2571
2572         switch (msg.what) {
2573             case DctConstants.EVENT_RECORDS_LOADED:
2574                 onRecordsLoaded();
2575                 break;
2576
2577             case DctConstants.EVENT_DATA_CONNECTION_DETACHED:
2578                 onDataConnectionDetached();
2579                 break;
2580
2581             case DctConstants.EVENT_DATA_CONNECTION_ATTACHED:
2582                 onDataConnectionAttached();
2583                 break;
2584
2585             case DctConstants.EVENT_DO_RECOVERY:
2586                 doRecovery();
2587                 break;
2588
2589             case DctConstants.EVENT_APN_CHANGED:
2590                 onApnChanged();
2591                 break;
2592
2593             case DctConstants.EVENT_PS_RESTRICT_ENABLED:
2594                 /**
2595                  * We don't need to explicitly to tear down the PDP context
2596                  * when PS restricted is enabled. The base band will deactive
2597                  * PDP context and notify us with PDP_CONTEXT_CHANGED.
2598                  * But we should stop the network polling and prevent reset PDP.
2599                  */
2600                 if (DBG) log("EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted);
2601                 stopNetStatPoll();
2602                 stopDataStallAlarm();
2603                 mIsPsRestricted = true;
2604                 break;
2605
2606             case DctConstants.EVENT_PS_RESTRICT_DISABLED:
2607                 /**
2608                  * When PS restrict is removed, we need setup PDP connection if
2609                  * PDP connection is down.
2610                  */
2611                 if (DBG) log("EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted);
2612                 mIsPsRestricted  = false;
2613                 if (isConnected()) {
2614                     startNetStatPoll();
2615                     startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
2616                 } else {
2617                     // TODO: Should all PDN states be checked to fail?
2618                     if (mState == DctConstants.State.FAILED) {
2619                         cleanUpAllConnections(false, Phone.REASON_PS_RESTRICT_ENABLED);
2620                         mReregisterOnReconnectFailure = false;
2621                     }
2622                     ApnContext apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_DEFAULT);
2623                     if (apnContext != null) {
2624                         apnContext.setReason(Phone.REASON_PS_RESTRICT_ENABLED);
2625                         trySetupData(apnContext);
2626                     } else {
2627                         loge("**** Default ApnContext not found ****");
2628                         if (Build.IS_DEBUGGABLE) {
2629                             throw new RuntimeException("Default ApnContext not found");
2630                         }
2631                     }
2632                 }
2633                 break;
2634
2635             case DctConstants.EVENT_TRY_SETUP_DATA:
2636                 if (msg.obj instanceof ApnContext) {
2637                     onTrySetupData((ApnContext)msg.obj);
2638                 } else if (msg.obj instanceof String) {
2639                     onTrySetupData((String)msg.obj);
2640                 } else {
2641                     loge("EVENT_TRY_SETUP request w/o apnContext or String");
2642                 }
2643                 break;
2644
2645             case DctConstants.EVENT_CLEAN_UP_CONNECTION:
2646                 boolean tearDown = (msg.arg1 == 0) ? false : true;
2647                 if (DBG) log("EVENT_CLEAN_UP_CONNECTION tearDown=" + tearDown);
2648                 if (msg.obj instanceof ApnContext) {
2649                     cleanUpConnection(tearDown, (ApnContext)msg.obj);
2650                 } else {
2651                     loge("EVENT_CLEAN_UP_CONNECTION request w/o apn context, call super");
2652                     super.handleMessage(msg);
2653                 }
2654                 break;
2655             case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE:
2656                 boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
2657                 onSetInternalDataEnabled(enabled, (Message) msg.obj);
2658                 break;
2659
2660             case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS:
2661                 Message mCause = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS, null);
2662                 if ((msg.obj != null) && (msg.obj instanceof String)) {
2663                     mCause.obj = msg.obj;
2664                 }
2665                 super.handleMessage(mCause);
2666                 break;
2667
2668             case DctConstants.EVENT_DATA_RAT_CHANGED:
2669                 //May new Network allow setupData, so try it here
2670                 setupDataOnConnectableApns(Phone.REASON_NW_TYPE_CHANGED,
2671                         RetryFailures.ONLY_ON_CHANGE);
2672                 break;
2673
2674             case DctConstants.CMD_CLEAR_PROVISIONING_SPINNER:
2675                 // Check message sender intended to clear the current spinner.
2676                 if (mProvisioningSpinner == msg.obj) {
2677                     mProvisioningSpinner.dismiss();
2678                     mProvisioningSpinner = null;
2679                 }
2680                 break;
2681
2682             default:
2683                 // handle the message in the super class DataConnectionTracker
2684                 super.handleMessage(msg);
2685                 break;
2686         }
2687     }
2688
2689     protected int getApnProfileID(String apnType) {
2690         if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IMS)) {
2691             return RILConstants.DATA_PROFILE_IMS;
2692         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_FOTA)) {
2693             return RILConstants.DATA_PROFILE_FOTA;
2694         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_CBS)) {
2695             return RILConstants.DATA_PROFILE_CBS;
2696         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IA)) {
2697             return RILConstants.DATA_PROFILE_DEFAULT; // DEFAULT for now
2698         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_DUN)) {
2699             return RILConstants.DATA_PROFILE_TETHERED;
2700         } else {
2701             return RILConstants.DATA_PROFILE_DEFAULT;
2702         }
2703     }
2704
2705     private int getCellLocationId() {
2706         int cid = -1;
2707         CellLocation loc = mPhone.getCellLocation();
2708
2709         if (loc != null) {
2710             if (loc instanceof GsmCellLocation) {
2711                 cid = ((GsmCellLocation)loc).getCid();
2712             } else if (loc instanceof CdmaCellLocation) {
2713                 cid = ((CdmaCellLocation)loc).getBaseStationId();
2714             }
2715         }
2716         return cid;
2717     }
2718
2719     private IccRecords getUiccRecords(int appFamily) {
2720         return mUiccController.getIccRecords(mPhone.getPhoneId(), appFamily);
2721     }
2722
2723
2724     @Override
2725     protected void onUpdateIcc() {
2726         if (mUiccController == null ) {
2727             return;
2728         }
2729
2730         IccRecords newIccRecords = getUiccRecords(UiccController.APP_FAM_3GPP);
2731
2732         IccRecords r = mIccRecords.get();
2733         if (r != newIccRecords) {
2734             if (r != null) {
2735                 log("Removing stale icc objects.");
2736                 r.unregisterForRecordsLoaded(this);
2737                 mIccRecords.set(null);
2738             }
2739             if (newIccRecords != null) {
2740                 log("New records found");
2741                 mIccRecords.set(newIccRecords);
2742                 newIccRecords.registerForRecordsLoaded(
2743                         this, DctConstants.EVENT_RECORDS_LOADED, null);
2744             } else {
2745                 onSimNotReady();
2746             }
2747         }
2748     }
2749
2750     public void update() {
2751         log("update sub = " + mPhone.getSubId());
2752         log("update(): Active DDS, register for all events now!");
2753         registerForAllEvents();
2754         onUpdateIcc();
2755
2756         mUserDataEnabled = getDataEnabled();
2757
2758         if (mPhone instanceof CDMALTEPhone) {
2759             ((CDMALTEPhone)mPhone).updateCurrentCarrierInProvider();
2760         } else if (mPhone instanceof GSMPhone) {
2761             ((GSMPhone)mPhone).updateCurrentCarrierInProvider();
2762         } else {
2763             log("Phone object is not MultiSim. This should not hit!!!!");
2764         }
2765     }
2766
2767     @Override
2768     public void cleanUpAllConnections(String cause) {
2769         cleanUpAllConnections(cause, null);
2770     }
2771
2772     public void updateRecords() {
2773         onUpdateIcc();
2774     }
2775
2776     public void cleanUpAllConnections(String cause, Message disconnectAllCompleteMsg) {
2777         log("cleanUpAllConnections");
2778         if (disconnectAllCompleteMsg != null) {
2779             mDisconnectAllCompleteMsgList.add(disconnectAllCompleteMsg);
2780         }
2781
2782         Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
2783         msg.obj = cause;
2784         sendMessage(msg);
2785     }
2786
2787     protected void notifyDataDisconnectComplete() {
2788         log("notifyDataDisconnectComplete");
2789         for (Message m: mDisconnectAllCompleteMsgList) {
2790             m.sendToTarget();
2791         }
2792         mDisconnectAllCompleteMsgList.clear();
2793     }
2794
2795
2796     protected void notifyAllDataDisconnected() {
2797         sEnableFailFastRefCounter = 0;
2798         mFailFast = false;
2799         mAllDataDisconnectedRegistrants.notifyRegistrants();
2800     }
2801
2802     public void registerForAllDataDisconnected(Handler h, int what, Object obj) {
2803         mAllDataDisconnectedRegistrants.addUnique(h, what, obj);
2804
2805         if (isDisconnected()) {
2806             log("notify All Data Disconnected");
2807             notifyAllDataDisconnected();
2808         }
2809     }
2810
2811     public void unregisterForAllDataDisconnected(Handler h) {
2812         mAllDataDisconnectedRegistrants.remove(h);
2813     }
2814
2815
2816     @Override
2817     protected void onSetInternalDataEnabled(boolean enable) {
2818         if (DBG) log("onSetInternalDataEnabled: enabled=" + enable);
2819         onSetInternalDataEnabled(enable, null);
2820     }
2821
2822     protected void onSetInternalDataEnabled(boolean enabled, Message onCompleteMsg) {
2823         if (DBG) log("onSetInternalDataEnabled: enabled=" + enabled);
2824         boolean sendOnComplete = true;
2825
2826         synchronized (mDataEnabledLock) {
2827             mInternalDataEnabled = enabled;
2828             if (enabled) {
2829                 log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
2830                 onTrySetupData(Phone.REASON_DATA_ENABLED);
2831             } else {
2832                 sendOnComplete = false;
2833                 log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
2834                 cleanUpAllConnections(null, onCompleteMsg);
2835             }
2836         }
2837
2838         if (sendOnComplete) {
2839             if (onCompleteMsg != null) {
2840                 onCompleteMsg.sendToTarget();
2841             }
2842         }
2843     }
2844
2845     public boolean setInternalDataEnabledFlag(boolean enable) {
2846         if (DBG) log("setInternalDataEnabledFlag(" + enable + ")");
2847
2848         if (mInternalDataEnabled != enable) {
2849             mInternalDataEnabled = enable;
2850         }
2851         return true;
2852     }
2853
2854     @Override
2855     public boolean setInternalDataEnabled(boolean enable) {
2856         return setInternalDataEnabled(enable, null);
2857     }
2858
2859     public boolean setInternalDataEnabled(boolean enable, Message onCompleteMsg) {
2860         if (DBG) log("setInternalDataEnabled(" + enable + ")");
2861
2862         Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE, onCompleteMsg);
2863         msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
2864         sendMessage(msg);
2865         return true;
2866     }
2867
2868     public void setDataAllowed(boolean enable, Message response) {
2869          if (DBG) log("setDataAllowed: enable=" + enable);
2870          mIsCleanupRequired = !enable;
2871          mPhone.mCi.setDataAllowed(enable, response);
2872          mInternalDataEnabled = enable;
2873     }
2874
2875     @Override
2876     protected void log(String s) {
2877         Rlog.d(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s);
2878     }
2879
2880     @Override
2881     protected void loge(String s) {
2882         Rlog.e(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s);
2883     }
2884
2885     @Override
2886     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2887         pw.println("DcTracker extends:");
2888         super.dump(fd, pw, args);
2889         pw.println(" mReregisterOnReconnectFailure=" + mReregisterOnReconnectFailure);
2890         pw.println(" canSetPreferApn=" + mCanSetPreferApn);
2891         pw.println(" mApnObserver=" + mApnObserver);
2892         pw.println(" getOverallState=" + getOverallState());
2893         pw.println(" mDataConnectionAsyncChannels=%s\n" + mDataConnectionAcHashMap);
2894         pw.println(" mAttached=" + mAttached.get());
2895     }
2896
2897     @Override
2898     public String[] getPcscfAddress(String apnType) {
2899         log("getPcscfAddress()");
2900         ApnContext apnContext = null;
2901
2902         if(apnType == null){
2903             log("apnType is null, return null");
2904             return null;
2905         }
2906
2907         if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_EMERGENCY)) {
2908             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_EMERGENCY);
2909         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IMS)) {
2910             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_IMS);
2911         } else {
2912             log("apnType is invalid, return null");
2913             return null;
2914         }
2915
2916         if (apnContext == null) {
2917             log("apnContext is null, return null");
2918             return null;
2919         }
2920
2921         DcAsyncChannel dcac = apnContext.getDcAc();
2922         String[] result = null;
2923
2924         if (dcac != null) {
2925             result = dcac.getPcscfAddr();
2926
2927             for (int i = 0; i < result.length; i++) {
2928                 log("Pcscf[" + i + "]: " + result[i]);
2929             }
2930             return result;
2931         }
2932         return null;
2933     }
2934
2935     @Override
2936     public void setImsRegistrationState(boolean registered) {
2937         log("setImsRegistrationState - mImsRegistrationState(before): "+ mImsRegistrationState
2938                 + ", registered(current) : " + registered);
2939
2940         if (mPhone == null) return;
2941
2942         ServiceStateTracker sst = mPhone.getServiceStateTracker();
2943         if (sst == null) return;
2944
2945         sst.setImsRegistrationState(registered);
2946     }
2947
2948     /**
2949      * Read APN configuration from Telephony.db for Emergency APN
2950      * All opertors recognize the connection request for EPDN based on APN type
2951      * PLMN name,APN name are not mandatory parameters
2952      */
2953     private void initEmergencyApnSetting() {
2954         // Operator Numeric is not available when sim records are not loaded.
2955         // Query Telephony.db with APN type as EPDN request does not
2956         // require APN name, plmn and all operators support same APN config.
2957         // DB will contain only one entry for Emergency APN
2958         String selection = "type=\"emergency\"";
2959         Cursor cursor = mPhone.getContext().getContentResolver().query(
2960                 Telephony.Carriers.CONTENT_URI, null, selection, null, null);
2961
2962         if (cursor != null) {
2963             if (cursor.getCount() > 0) {
2964                 if (cursor.moveToFirst()) {
2965                     mEmergencyApn = makeApnSetting(cursor);
2966                 }
2967             }
2968             cursor.close();
2969         }
2970     }
2971
2972     /**
2973      * Add the Emergency APN settings to APN settings list
2974      */
2975     private void addEmergencyApnSetting() {
2976         if(mEmergencyApn != null) {
2977             if(mAllApnSettings == null) {
2978                 mAllApnSettings = new ArrayList<ApnSetting>();
2979             } else {
2980                 boolean hasEmergencyApn = false;
2981                 for (ApnSetting apn : mAllApnSettings) {
2982                     if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_EMERGENCY)) {
2983                         hasEmergencyApn = true;
2984                         break;
2985                     }
2986                 }
2987
2988                 if(hasEmergencyApn == false) {
2989                     mAllApnSettings.add(mEmergencyApn);
2990                 } else {
2991                     log("addEmergencyApnSetting - E-APN setting is already present");
2992                 }
2993             }
2994         }
2995     }
2996
2997     private void cleanUpConnectionsOnUpdatedApns(boolean tearDown) {
2998         if (DBG) log("cleanUpConnectionsOnUpdatedApns: tearDown=" + tearDown);
2999         if (mAllApnSettings.isEmpty()) {
3000             cleanUpAllConnections(tearDown, Phone.REASON_APN_CHANGED);
3001         } else {
3002             for (ApnContext apnContext : mApnContexts.values()) {
3003                 if (VDBG) log("cleanUpConnectionsOnUpdatedApns for "+ apnContext);
3004
3005                 boolean cleanUpApn = true;
3006                 ArrayList<ApnSetting> currentWaitingApns = apnContext.getWaitingApns();
3007
3008                 if ((currentWaitingApns != null) && (!apnContext.isDisconnected())) {
3009                     int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
3010                     ArrayList<ApnSetting> waitingApns = buildWaitingApns(
3011                             apnContext.getApnType(), radioTech);
3012                     if (VDBG) log("new waitingApns:" + waitingApns);
3013                     if (waitingApns.size() == currentWaitingApns.size()) {
3014                         cleanUpApn = false;
3015                         for (int i = 0; i < waitingApns.size(); i++) {
3016                             if (!currentWaitingApns.get(i).equals(waitingApns.get(i))) {
3017                                 if (VDBG) log("new waiting apn is different at " + i);
3018                                 cleanUpApn = true;
3019                                 apnContext.setWaitingApns(waitingApns);
3020                                 break;
3021                             }
3022                         }
3023                     }
3024                 }
3025
3026                 if (cleanUpApn) {
3027                     apnContext.setReason(Phone.REASON_APN_CHANGED);
3028                     cleanUpConnection(true, apnContext);
3029                 }
3030             }
3031         }
3032
3033         if (!isConnected()) {
3034             stopNetStatPoll();
3035             stopDataStallAlarm();
3036         }
3037
3038         mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
3039
3040         if (DBG) log("mDisconnectPendingCount = " + mDisconnectPendingCount);
3041         if (tearDown && mDisconnectPendingCount == 0) {
3042             notifyDataDisconnectComplete();
3043             notifyAllDataDisconnected();
3044         }
3045     }
3046 }