GsmDataConnectionTracker.java revision 887f2e401edb84867b8ee4026306269abb0f909b
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
17package com.android.internal.telephony.gsm;
18
19import android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.SharedPreferences;
28import android.database.ContentObserver;
29import android.database.Cursor;
30import android.net.ConnectivityManager;
31import android.net.IConnectivityManager;
32import android.net.NetworkInfo;
33import android.net.TrafficStats;
34import android.net.Uri;
35import android.net.wifi.WifiManager;
36import android.os.AsyncResult;
37import android.os.Message;
38import android.os.RemoteException;
39import android.os.ServiceManager;
40import android.os.SystemClock;
41import android.os.SystemProperties;
42import android.preference.PreferenceManager;
43import android.provider.Settings;
44import android.provider.Telephony;
45import android.telephony.ServiceState;
46import android.telephony.TelephonyManager;
47import android.telephony.gsm.GsmCellLocation;
48import android.util.EventLog;
49import android.util.Log;
50
51import com.android.internal.R;
52import com.android.internal.telephony.DataCallState;
53import com.android.internal.telephony.DataConnection;
54import com.android.internal.telephony.DataConnectionTracker;
55import com.android.internal.telephony.Phone;
56import com.android.internal.telephony.RetryManager;
57import com.android.internal.telephony.EventLogTags;
58import com.android.internal.telephony.DataConnection.FailCause;
59
60import java.io.IOException;
61import java.util.ArrayList;
62
63/**
64 * {@hide}
65 */
66public final class GsmDataConnectionTracker extends DataConnectionTracker {
67    protected final String LOG_TAG = "GSM";
68
69    private GSMPhone mGsmPhone;
70    /**
71     * Handles changes to the APN db.
72     */
73    private class ApnChangeObserver extends ContentObserver {
74        public ApnChangeObserver () {
75            super(mDataConnectionTracker);
76        }
77
78        @Override
79        public void onChange(boolean selfChange) {
80            sendMessage(obtainMessage(EVENT_APN_CHANGED));
81        }
82    }
83
84    //***** Instance Variables
85
86    // Indicates baseband will not auto-attach
87    private boolean noAutoAttach = false;
88
89    private boolean mReregisterOnReconnectFailure = false;
90    private ContentResolver mResolver;
91
92    private boolean mPingTestActive = false;
93    // Count of PDP reset attempts; reset when we see incoming,
94    // call reRegisterNetwork, or pingTest succeeds.
95    private int mPdpResetCount = 0;
96    private boolean mIsScreenOn = true;
97
98    /** Delay between APN attempts */
99    protected static final int APN_DELAY_MILLIS = 5000;
100
101    //useful for debugging
102    boolean failNextConnect = false;
103
104    /**
105     * allApns holds all apns for this sim spn, retrieved from
106     * the Carrier DB.
107     *
108     * Create once after simcard info is loaded
109     */
110    private ArrayList<ApnSetting> allApns = null;
111
112    /**
113     * waitingApns holds all apns that are waiting to be connected
114     *
115     * It is a subset of allApns and has the same format
116     */
117    private ArrayList<ApnSetting> waitingApns = null;
118
119    private ApnSetting preferredApn = null;
120
121    /* Currently active APN */
122    protected ApnSetting mActiveApn;
123
124    /**
125     * pdpList holds all the PDP connection, i.e. IP Link in GPRS
126     */
127    private ArrayList<DataConnection> pdpList;
128
129    /** Currently active DataConnection */
130    private GsmDataConnection mActivePdp;
131
132    /** Is packet service restricted by network */
133    private boolean mIsPsRestricted = false;
134
135    //***** Constants
136
137    // TODO: Increase this to match the max number of simultaneous
138    // PDP contexts we plan to support.
139    /**
140     * Pool size of DataConnection objects.
141     */
142    private static final int PDP_CONNECTION_POOL_SIZE = 1;
143
144    private static final int POLL_PDP_MILLIS = 5 * 1000;
145
146    private static final String INTENT_RECONNECT_ALARM = "com.android.internal.telephony.gprs-reconnect";
147    private static final String INTENT_RECONNECT_ALARM_EXTRA_REASON = "reason";
148
149    static final Uri PREFERAPN_URI = Uri.parse("content://telephony/carriers/preferapn");
150    static final String APN_ID = "apn_id";
151    private boolean canSetPreferApn = false;
152
153    // for tracking retries on the default APN
154    private RetryManager mDefaultRetryManager;
155    // for tracking retries on a secondary APN
156    private RetryManager mSecondaryRetryManager;
157
158    BroadcastReceiver mIntentReceiver = new BroadcastReceiver ()
159    {
160        @Override
161        public void onReceive(Context context, Intent intent)
162        {
163            String action = intent.getAction();
164            if (action.equals(Intent.ACTION_SCREEN_ON)) {
165                mIsScreenOn = true;
166                stopNetStatPoll();
167                startNetStatPoll();
168            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
169                mIsScreenOn = false;
170                stopNetStatPoll();
171                startNetStatPoll();
172            } else if (action.equals((INTENT_RECONNECT_ALARM))) {
173                Log.d(LOG_TAG, "GPRS reconnect alarm. Previous state was " + state);
174
175                String reason = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON);
176                if (state == State.FAILED) {
177                    Message msg = obtainMessage(EVENT_CLEAN_UP_CONNECTION);
178                    msg.arg1 = 0; // tearDown is false
179                    msg.obj = (String) reason;
180                    sendMessage(msg);
181                }
182                sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA));
183            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
184                final android.net.NetworkInfo networkInfo = (NetworkInfo)
185                        intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
186                mIsWifiConnected = (networkInfo != null && networkInfo.isConnected());
187            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
188                final boolean enabled = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
189                        WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_ENABLED;
190
191                if (!enabled) {
192                    // when wifi got disabled, the NETWORK_STATE_CHANGED_ACTION
193                    // quit and won't report disconnected til next enabling.
194                    mIsWifiConnected = false;
195                }
196            }
197        }
198    };
199
200    /** Watches for changes to the APN db. */
201    private ApnChangeObserver apnObserver;
202
203    //***** Constructor
204
205    GsmDataConnectionTracker(GSMPhone p) {
206        super(p);
207        mGsmPhone = p;
208        p.mCM.registerForAvailable (this, EVENT_RADIO_AVAILABLE, null);
209        p.mCM.registerForOffOrNotAvailable(this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
210        p.mSIMRecords.registerForRecordsLoaded(this, EVENT_RECORDS_LOADED, null);
211        p.mCM.registerForDataStateChanged (this, EVENT_DATA_STATE_CHANGED, null);
212        p.mCT.registerForVoiceCallEnded (this, EVENT_VOICE_CALL_ENDED, null);
213        p.mCT.registerForVoiceCallStarted (this, EVENT_VOICE_CALL_STARTED, null);
214        p.mSST.registerForGprsAttached(this, EVENT_GPRS_ATTACHED, null);
215        p.mSST.registerForGprsDetached(this, EVENT_GPRS_DETACHED, null);
216        p.mSST.registerForRoamingOn(this, EVENT_ROAMING_ON, null);
217        p.mSST.registerForRoamingOff(this, EVENT_ROAMING_OFF, null);
218        p.mSST.registerForPsRestrictedEnabled(this, EVENT_PS_RESTRICT_ENABLED, null);
219        p.mSST.registerForPsRestrictedDisabled(this, EVENT_PS_RESTRICT_DISABLED, null);
220
221        IntentFilter filter = new IntentFilter();
222        filter.addAction(INTENT_RECONNECT_ALARM);
223        filter.addAction(Intent.ACTION_SCREEN_ON);
224        filter.addAction(Intent.ACTION_SCREEN_OFF);
225        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
226        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
227
228        // TODO: Why is this registering the phone as the receiver of the intent
229        //       and not its own handler?
230        p.getContext().registerReceiver(mIntentReceiver, filter, null, p);
231
232
233        mDataConnectionTracker = this;
234        mResolver = phone.getContext().getContentResolver();
235
236        apnObserver = new ApnChangeObserver();
237        p.getContext().getContentResolver().registerContentObserver(
238                Telephony.Carriers.CONTENT_URI, true, apnObserver);
239
240        createAllPdpList();
241
242        // This preference tells us 1) initial condition for "dataEnabled",
243        // and 2) whether the RIL will setup the baseband to auto-PS attach.
244        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(phone.getContext());
245        boolean dataEnabledSetting = true;
246        try {
247            dataEnabledSetting = IConnectivityManager.Stub.asInterface(ServiceManager.
248                getService(Context.CONNECTIVITY_SERVICE)).getMobileDataEnabled();
249        } catch (Exception e) {
250            // nothing to do - use the old behavior and leave data on
251        }
252        dataEnabled[APN_DEFAULT_ID] = !sp.getBoolean(GSMPhone.DATA_DISABLED_ON_BOOT_KEY, false) &&
253                dataEnabledSetting;
254        if (dataEnabled[APN_DEFAULT_ID]) {
255            enabledCount++;
256        }
257        noAutoAttach = !dataEnabled[APN_DEFAULT_ID];
258
259        if (!mRetryMgr.configure(SystemProperties.get("ro.gsm.data_retry_config"))) {
260            if (!mRetryMgr.configure(DEFAULT_DATA_RETRY_CONFIG)) {
261                // Should never happen, log an error and default to a simple linear sequence.
262                Log.e(LOG_TAG, "Could not configure using DEFAULT_DATA_RETRY_CONFIG="
263                        + DEFAULT_DATA_RETRY_CONFIG);
264                mRetryMgr.configure(20, 2000, 1000);
265            }
266        }
267
268        mDefaultRetryManager = mRetryMgr;
269        mSecondaryRetryManager = new RetryManager();
270
271        if (!mSecondaryRetryManager.configure(SystemProperties.get(
272                "ro.gsm.2nd_data_retry_config"))) {
273            if (!mSecondaryRetryManager.configure(SECONDARY_DATA_RETRY_CONFIG)) {
274                // Should never happen, log an error and default to a simple sequence.
275                Log.e(LOG_TAG, "Could note configure using SECONDARY_DATA_RETRY_CONFIG="
276                        + SECONDARY_DATA_RETRY_CONFIG);
277                mSecondaryRetryManager.configure("max_retries=3, 333, 333, 333");
278            }
279        }
280    }
281
282    public void dispose() {
283        //Unregister for all events
284        phone.mCM.unregisterForAvailable(this);
285        phone.mCM.unregisterForOffOrNotAvailable(this);
286        mGsmPhone.mSIMRecords.unregisterForRecordsLoaded(this);
287        phone.mCM.unregisterForDataStateChanged(this);
288        mGsmPhone.mCT.unregisterForVoiceCallEnded(this);
289        mGsmPhone.mCT.unregisterForVoiceCallStarted(this);
290        mGsmPhone.mSST.unregisterForGprsAttached(this);
291        mGsmPhone.mSST.unregisterForGprsDetached(this);
292        mGsmPhone.mSST.unregisterForRoamingOn(this);
293        mGsmPhone.mSST.unregisterForRoamingOff(this);
294        mGsmPhone.mSST.unregisterForPsRestrictedEnabled(this);
295        mGsmPhone.mSST.unregisterForPsRestrictedDisabled(this);
296
297        phone.getContext().unregisterReceiver(this.mIntentReceiver);
298        phone.getContext().getContentResolver().unregisterContentObserver(this.apnObserver);
299
300        destroyAllPdpList();
301    }
302
303    protected void finalize() {
304        if(DBG) Log.d(LOG_TAG, "GsmDataConnectionTracker finalized");
305    }
306
307    protected void setState(State s) {
308        if (DBG) log ("setState: " + s);
309        if (state != s) {
310            EventLog.writeEvent(EventLogTags.GSM_DATA_STATE_CHANGE, state.toString(), s.toString());
311            state = s;
312        }
313
314        if (state == State.FAILED) {
315            if (waitingApns != null)
316                waitingApns.clear(); // when teardown the connection and set to IDLE
317        }
318    }
319
320    public String[] getActiveApnTypes() {
321        String[] result;
322        if (mActiveApn != null) {
323            result = mActiveApn.types;
324        } else {
325            result = new String[1];
326            result[0] = Phone.APN_TYPE_DEFAULT;
327        }
328        return result;
329    }
330
331    protected String getActiveApnString() {
332        String result = null;
333        if (mActiveApn != null) {
334            result = mActiveApn.apn;
335        }
336        return result;
337    }
338
339    /**
340     * The data connection is expected to be setup while device
341     *  1. has sim card
342     *  2. registered to gprs service
343     *  3. user doesn't explicitly disable data service
344     *  4. wifi is not on
345     *
346     * @return false while no data connection if all above requirements are met.
347     */
348    public boolean isDataConnectionAsDesired() {
349        boolean roaming = phone.getServiceState().getRoaming();
350
351        if (mGsmPhone.mSIMRecords.getRecordsLoaded() &&
352                mGsmPhone.mSST.getCurrentGprsState() == ServiceState.STATE_IN_SERVICE &&
353                (!roaming || getDataOnRoamingEnabled()) &&
354            !mIsWifiConnected &&
355            !mIsPsRestricted ) {
356            return (state == State.CONNECTED);
357        }
358        return true;
359    }
360
361    @Override
362    protected boolean isApnTypeActive(String type) {
363        // TODO: support simultaneous with List instead
364        return mActiveApn != null && mActiveApn.canHandleType(type);
365    }
366
367    @Override
368    protected boolean isApnTypeAvailable(String type) {
369        if (type.equals(Phone.APN_TYPE_DUN)) {
370            return (fetchDunApn() != null);
371        }
372
373        if (allApns != null) {
374            for (ApnSetting apn : allApns) {
375                if (apn.canHandleType(type)) {
376                    return true;
377                }
378            }
379        }
380        return false;
381    }
382
383    /**
384     * Formerly this method was ArrayList<GsmDataConnection> getAllPdps()
385     */
386    public ArrayList<DataConnection> getAllDataConnections() {
387        ArrayList<DataConnection> pdps = (ArrayList<DataConnection>)pdpList.clone();
388        return pdps;
389    }
390
391    private boolean isDataAllowed() {
392        boolean roaming = phone.getServiceState().getRoaming();
393        return getAnyDataEnabled() && (!roaming || getDataOnRoamingEnabled()) &&
394                mMasterDataEnabled;
395    }
396
397    //****** Called from ServiceStateTracker
398    /**
399     * Invoked when ServiceStateTracker observes a transition from GPRS
400     * attach to detach.
401     */
402    protected void onGprsDetached() {
403        /*
404         * We presently believe it is unnecessary to tear down the PDP context
405         * when GPRS detaches, but we should stop the network polling.
406         */
407        stopNetStatPoll();
408        phone.notifyDataConnection(Phone.REASON_GPRS_DETACHED);
409    }
410
411    private void onGprsAttached() {
412        if (state == State.CONNECTED) {
413            startNetStatPoll();
414            phone.notifyDataConnection(Phone.REASON_GPRS_ATTACHED);
415        } else {
416            if (state == State.FAILED) {
417                cleanUpConnection(false, Phone.REASON_GPRS_ATTACHED);
418                mRetryMgr.resetRetryCount();
419            }
420            trySetupData(Phone.REASON_GPRS_ATTACHED);
421        }
422    }
423
424    private boolean trySetupData(String reason) {
425        if (DBG) log("***trySetupData due to " + (reason == null ? "(unspecified)" : reason));
426
427        Log.d(LOG_TAG, "[DSAC DEB] " + "trySetupData with mIsPsRestricted=" + mIsPsRestricted);
428
429        if (phone.getSimulatedRadioControl() != null) {
430            // Assume data is connected on the simulator
431            // FIXME  this can be improved
432            setState(State.CONNECTED);
433            phone.notifyDataConnection(reason);
434
435            Log.i(LOG_TAG, "(fix?) We're on the simulator; assuming data is connected");
436            return true;
437        }
438
439        int gprsState = mGsmPhone.mSST.getCurrentGprsState();
440        boolean desiredPowerState = mGsmPhone.mSST.getDesiredPowerState();
441
442        if ((state == State.IDLE || state == State.SCANNING)
443                && (gprsState == ServiceState.STATE_IN_SERVICE || noAutoAttach)
444                && mGsmPhone.mSIMRecords.getRecordsLoaded()
445                && phone.getState() == Phone.State.IDLE
446                && isDataAllowed()
447                && !mIsPsRestricted
448                && desiredPowerState ) {
449
450            if (state == State.IDLE) {
451                waitingApns = buildWaitingApns();
452                if (waitingApns.isEmpty()) {
453                    if (DBG) log("No APN found");
454                    notifyNoData(GsmDataConnection.FailCause.MISSING_UNKNOWN_APN);
455                    return false;
456                } else {
457                    log ("Create from allApns : " + apnListToString(allApns));
458                }
459            }
460
461            if (DBG) {
462                log ("Setup waitngApns : " + apnListToString(waitingApns));
463            }
464            return setupData(reason);
465        } else {
466            if (DBG)
467                log("trySetupData: Not ready for data: " +
468                    " dataState=" + state +
469                    " gprsState=" + gprsState +
470                    " sim=" + mGsmPhone.mSIMRecords.getRecordsLoaded() +
471                    " UMTS=" + mGsmPhone.mSST.isConcurrentVoiceAndData() +
472                    " phoneState=" + phone.getState() +
473                    " isDataAllowed=" + isDataAllowed() +
474                    " dataEnabled=" + getAnyDataEnabled() +
475                    " roaming=" + phone.getServiceState().getRoaming() +
476                    " dataOnRoamingEnable=" + getDataOnRoamingEnabled() +
477                    " ps restricted=" + mIsPsRestricted +
478                    " desiredPowerState=" + desiredPowerState +
479                    " MasterDataEnabled=" + mMasterDataEnabled);
480            return false;
481        }
482    }
483
484    /**
485     * If tearDown is true, this only tears down a CONNECTED session. Presently,
486     * there is no mechanism for abandoning an INITING/CONNECTING session,
487     * but would likely involve cancelling pending async requests or
488     * setting a flag or new state to ignore them when they came in
489     * @param tearDown true if the underlying GsmDataConnection should be
490     * disconnected.
491     * @param reason reason for the clean up.
492     */
493    private void cleanUpConnection(boolean tearDown, String reason) {
494        if (DBG) log("Clean up connection due to " + reason);
495
496        // Clear the reconnect alarm, if set.
497        if (mReconnectIntent != null) {
498            AlarmManager am =
499                (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
500            am.cancel(mReconnectIntent);
501            mReconnectIntent = null;
502        }
503
504        setState(State.DISCONNECTING);
505
506        boolean notificationDeferred = false;
507        for (DataConnection conn : pdpList) {
508            if (tearDown) {
509                if (DBG) log("cleanUpConnection: teardown, call conn.disconnect");
510                conn.disconnect(obtainMessage(EVENT_DISCONNECT_DONE, reason));
511                notificationDeferred = true;
512            } else {
513                if (DBG) log("cleanUpConnection: !tearDown, call conn.resetSynchronously");
514                conn.resetSynchronously();
515                notificationDeferred = false;
516            }
517        }
518        stopNetStatPoll();
519
520        if (!notificationDeferred) {
521            if (DBG) log("cleanupConnection: !notificationDeferred");
522            gotoIdleAndNotifyDataConnection(reason);
523        }
524    }
525
526    /**
527     * @param types comma delimited list of APN types
528     * @return array of APN types
529     */
530    private String[] parseTypes(String types) {
531        String[] result;
532        // If unset, set to DEFAULT.
533        if (types == null || types.equals("")) {
534            result = new String[1];
535            result[0] = Phone.APN_TYPE_ALL;
536        } else {
537            result = types.split(",");
538        }
539        return result;
540    }
541
542    private ArrayList<ApnSetting> createApnList(Cursor cursor) {
543        ArrayList<ApnSetting> result = new ArrayList<ApnSetting>();
544        if (cursor.moveToFirst()) {
545            do {
546                String[] types = parseTypes(
547                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
548                ApnSetting apn = new ApnSetting(
549                        cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
550                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
551                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)),
552                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
553                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY)),
554                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)),
555                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC)),
556                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY)),
557                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)),
558                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
559                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
560                        cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
561                        types);
562                result.add(apn);
563            } while (cursor.moveToNext());
564        }
565        return result;
566    }
567
568    private GsmDataConnection findFreePdp() {
569        for (DataConnection conn : pdpList) {
570            GsmDataConnection pdp = (GsmDataConnection) conn;
571            if (pdp.isInactive()) {
572                return pdp;
573            }
574        }
575        return null;
576    }
577
578    private boolean setupData(String reason) {
579        ApnSetting apn;
580        GsmDataConnection pdp;
581
582        apn = getNextApn();
583        if (apn == null) return false;
584        pdp = findFreePdp();
585        if (pdp == null) {
586            if (DBG) log("setupData: No free GsmDataConnection found!");
587            return false;
588        }
589        mActiveApn = apn;
590        mActivePdp = pdp;
591
592        Message msg = obtainMessage();
593        msg.what = EVENT_DATA_SETUP_COMPLETE;
594        msg.obj = reason;
595        pdp.connect(msg, apn);
596
597        setState(State.INITING);
598        phone.notifyDataConnection(reason);
599        return true;
600    }
601
602    protected String getInterfaceName(String apnType) {
603        if (mActivePdp != null &&
604                (apnType == null ||
605                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
606            return mActivePdp.getInterface();
607        }
608        return null;
609    }
610
611    protected String getIpAddress(String apnType) {
612        if (mActivePdp != null &&
613                (apnType == null ||
614                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
615            return mActivePdp.getIpAddress();
616        }
617        return null;
618    }
619
620    public String getGateway(String apnType) {
621        if (mActivePdp != null &&
622                (apnType == null ||
623                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
624            return mActivePdp.getGatewayAddress();
625        }
626        return null;
627    }
628
629    protected String[] getDnsServers(String apnType) {
630        if (mActivePdp != null &&
631                (apnType == null ||
632                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
633            return mActivePdp.getDnsServers();
634        }
635        return null;
636    }
637
638    private boolean
639    pdpStatesHasCID (ArrayList<DataCallState> states, int cid) {
640        for (int i = 0, s = states.size() ; i < s ; i++) {
641            if (states.get(i).cid == cid) return true;
642        }
643
644        return false;
645    }
646
647    private boolean
648    pdpStatesHasActiveCID (ArrayList<DataCallState> states, int cid) {
649        for (int i = 0, s = states.size() ; i < s ; i++) {
650            if ((states.get(i).cid == cid) && (states.get(i).active != 0)) {
651                return true;
652            }
653        }
654
655        return false;
656    }
657
658    /**
659     * Handles changes to the APN database.
660     */
661    private void onApnChanged() {
662        boolean isConnected;
663
664        isConnected = (state != State.IDLE && state != State.FAILED);
665
666        // The "current" may no longer be valid.  MMS depends on this to send properly.
667        mGsmPhone.updateCurrentCarrierInProvider();
668
669        // TODO: It'd be nice to only do this if the changed entrie(s)
670        // match the current operator.
671        createAllApnList();
672        if (state != State.DISCONNECTING) {
673            cleanUpConnection(isConnected, Phone.REASON_APN_CHANGED);
674            if (!isConnected) {
675                // reset reconnect timer
676                mRetryMgr.resetRetryCount();
677                mReregisterOnReconnectFailure = false;
678                trySetupData(Phone.REASON_APN_CHANGED);
679            }
680        }
681    }
682
683    /**
684     * @param explicitPoll if true, indicates that *we* polled for this
685     * update while state == CONNECTED rather than having it delivered
686     * via an unsolicited response (which could have happened at any
687     * previous state
688     */
689    protected void onPdpStateChanged (AsyncResult ar, boolean explicitPoll) {
690        ArrayList<DataCallState> pdpStates;
691
692        pdpStates = (ArrayList<DataCallState>)(ar.result);
693
694        if (ar.exception != null) {
695            // This is probably "radio not available" or something
696            // of that sort. If so, the whole connection is going
697            // to come down soon anyway
698            return;
699        }
700
701        if (state == State.CONNECTED) {
702            // The way things are supposed to work, the PDP list
703            // should not contain the CID after it disconnects.
704            // However, the way things really work, sometimes the PDP
705            // context is still listed with active = false, which
706            // makes it hard to distinguish an activating context from
707            // an activated-and-then deactivated one.
708            if (!pdpStatesHasCID(pdpStates, cidActive)) {
709                // It looks like the PDP context has deactivated.
710                // Tear everything down and try to reconnect.
711
712                Log.i(LOG_TAG, "PDP connection has dropped. Reconnecting");
713
714                // Add an event log when the network drops PDP
715                GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
716                EventLog.writeEvent(EventLogTags.PDP_NETWORK_DROP,
717                        loc != null ? loc.getCid() : -1,
718                        TelephonyManager.getDefault().getNetworkType());
719
720                cleanUpConnection(true, null);
721                return;
722            } else if (!pdpStatesHasActiveCID(pdpStates, cidActive)) {
723                // Here, we only consider this authoritative if we asked for the
724                // PDP list. If it was an unsolicited response, we poll again
725                // to make sure everyone agrees on the initial state.
726
727                if (!explicitPoll) {
728                    // We think it disconnected but aren't sure...poll from our side
729                    phone.mCM.getPDPContextList(
730                            this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE));
731                } else {
732                    Log.i(LOG_TAG, "PDP connection has dropped (active=false case). "
733                                    + " Reconnecting");
734
735                    // Log the network drop on the event log.
736                    GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
737                    EventLog.writeEvent(EventLogTags.PDP_NETWORK_DROP,
738                            loc != null ? loc.getCid() : -1,
739                            TelephonyManager.getDefault().getNetworkType());
740
741                    cleanUpConnection(true, null);
742                }
743            }
744        }
745    }
746
747    private void notifyDefaultData(String reason) {
748        setState(State.CONNECTED);
749        phone.notifyDataConnection(reason);
750        startNetStatPoll();
751        // reset reconnect timer
752        mRetryMgr.resetRetryCount();
753        mReregisterOnReconnectFailure = false;
754    }
755
756    private void gotoIdleAndNotifyDataConnection(String reason) {
757        if (DBG) log("gotoIdleAndNotifyDataConnection: reason=" + reason);
758        setState(State.IDLE);
759        phone.notifyDataConnection(reason);
760        mActiveApn = null;
761    }
762
763    /**
764     * This is a kludge to deal with the fact that
765     * the PDP state change notification doesn't always work
766     * with certain RIL impl's/basebands
767     *
768     */
769    private void startPeriodicPdpPoll() {
770        removeMessages(EVENT_POLL_PDP);
771
772        sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS);
773    }
774
775    private void resetPollStats() {
776        txPkts = -1;
777        rxPkts = -1;
778        sentSinceLastRecv = 0;
779        netStatPollPeriod = POLL_NETSTAT_MILLIS;
780        mNoRecvPollCount = 0;
781    }
782
783    private void doRecovery() {
784        if (state == State.CONNECTED) {
785            int maxPdpReset = Settings.Secure.getInt(mResolver,
786                    Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT,
787                    DEFAULT_MAX_PDP_RESET_FAIL);
788            if (mPdpResetCount < maxPdpReset) {
789                mPdpResetCount++;
790                EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET, sentSinceLastRecv);
791                cleanUpConnection(true, Phone.REASON_PDP_RESET);
792            } else {
793                mPdpResetCount = 0;
794                EventLog.writeEvent(EventLogTags.PDP_REREGISTER_NETWORK, sentSinceLastRecv);
795                mGsmPhone.mSST.reRegisterNetwork(null);
796            }
797            // TODO: Add increasingly drastic recovery steps, eg,
798            // reset the radio, reset the device.
799        }
800    }
801
802    protected void startNetStatPoll() {
803        if (state == State.CONNECTED && mPingTestActive == false && netStatPollEnabled == false) {
804            Log.d(LOG_TAG, "[DataConnection] Start poll NetStat");
805            resetPollStats();
806            netStatPollEnabled = true;
807            mPollNetStat.run();
808        }
809    }
810
811    protected void stopNetStatPoll() {
812        netStatPollEnabled = false;
813        removeCallbacks(mPollNetStat);
814        Log.d(LOG_TAG, "[DataConnection] Stop poll NetStat");
815    }
816
817    protected void restartRadio() {
818        Log.d(LOG_TAG, "************TURN OFF RADIO**************");
819        cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF);
820        mGsmPhone.mSST.powerOffRadioSafely();
821        /* Note: no need to call setRadioPower(true).  Assuming the desired
822         * radio power state is still ON (as tracked by ServiceStateTracker),
823         * ServiceStateTracker will call setRadioPower when it receives the
824         * RADIO_STATE_CHANGED notification for the power off.  And if the
825         * desired power state has changed in the interim, we don't want to
826         * override it with an unconditional power on.
827         */
828
829        int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0"));
830        SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1));
831    }
832
833    private Runnable mPollNetStat = new Runnable()
834    {
835
836        public void run() {
837            long sent, received;
838            long preTxPkts = -1, preRxPkts = -1;
839
840            Activity newActivity;
841
842            preTxPkts = txPkts;
843            preRxPkts = rxPkts;
844
845            txPkts = TrafficStats.getMobileTxPackets();
846            rxPkts = TrafficStats.getMobileRxPackets();
847
848            //Log.d(LOG_TAG, "rx " + String.valueOf(rxPkts) + " tx " + String.valueOf(txPkts));
849
850            if (netStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) {
851                sent = txPkts - preTxPkts;
852                received = rxPkts - preRxPkts;
853
854                if ( sent > 0 && received > 0 ) {
855                    sentSinceLastRecv = 0;
856                    newActivity = Activity.DATAINANDOUT;
857                    mPdpResetCount = 0;
858                } else if (sent > 0 && received == 0) {
859                    if (phone.getState() == Phone.State.IDLE) {
860                        sentSinceLastRecv += sent;
861                    } else {
862                        sentSinceLastRecv = 0;
863                    }
864                    newActivity = Activity.DATAOUT;
865                } else if (sent == 0 && received > 0) {
866                    sentSinceLastRecv = 0;
867                    newActivity = Activity.DATAIN;
868                    mPdpResetCount = 0;
869                } else if (sent == 0 && received == 0) {
870                    newActivity = Activity.NONE;
871                } else {
872                    sentSinceLastRecv = 0;
873                    newActivity = Activity.NONE;
874                }
875
876                if (activity != newActivity && mIsScreenOn) {
877                    activity = newActivity;
878                    phone.notifyDataActivity();
879                }
880            }
881
882            int watchdogTrigger = Settings.Secure.getInt(mResolver,
883                    Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT,
884                    NUMBER_SENT_PACKETS_OF_HANG);
885
886            if (sentSinceLastRecv >= watchdogTrigger) {
887                // we already have NUMBER_SENT_PACKETS sent without ack
888                if (mNoRecvPollCount == 0) {
889                    EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET_COUNTDOWN_TRIGGERED,
890                            sentSinceLastRecv);
891                }
892
893                int noRecvPollLimit = Settings.Secure.getInt(mResolver,
894                        Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT, NO_RECV_POLL_LIMIT);
895
896                if (mNoRecvPollCount < noRecvPollLimit) {
897                    // It's possible the PDP context went down and we weren't notified.
898                    // Start polling the context list in an attempt to recover.
899                    if (DBG) log("no DATAIN in a while; polling PDP");
900                    phone.mCM.getDataCallList(obtainMessage(EVENT_GET_PDP_LIST_COMPLETE));
901
902                    mNoRecvPollCount++;
903
904                    // Slow down the poll interval to let things happen
905                    netStatPollPeriod = Settings.Secure.getInt(mResolver,
906                            Settings.Secure.PDP_WATCHDOG_ERROR_POLL_INTERVAL_MS,
907                            POLL_NETSTAT_SLOW_MILLIS);
908                } else {
909                    if (DBG) log("Sent " + String.valueOf(sentSinceLastRecv) +
910                                        " pkts since last received");
911                    // We've exceeded the threshold.  Run ping test as a final check;
912                    // it will proceed with recovery if ping fails.
913                    stopNetStatPoll();
914                    Thread pingTest = new Thread() {
915                        public void run() {
916                            runPingTest();
917                        }
918                    };
919                    mPingTestActive = true;
920                    pingTest.start();
921                }
922            } else {
923                mNoRecvPollCount = 0;
924                if (mIsScreenOn) {
925                    netStatPollPeriod = Settings.Secure.getInt(mResolver,
926                            Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
927                } else {
928                    netStatPollPeriod = Settings.Secure.getInt(mResolver,
929                            Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS,
930                            POLL_NETSTAT_SCREEN_OFF_MILLIS);
931                }
932            }
933
934            if (netStatPollEnabled) {
935                mDataConnectionTracker.postDelayed(this, netStatPollPeriod);
936            }
937        }
938    };
939
940    private void runPingTest () {
941        int status = -1;
942        try {
943            String address = Settings.Secure.getString(mResolver,
944                    Settings.Secure.PDP_WATCHDOG_PING_ADDRESS);
945            int deadline = Settings.Secure.getInt(mResolver,
946                        Settings.Secure.PDP_WATCHDOG_PING_DEADLINE, DEFAULT_PING_DEADLINE);
947            if (DBG) log("pinging " + address + " for " + deadline + "s");
948            if (address != null && !NULL_IP.equals(address)) {
949                Process p = Runtime.getRuntime()
950                                .exec("ping -c 1 -i 1 -w "+ deadline + " " + address);
951                status = p.waitFor();
952            }
953        } catch (IOException e) {
954            Log.w(LOG_TAG, "ping failed: IOException");
955        } catch (Exception e) {
956            Log.w(LOG_TAG, "exception trying to ping");
957        }
958
959        if (status == 0) {
960            // ping succeeded.  False alarm.  Reset netStatPoll.
961            // ("-1" for this event indicates a false alarm)
962            EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET, -1);
963            mPdpResetCount = 0;
964            sendMessage(obtainMessage(EVENT_START_NETSTAT_POLL));
965        } else {
966            // ping failed.  Proceed with recovery.
967            sendMessage(obtainMessage(EVENT_START_RECOVERY));
968        }
969    }
970
971    /**
972     * Returns true if the last fail cause is something that
973     * seems like it deserves an error notification.
974     * Transient errors are ignored
975     */
976    private boolean shouldPostNotification(GsmDataConnection.FailCause  cause) {
977        return (cause != GsmDataConnection.FailCause.UNKNOWN);
978    }
979
980    /**
981     * Return true if data connection need to be setup after disconnected due to
982     * reason.
983     *
984     * @param reason the reason why data is disconnected
985     * @return true if try setup data connection is need for this reason
986     */
987    private boolean retryAfterDisconnected(String reason) {
988        boolean retry = true;
989
990        if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) ) {
991            retry = false;
992        }
993        return retry;
994    }
995
996    private void reconnectAfterFail(FailCause lastFailCauseCode, String reason) {
997        if (state == State.FAILED) {
998            if (!mRetryMgr.isRetryNeeded()) {
999                if (!mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
1000                    // if no more retries on a secondary APN attempt, tell the world and revert.
1001                    phone.notifyDataConnection(Phone.REASON_APN_FAILED);
1002                    onEnableApn(apnTypeToId(mRequestedApnType), DISABLED);
1003                    return;
1004                }
1005                if (mReregisterOnReconnectFailure) {
1006                    // We've re-registerd once now just retry forever.
1007                    mRetryMgr.retryForeverUsingLastTimeout();
1008                } else {
1009                    // Try to re-register to the network.
1010                    Log.d(LOG_TAG, "PDP activate failed, Reregistering to the network");
1011                    mReregisterOnReconnectFailure = true;
1012                    mGsmPhone.mSST.reRegisterNetwork(null);
1013                    mRetryMgr.resetRetryCount();
1014                    return;
1015                }
1016            }
1017
1018            int nextReconnectDelay = mRetryMgr.getRetryTimer();
1019            Log.d(LOG_TAG, "PDP activate failed. Scheduling next attempt for "
1020                    + (nextReconnectDelay / 1000) + "s");
1021
1022            AlarmManager am =
1023                (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
1024            Intent intent = new Intent(INTENT_RECONNECT_ALARM);
1025            intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON, reason);
1026            mReconnectIntent = PendingIntent.getBroadcast(
1027                    phone.getContext(), 0, intent, 0);
1028            am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1029                    SystemClock.elapsedRealtime() + nextReconnectDelay,
1030                    mReconnectIntent);
1031
1032            mRetryMgr.increaseRetryCount();
1033
1034            if (!shouldPostNotification(lastFailCauseCode)) {
1035                Log.d(LOG_TAG,"NOT Posting GPRS Unavailable notification "
1036                                + "-- likely transient error");
1037            } else {
1038                notifyNoData(lastFailCauseCode);
1039            }
1040        }
1041    }
1042
1043    private void notifyNoData(GsmDataConnection.FailCause lastFailCauseCode) {
1044        setState(State.FAILED);
1045    }
1046
1047    protected void onRecordsLoaded() {
1048        createAllApnList();
1049        if (state == State.FAILED) {
1050            cleanUpConnection(false, null);
1051        }
1052        sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA, Phone.REASON_SIM_LOADED));
1053    }
1054
1055    @Override
1056    protected void onEnableNewApn() {
1057        // change our retry manager to use the appropriate numbers for the new APN
1058        if (mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
1059            mRetryMgr = mDefaultRetryManager;
1060        } else {
1061            mRetryMgr = mSecondaryRetryManager;
1062        }
1063        mRetryMgr.resetRetryCount();
1064
1065        // TODO:  To support simultaneous PDP contexts, this should really only call
1066        // cleanUpConnection if it needs to free up a GsmDataConnection.
1067        cleanUpConnection(true, Phone.REASON_APN_SWITCHED);
1068    }
1069
1070    protected boolean onTrySetupData(String reason) {
1071        return trySetupData(reason);
1072    }
1073
1074    @Override
1075    protected void onRoamingOff() {
1076        trySetupData(Phone.REASON_ROAMING_OFF);
1077    }
1078
1079    @Override
1080    protected void onRoamingOn() {
1081        if (getDataOnRoamingEnabled()) {
1082            trySetupData(Phone.REASON_ROAMING_ON);
1083        } else {
1084            if (DBG) log("Tear down data connection on roaming.");
1085            cleanUpConnection(true, Phone.REASON_ROAMING_ON);
1086        }
1087    }
1088
1089    protected void onRadioAvailable() {
1090        if (phone.getSimulatedRadioControl() != null) {
1091            // Assume data is connected on the simulator
1092            // FIXME  this can be improved
1093            setState(State.CONNECTED);
1094            phone.notifyDataConnection(null);
1095
1096            Log.i(LOG_TAG, "We're on the simulator; assuming data is connected");
1097        }
1098
1099        if (state != State.IDLE) {
1100            cleanUpConnection(true, null);
1101        }
1102    }
1103
1104    protected void onRadioOffOrNotAvailable() {
1105        // Make sure our reconnect delay starts at the initial value
1106        // next time the radio comes on
1107        mRetryMgr.resetRetryCount();
1108        mReregisterOnReconnectFailure = false;
1109
1110        if (phone.getSimulatedRadioControl() != null) {
1111            // Assume data is connected on the simulator
1112            // FIXME  this can be improved
1113            Log.i(LOG_TAG, "We're on the simulator; assuming radio off is meaningless");
1114        } else {
1115            if (DBG) log("Radio is off and clean up all connection");
1116            // TODO: Should we reset mRequestedApnType to "default"?
1117            cleanUpConnection(false, Phone.REASON_RADIO_TURNED_OFF);
1118        }
1119    }
1120
1121    protected void onDataSetupComplete(AsyncResult ar) {
1122        String reason = null;
1123        if (ar.userObj instanceof String) {
1124            reason = (String) ar.userObj;
1125        }
1126
1127        if (ar.exception == null) {
1128            // everything is setup
1129            if (isApnTypeActive(Phone.APN_TYPE_DEFAULT)) {
1130                SystemProperties.set("gsm.defaultpdpcontext.active", "true");
1131                        if (canSetPreferApn && preferredApn == null) {
1132                            Log.d(LOG_TAG, "PREFERRED APN is null");
1133                            preferredApn = mActiveApn;
1134                            setPreferredApn(preferredApn.id);
1135                        }
1136            } else {
1137                SystemProperties.set("gsm.defaultpdpcontext.active", "false");
1138            }
1139            notifyDefaultData(reason);
1140
1141            // TODO: For simultaneous PDP support, we need to build another
1142            // trigger another TRY_SETUP_DATA for the next APN type.  (Note
1143            // that the existing connection may service that type, in which
1144            // case we should try the next type, etc.
1145        } else {
1146            GsmDataConnection.FailCause cause;
1147            cause = (GsmDataConnection.FailCause) (ar.result);
1148            if(DBG) log("PDP setup failed " + cause);
1149                    // Log this failure to the Event Logs.
1150            if (cause.isEventLoggable()) {
1151                GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
1152                EventLog.writeEvent(EventLogTags.PDP_SETUP_FAIL,
1153                        cause.ordinal(), loc != null ? loc.getCid() : -1,
1154                        TelephonyManager.getDefault().getNetworkType());
1155            }
1156
1157            // No try for permanent failure
1158            if (cause.isPermanentFail()) {
1159                notifyNoData(cause);
1160                phone.notifyDataConnection(Phone.REASON_APN_FAILED);
1161                onEnableApn(apnTypeToId(mRequestedApnType), DISABLED);
1162                return;
1163            }
1164
1165            waitingApns.remove(0);
1166            if (waitingApns.isEmpty()) {
1167                // No more to try, start delayed retry
1168                startDelayedRetry(cause, reason);
1169            } else {
1170                // we still have more apns to try
1171                setState(State.SCANNING);
1172                // Wait a bit before trying the next APN, so that
1173                // we're not tying up the RIL command channel
1174                sendMessageDelayed(obtainMessage(EVENT_TRY_SETUP_DATA, reason), APN_DELAY_MILLIS);
1175            }
1176        }
1177    }
1178
1179    /**
1180     * Called when EVENT_DISCONNECT_DONE is received.
1181     */
1182    protected void onDisconnectDone(AsyncResult ar) {
1183        String reason = null;
1184        if(DBG) log("EVENT_DISCONNECT_DONE");
1185        if (ar.userObj instanceof String) {
1186           reason = (String) ar.userObj;
1187        }
1188        setState(State.IDLE);
1189        phone.notifyDataConnection(reason);
1190        mActiveApn = null;
1191        if (retryAfterDisconnected(reason)) {
1192            trySetupData(reason);
1193        }
1194    }
1195
1196    /**
1197     * Called when EVENT_RESET_DONE is received.
1198     */
1199    @Override
1200    protected void onResetDone(AsyncResult ar) {
1201        if (DBG) log("EVENT_RESET_DONE");
1202        String reason = null;
1203        if (ar.userObj instanceof String) {
1204            reason = (String) ar.userObj;
1205        }
1206        gotoIdleAndNotifyDataConnection(reason);
1207    }
1208
1209    protected void onPollPdp() {
1210        if (state == State.CONNECTED) {
1211            // only poll when connected
1212            phone.mCM.getPDPContextList(this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE));
1213            sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS);
1214        }
1215    }
1216
1217    protected void onVoiceCallStarted() {
1218        if (state == State.CONNECTED && ! mGsmPhone.mSST.isConcurrentVoiceAndData()) {
1219            stopNetStatPoll();
1220            phone.notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED);
1221        }
1222    }
1223
1224    protected void onVoiceCallEnded() {
1225        if (state == State.CONNECTED) {
1226            if (!mGsmPhone.mSST.isConcurrentVoiceAndData()) {
1227                startNetStatPoll();
1228                phone.notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED);
1229            } else {
1230                // clean slate after call end.
1231                resetPollStats();
1232            }
1233        } else {
1234            // reset reconnect timer
1235            mRetryMgr.resetRetryCount();
1236            mReregisterOnReconnectFailure = false;
1237            // in case data setup was attempted when we were on a voice call
1238            trySetupData(Phone.REASON_VOICE_CALL_ENDED);
1239        }
1240    }
1241
1242    protected void onCleanUpConnection(boolean tearDown, String reason) {
1243        cleanUpConnection(tearDown, reason);
1244    }
1245
1246    /**
1247     * Based on the sim operator numeric, create a list for all possible pdps
1248     * with all apns associated with that pdp
1249     *
1250     *
1251     */
1252    private void createAllApnList() {
1253        allApns = new ArrayList<ApnSetting>();
1254        String operator = mGsmPhone.mSIMRecords.getSIMOperatorNumeric();
1255
1256        if (operator != null) {
1257            String selection = "numeric = '" + operator + "'";
1258
1259            Cursor cursor = phone.getContext().getContentResolver().query(
1260                    Telephony.Carriers.CONTENT_URI, null, selection, null, null);
1261
1262            if (cursor != null) {
1263                if (cursor.getCount() > 0) {
1264                    allApns = createApnList(cursor);
1265                    // TODO: Figure out where this fits in.  This basically just
1266                    // writes the pap-secrets file.  No longer tied to GsmDataConnection
1267                    // object.  Not used on current platform (no ppp).
1268                    //GsmDataConnection pdp = pdpList.get(pdp_name);
1269                    //if (pdp != null && pdp.dataLink != null) {
1270                    //    pdp.dataLink.setPasswordInfo(cursor);
1271                    //}
1272                }
1273                cursor.close();
1274            }
1275        }
1276
1277        if (allApns.isEmpty()) {
1278            if (DBG) log("No APN found for carrier: " + operator);
1279            preferredApn = null;
1280            notifyNoData(GsmDataConnection.FailCause.MISSING_UNKNOWN_APN);
1281        } else {
1282            preferredApn = getPreferredApn();
1283            Log.d(LOG_TAG, "Get PreferredAPN");
1284            if (preferredApn != null && !preferredApn.numeric.equals(operator)) {
1285                preferredApn = null;
1286                setPreferredApn(-1);
1287            }
1288        }
1289    }
1290
1291    private void createAllPdpList() {
1292        pdpList = new ArrayList<DataConnection>();
1293        DataConnection pdp;
1294
1295        for (int i = 0; i < PDP_CONNECTION_POOL_SIZE; i++) {
1296            pdp = GsmDataConnection.makeDataConnection(mGsmPhone);
1297            pdpList.add(pdp);
1298         }
1299    }
1300
1301    private void destroyAllPdpList() {
1302        if(pdpList != null) {
1303            GsmDataConnection pdp;
1304            pdpList.removeAll(pdpList);
1305        }
1306    }
1307
1308    private ApnSetting fetchDunApn() {
1309        Context c = phone.getContext();
1310        String apnData = Settings.Secure.getString(c.getContentResolver(),
1311                                    Settings.Secure.TETHER_DUN_APN);
1312        ApnSetting dunSetting = ApnSetting.fromString(apnData);
1313        if (dunSetting != null) return dunSetting;
1314
1315        apnData = c.getResources().getString(R.string.config_tether_apndata);
1316        return ApnSetting.fromString(apnData);
1317    }
1318
1319    /**
1320     *
1321     * @return waitingApns list to be used to create PDP
1322     *          error when waitingApns.isEmpty()
1323     */
1324    private ArrayList<ApnSetting> buildWaitingApns() {
1325        ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>();
1326
1327        if (mRequestedApnType.equals(Phone.APN_TYPE_DUN)) {
1328            ApnSetting dun = fetchDunApn();
1329            if (dun != null) apnList.add(dun);
1330            return apnList;
1331        }
1332
1333        String operator = mGsmPhone.mSIMRecords.getSIMOperatorNumeric();
1334
1335        if (mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
1336            if (canSetPreferApn && preferredApn != null) {
1337                Log.i(LOG_TAG, "Preferred APN:" + operator + ":"
1338                        + preferredApn.numeric + ":" + preferredApn);
1339                if (preferredApn.numeric.equals(operator)) {
1340                    Log.i(LOG_TAG, "Waiting APN set to preferred APN");
1341                    apnList.add(preferredApn);
1342                    return apnList;
1343                } else {
1344                    setPreferredApn(-1);
1345                    preferredApn = null;
1346                }
1347            }
1348        }
1349
1350        if (allApns != null) {
1351            for (ApnSetting apn : allApns) {
1352                if (apn.canHandleType(mRequestedApnType)) {
1353                    apnList.add(apn);
1354                }
1355            }
1356        }
1357        return apnList;
1358    }
1359
1360    /**
1361     * Get next apn in waitingApns
1362     * @return the first apn found in waitingApns, null if none
1363     */
1364    private ApnSetting getNextApn() {
1365        ArrayList<ApnSetting> list = waitingApns;
1366        ApnSetting apn = null;
1367
1368        if (list != null) {
1369            if (!list.isEmpty()) {
1370                apn = list.get(0);
1371            }
1372        }
1373        return apn;
1374    }
1375
1376    private String apnListToString (ArrayList<ApnSetting> apns) {
1377        StringBuilder result = new StringBuilder();
1378        for (int i = 0, size = apns.size(); i < size; i++) {
1379            result.append('[')
1380                  .append(apns.get(i).toString())
1381                  .append(']');
1382        }
1383        return result.toString();
1384    }
1385
1386    private void startDelayedRetry(GsmDataConnection.FailCause cause, String reason) {
1387        notifyNoData(cause);
1388        reconnectAfterFail(cause, reason);
1389    }
1390
1391    private void setPreferredApn(int pos) {
1392        if (!canSetPreferApn) {
1393            return;
1394        }
1395
1396        ContentResolver resolver = phone.getContext().getContentResolver();
1397        resolver.delete(PREFERAPN_URI, null, null);
1398
1399        if (pos >= 0) {
1400            ContentValues values = new ContentValues();
1401            values.put(APN_ID, pos);
1402            resolver.insert(PREFERAPN_URI, values);
1403        }
1404    }
1405
1406    private ApnSetting getPreferredApn() {
1407        if (allApns.isEmpty()) {
1408            return null;
1409        }
1410
1411        Cursor cursor = phone.getContext().getContentResolver().query(
1412                PREFERAPN_URI, new String[] { "_id", "name", "apn" },
1413                null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
1414
1415        if (cursor != null) {
1416            canSetPreferApn = true;
1417        } else {
1418            canSetPreferApn = false;
1419        }
1420
1421        if (canSetPreferApn && cursor.getCount() > 0) {
1422            int pos;
1423            cursor.moveToFirst();
1424            pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID));
1425            for(ApnSetting p:allApns) {
1426                if (p.id == pos && p.canHandleType(mRequestedApnType)) {
1427                    cursor.close();
1428                    return p;
1429                }
1430            }
1431        }
1432
1433        if (cursor != null) {
1434            cursor.close();
1435        }
1436
1437        return null;
1438    }
1439
1440    public void handleMessage (Message msg) {
1441        if (DBG) Log.d(LOG_TAG,"GSMDataConnTrack handleMessage "+msg);
1442
1443        if (!mGsmPhone.mIsTheCurrentActivePhone) {
1444            Log.d(LOG_TAG, "Ignore GSM msgs since GSM phone is inactive");
1445            return;
1446        }
1447
1448        switch (msg.what) {
1449            case EVENT_RECORDS_LOADED:
1450                onRecordsLoaded();
1451                break;
1452
1453            case EVENT_GPRS_DETACHED:
1454                onGprsDetached();
1455                break;
1456
1457            case EVENT_GPRS_ATTACHED:
1458                onGprsAttached();
1459                break;
1460
1461            case EVENT_DATA_STATE_CHANGED:
1462                onPdpStateChanged((AsyncResult) msg.obj, false);
1463                break;
1464
1465            case EVENT_GET_PDP_LIST_COMPLETE:
1466                onPdpStateChanged((AsyncResult) msg.obj, true);
1467                break;
1468
1469            case EVENT_POLL_PDP:
1470                onPollPdp();
1471                break;
1472
1473            case EVENT_START_NETSTAT_POLL:
1474                mPingTestActive = false;
1475                startNetStatPoll();
1476                break;
1477
1478            case EVENT_START_RECOVERY:
1479                mPingTestActive = false;
1480                doRecovery();
1481                break;
1482
1483            case EVENT_APN_CHANGED:
1484                onApnChanged();
1485                break;
1486
1487            case EVENT_PS_RESTRICT_ENABLED:
1488                /**
1489                 * We don't need to explicitly to tear down the PDP context
1490                 * when PS restricted is enabled. The base band will deactive
1491                 * PDP context and notify us with PDP_CONTEXT_CHANGED.
1492                 * But we should stop the network polling and prevent reset PDP.
1493                 */
1494                Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted);
1495                stopNetStatPoll();
1496                mIsPsRestricted = true;
1497                break;
1498
1499            case EVENT_PS_RESTRICT_DISABLED:
1500                /**
1501                 * When PS restrict is removed, we need setup PDP connection if
1502                 * PDP connection is down.
1503                 */
1504                Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted);
1505                mIsPsRestricted  = false;
1506                if (state == State.CONNECTED) {
1507                    startNetStatPoll();
1508                } else {
1509                    if (state == State.FAILED) {
1510                        cleanUpConnection(false, Phone.REASON_PS_RESTRICT_ENABLED);
1511                        mRetryMgr.resetRetryCount();
1512                        mReregisterOnReconnectFailure = false;
1513                    }
1514                    trySetupData(Phone.REASON_PS_RESTRICT_ENABLED);
1515                }
1516                break;
1517
1518            default:
1519                // handle the message in the super class DataConnectionTracker
1520                super.handleMessage(msg);
1521                break;
1522        }
1523    }
1524
1525    protected void log(String s) {
1526        Log.d(LOG_TAG, "[GsmDataConnectionTracker] " + s);
1527    }
1528}
1529