GsmDataConnectionTracker.java revision 02722fbd77fa22f60ed3778b806b1e8f176b88c1
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.NetworkInfo;
31import android.net.Uri;
32import android.net.wifi.WifiManager;
33import android.os.AsyncResult;
34import android.os.INetStatService;
35import android.os.Message;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.SystemClock;
39import android.os.SystemProperties;
40import android.preference.PreferenceManager;
41import android.provider.Checkin;
42import android.provider.Settings;
43import android.provider.Telephony;
44import android.telephony.ServiceState;
45import android.telephony.TelephonyManager;
46import android.telephony.gsm.GsmCellLocation;
47import android.text.TextUtils;
48import android.util.EventLog;
49import android.util.Log;
50
51import com.android.internal.telephony.DataCallState;
52import com.android.internal.telephony.DataConnection;
53import com.android.internal.telephony.DataConnectionTracker;
54import com.android.internal.telephony.Phone;
55import com.android.internal.telephony.RetryManager;
56import com.android.internal.telephony.TelephonyEventLog;
57import com.android.internal.telephony.DataConnection.FailCause;
58
59import java.io.IOException;
60import java.util.ArrayList;
61
62/**
63 * {@hide}
64 */
65public final class GsmDataConnectionTracker extends DataConnectionTracker {
66    protected final String LOG_TAG = "GSM";
67
68    private GSMPhone mGsmPhone;
69    /**
70     * Handles changes to the APN db.
71     */
72    private class ApnChangeObserver extends ContentObserver {
73        public ApnChangeObserver () {
74            super(mDataConnectionTracker);
75        }
76
77        @Override
78        public void onChange(boolean selfChange) {
79            sendMessage(obtainMessage(EVENT_APN_CHANGED));
80        }
81    }
82
83    //***** Instance Variables
84
85    INetStatService netstat;
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 retrys on the default APN
154    private RetryManager mDefaultRetryManager;
155    // for tracking retrys 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 disabeled, the NETWORK_STATE_CHANGED_ACTION
193                    // quit and wont report disconnected til next enalbing.
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        this.netstat = INetStatService.Stub.asInterface(ServiceManager.getService("netstat"));
222
223        IntentFilter filter = new IntentFilter();
224        filter.addAction(INTENT_RECONNECT_ALARM);
225        filter.addAction(Intent.ACTION_SCREEN_ON);
226        filter.addAction(Intent.ACTION_SCREEN_OFF);
227        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
228        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
229
230        // TODO: Why is this registering the phone as the receiver of the intent
231        //       and not its own handler?
232        p.getContext().registerReceiver(mIntentReceiver, filter, null, p);
233
234
235        mDataConnectionTracker = this;
236        mResolver = phone.getContext().getContentResolver();
237
238        apnObserver = new ApnChangeObserver();
239        p.getContext().getContentResolver().registerContentObserver(
240                Telephony.Carriers.CONTENT_URI, true, apnObserver);
241
242        createAllPdpList();
243
244        // This preference tells us 1) initial condition for "dataEnabled",
245        // and 2) whether the RIL will setup the baseband to auto-PS attach.
246        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(phone.getContext());
247        dataEnabled[APN_DEFAULT_ID] = !sp.getBoolean(GSMPhone.DATA_DISABLED_ON_BOOT_KEY, false);
248        if (dataEnabled[APN_DEFAULT_ID]) {
249            enabledCount++;
250        }
251        noAutoAttach = !dataEnabled[APN_DEFAULT_ID];
252
253        if (!mRetryMgr.configure(SystemProperties.get("ro.gsm.data_retry_config"))) {
254            if (!mRetryMgr.configure(DEFAULT_DATA_RETRY_CONFIG)) {
255                // Should never happen, log an error and default to a simple linear sequence.
256                Log.e(LOG_TAG, "Could not configure using DEFAULT_DATA_RETRY_CONFIG="
257                        + DEFAULT_DATA_RETRY_CONFIG);
258                mRetryMgr.configure(20, 2000, 1000);
259            }
260        }
261
262        mDefaultRetryManager = mRetryMgr;
263        mSecondaryRetryManager = new RetryManager();
264
265        if (!mSecondaryRetryManager.configure(SystemProperties.get(
266                "ro.gsm.2nd_data_retry_config"))) {
267            if (!mSecondaryRetryManager.configure(SECONDARY_DATA_RETRY_CONFIG)) {
268                // Should never happen, log an error and default to a simple sequence.
269                Log.e(LOG_TAG, "Could note configure using SECONDARY_DATA_RETRY_CONFIG="
270                        + SECONDARY_DATA_RETRY_CONFIG);
271                mSecondaryRetryManager.configure("max_retries=3, 333, 333, 333");
272            }
273        }
274    }
275
276    public void dispose() {
277        //Unregister for all events
278        phone.mCM.unregisterForAvailable(this);
279        phone.mCM.unregisterForOffOrNotAvailable(this);
280        mGsmPhone.mSIMRecords.unregisterForRecordsLoaded(this);
281        phone.mCM.unregisterForDataStateChanged(this);
282        mGsmPhone.mCT.unregisterForVoiceCallEnded(this);
283        mGsmPhone.mCT.unregisterForVoiceCallStarted(this);
284        mGsmPhone.mSST.unregisterForGprsAttached(this);
285        mGsmPhone.mSST.unregisterForGprsDetached(this);
286        mGsmPhone.mSST.unregisterForRoamingOn(this);
287        mGsmPhone.mSST.unregisterForRoamingOff(this);
288        mGsmPhone.mSST.unregisterForPsRestrictedEnabled(this);
289        mGsmPhone.mSST.unregisterForPsRestrictedDisabled(this);
290
291        phone.getContext().unregisterReceiver(this.mIntentReceiver);
292        phone.getContext().getContentResolver().unregisterContentObserver(this.apnObserver);
293
294        destroyAllPdpList();
295    }
296
297    protected void finalize() {
298        if(DBG) Log.d(LOG_TAG, "GsmDataConnectionTracker finalized");
299    }
300
301    protected void setState(State s) {
302        if (DBG) log ("setState: " + s);
303        if (state != s) {
304            if (s == State.INITING) { // request PDP context
305                Checkin.updateStats(
306                        phone.getContext().getContentResolver(),
307                        Checkin.Stats.Tag.PHONE_GPRS_ATTEMPTED, 1, 0.0);
308            }
309
310            if (s == State.CONNECTED) { // pppd is up
311                Checkin.updateStats(
312                        phone.getContext().getContentResolver(),
313                        Checkin.Stats.Tag.PHONE_GPRS_CONNECTED, 1, 0.0);
314            }
315        }
316
317        state = s;
318
319        if (state == State.FAILED) {
320            if (waitingApns != null)
321                waitingApns.clear(); // when teardown the connection and set to IDLE
322        }
323    }
324
325    public String[] getActiveApnTypes() {
326        String[] result;
327        if (mActiveApn != null) {
328            result = mActiveApn.types;
329        } else {
330            result = new String[1];
331            result[0] = Phone.APN_TYPE_DEFAULT;
332        }
333        return result;
334    }
335
336    protected String getActiveApnString() {
337        String result = null;
338        if (mActiveApn != null) {
339            result = mActiveApn.apn;
340        }
341        return result;
342    }
343
344    /**
345     * The data connection is expected to be setup while device
346     *  1. has sim card
347     *  2. registered to gprs service
348     *  3. user doesn't explicitly disable data service
349     *  4. wifi is not on
350     *
351     * @return false while no data connection if all above requirements are met.
352     */
353    public boolean isDataConnectionAsDesired() {
354        boolean roaming = phone.getServiceState().getRoaming();
355
356        if (mGsmPhone.mSIMRecords.getRecordsLoaded() &&
357                mGsmPhone.mSST.getCurrentGprsState() == ServiceState.STATE_IN_SERVICE &&
358                (!roaming || getDataOnRoamingEnabled()) &&
359            !mIsWifiConnected &&
360            !mIsPsRestricted ) {
361            return (state == State.CONNECTED);
362        }
363        return true;
364    }
365
366    @Override
367    protected boolean isApnTypeActive(String type) {
368        // TODO: support simultaneous with List instead
369        return mActiveApn != null && mActiveApn.canHandleType(type);
370    }
371
372    @Override
373    protected boolean isApnTypeAvailable(String type) {
374        if (allApns != null) {
375            for (ApnSetting apn : allApns) {
376                if (apn.canHandleType(type)) {
377                    return true;
378                }
379            }
380        }
381        return false;
382    }
383
384    /**
385     * Formerly this method was ArrayList<GsmDataConnection> getAllPdps()
386     */
387    public ArrayList<DataConnection> getAllDataConnections() {
388        ArrayList<DataConnection> pdps = (ArrayList<DataConnection>)pdpList.clone();
389        return pdps;
390    }
391
392    private boolean isDataAllowed() {
393        boolean roaming = phone.getServiceState().getRoaming();
394        return getAnyDataEnabled() && (!roaming || getDataOnRoamingEnabled()) &&
395                mMasterDataEnabled;
396    }
397
398    //****** Called from ServiceStateTracker
399    /**
400     * Invoked when ServiceStateTracker observes a transition from GPRS
401     * attach to detach.
402     */
403    protected void onGprsDetached() {
404        /*
405         * We presently believe it is unnecessary to tear down the PDP context
406         * when GPRS detaches, but we should stop the network polling.
407         */
408        stopNetStatPoll();
409        phone.notifyDataConnection(Phone.REASON_GPRS_DETACHED);
410    }
411
412    private void onGprsAttached() {
413        if (state == State.CONNECTED) {
414            startNetStatPoll();
415            phone.notifyDataConnection(Phone.REASON_GPRS_ATTACHED);
416        } else {
417            if (state == State.FAILED) {
418                cleanUpConnection(false, Phone.REASON_GPRS_ATTACHED);
419                mRetryMgr.resetRetryCount();
420            }
421            trySetupData(Phone.REASON_GPRS_ATTACHED);
422        }
423    }
424
425    private boolean trySetupData(String reason) {
426        if (DBG) log("***trySetupData due to " + (reason == null ? "(unspecified)" : reason));
427
428        Log.d(LOG_TAG, "[DSAC DEB] " + "trySetupData with mIsPsRestricted=" + mIsPsRestricted);
429
430        if (phone.getSimulatedRadioControl() != null) {
431            // Assume data is connected on the simulator
432            // FIXME  this can be improved
433            setState(State.CONNECTED);
434            phone.notifyDataConnection(reason);
435
436            Log.i(LOG_TAG, "(fix?) We're on the simulator; assuming data is connected");
437            return true;
438        }
439
440        int gprsState = mGsmPhone.mSST.getCurrentGprsState();
441        boolean desiredPowerState = mGsmPhone.mSST.getDesiredPowerState();
442
443        if ((state == State.IDLE || state == State.SCANNING)
444                && (gprsState == ServiceState.STATE_IN_SERVICE || noAutoAttach)
445                && mGsmPhone.mSIMRecords.getRecordsLoaded()
446                && phone.getState() == Phone.State.IDLE
447                && isDataAllowed()
448                && !mIsPsRestricted
449                && desiredPowerState ) {
450
451            if (state == State.IDLE) {
452                waitingApns = buildWaitingApns();
453                if (waitingApns.isEmpty()) {
454                    if (DBG) log("No APN found");
455                    notifyNoData(GsmDataConnection.FailCause.MISSING_UKNOWN_APN);
456                    return false;
457                } else {
458                    log ("Create from allApns : " + apnListToString(allApns));
459                }
460            }
461
462            if (DBG) {
463                log ("Setup waitngApns : " + apnListToString(waitingApns));
464            }
465            return setupData(reason);
466        } else {
467            if (DBG)
468                log("trySetupData: Not ready for data: " +
469                    " dataState=" + state +
470                    " gprsState=" + gprsState +
471                    " sim=" + mGsmPhone.mSIMRecords.getRecordsLoaded() +
472                    " UMTS=" + mGsmPhone.mSST.isConcurrentVoiceAndData() +
473                    " phoneState=" + phone.getState() +
474                    " isDataAllowed=" + isDataAllowed() +
475                    " dataEnabled=" + getAnyDataEnabled() +
476                    " roaming=" + phone.getServiceState().getRoaming() +
477                    " dataOnRoamingEnable=" + getDataOnRoamingEnabled() +
478                    " ps restricted=" + mIsPsRestricted +
479                    " desiredPowerState=" + desiredPowerState +
480                    " MasterDataEnabled=" + mMasterDataEnabled);
481            return false;
482        }
483    }
484
485    /**
486     * If tearDown is true, this only tears down a CONNECTED session. Presently,
487     * there is no mechanism for abandoning an INITING/CONNECTING session,
488     * but would likely involve cancelling pending async requests or
489     * setting a flag or new state to ignore them when they came in
490     * @param tearDown true if the underlying GsmDataConnection should be
491     * disconnected.
492     * @param reason reason for the clean up.
493     */
494    private void cleanUpConnection(boolean tearDown, String reason) {
495        if (DBG) log("Clean up connection due to " + reason);
496
497        // Clear the reconnect alarm, if set.
498        if (mReconnectIntent != null) {
499            AlarmManager am =
500                (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
501            am.cancel(mReconnectIntent);
502            mReconnectIntent = null;
503        }
504
505        setState(State.DISCONNECTING);
506
507        for (DataConnection conn : pdpList) {
508            if (tearDown) {
509                Message msg = obtainMessage(EVENT_DISCONNECT_DONE, reason);
510                conn.disconnect(msg);
511            } else {
512                conn.reset();
513            }
514        }
515        stopNetStatPoll();
516
517        if (!tearDown) {
518            setState(State.IDLE);
519            phone.notifyDataConnection(reason);
520            mActiveApn = null;
521        }
522    }
523
524    /**
525     * @param types comma delimited list of APN types
526     * @return array of APN types
527     */
528    private String[] parseTypes(String types) {
529        String[] result;
530        // If unset, set to DEFAULT.
531        if (types == null || types.equals("")) {
532            result = new String[1];
533            result[0] = Phone.APN_TYPE_ALL;
534        } else {
535            result = types.split(",");
536        }
537        return result;
538    }
539
540    private ArrayList<ApnSetting> createApnList(Cursor cursor) {
541        ArrayList<ApnSetting> result = new ArrayList<ApnSetting>();
542        if (cursor.moveToFirst()) {
543            do {
544                String[] types = parseTypes(
545                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
546                ApnSetting apn = new ApnSetting(
547                        cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
548                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
549                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)),
550                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
551                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY)),
552                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)),
553                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC)),
554                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY)),
555                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)),
556                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
557                        cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
558                        cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
559                        types);
560                result.add(apn);
561            } while (cursor.moveToNext());
562        }
563        return result;
564    }
565
566    private GsmDataConnection findFreePdp() {
567        for (DataConnection conn : pdpList) {
568            GsmDataConnection pdp = (GsmDataConnection) conn;
569            if (pdp.isInactive()) {
570                return pdp;
571            }
572        }
573        return null;
574    }
575
576    private boolean setupData(String reason) {
577        ApnSetting apn;
578        GsmDataConnection pdp;
579
580        apn = getNextApn();
581        if (apn == null) return false;
582        pdp = findFreePdp();
583        if (pdp == null) {
584            if (DBG) log("setupData: No free GsmDataConnection found!");
585            return false;
586        }
587        mActiveApn = apn;
588        mActivePdp = pdp;
589
590        Message msg = obtainMessage();
591        msg.what = EVENT_DATA_SETUP_COMPLETE;
592        msg.obj = reason;
593        pdp.connect(msg, apn);
594
595        setState(State.INITING);
596        phone.notifyDataConnection(reason);
597        return true;
598    }
599
600    protected String getInterfaceName(String apnType) {
601        if (mActivePdp != null &&
602                (apnType == null ||
603                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
604            return mActivePdp.getInterface();
605        }
606        return null;
607    }
608
609    protected String getIpAddress(String apnType) {
610        if (mActivePdp != null &&
611                (apnType == null ||
612                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
613            return mActivePdp.getIpAddress();
614        }
615        return null;
616    }
617
618    public String getGateway(String apnType) {
619        if (mActivePdp != null &&
620                (apnType == null ||
621                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
622            return mActivePdp.getGatewayAddress();
623        }
624        return null;
625    }
626
627    protected String[] getDnsServers(String apnType) {
628        if (mActivePdp != null &&
629                (apnType == null ||
630                (mActiveApn != null && mActiveApn.canHandleType(apnType)))) {
631            return mActivePdp.getDnsServers();
632        }
633        return null;
634    }
635
636    private boolean
637    pdpStatesHasCID (ArrayList<DataCallState> states, int cid) {
638        for (int i = 0, s = states.size() ; i < s ; i++) {
639            if (states.get(i).cid == cid) return true;
640        }
641
642        return false;
643    }
644
645    private boolean
646    pdpStatesHasActiveCID (ArrayList<DataCallState> states, int cid) {
647        for (int i = 0, s = states.size() ; i < s ; i++) {
648            if ((states.get(i).cid == cid) && (states.get(i).active != 0)) {
649                return true;
650            }
651        }
652
653        return false;
654    }
655
656    /**
657     * Handles changes to the APN database.
658     */
659    private void onApnChanged() {
660        boolean isConnected;
661
662        isConnected = (state != State.IDLE && state != State.FAILED);
663
664        // The "current" may no longer be valid.  MMS depends on this to send properly.
665        mGsmPhone.updateCurrentCarrierInProvider();
666
667        // TODO: It'd be nice to only do this if the changed entrie(s)
668        // match the current operator.
669        createAllApnList();
670        if (state != State.DISCONNECTING) {
671            cleanUpConnection(isConnected, Phone.REASON_APN_CHANGED);
672            if (!isConnected) {
673                // reset reconnect timer
674                mRetryMgr.resetRetryCount();
675                mReregisterOnReconnectFailure = false;
676                trySetupData(Phone.REASON_APN_CHANGED);
677            }
678        }
679    }
680
681    /**
682     * @param explicitPoll if true, indicates that *we* polled for this
683     * update while state == CONNECTED rather than having it delivered
684     * via an unsolicited response (which could have happened at any
685     * previous state
686     */
687    protected void onPdpStateChanged (AsyncResult ar, boolean explicitPoll) {
688        ArrayList<DataCallState> pdpStates;
689
690        pdpStates = (ArrayList<DataCallState>)(ar.result);
691
692        if (ar.exception != null) {
693            // This is probably "radio not available" or something
694            // of that sort. If so, the whole connection is going
695            // to come down soon anyway
696            return;
697        }
698
699        if (state == State.CONNECTED) {
700            // The way things are supposed to work, the PDP list
701            // should not contain the CID after it disconnects.
702            // However, the way things really work, sometimes the PDP
703            // context is still listed with active = false, which
704            // makes it hard to distinguish an activating context from
705            // an activated-and-then deactivated one.
706            if (!pdpStatesHasCID(pdpStates, cidActive)) {
707                // It looks like the PDP context has deactivated.
708                // Tear everything down and try to reconnect.
709
710                Log.i(LOG_TAG, "PDP connection has dropped. Reconnecting");
711
712                // Add an event log when the network drops PDP
713                int cid = -1;
714                GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
715                if (loc != null) cid = loc.getCid();
716                EventLog.List val = new EventLog.List(cid,
717                        TelephonyManager.getDefault().getNetworkType());
718                EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val);
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                    int cid = -1;
737                    GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
738                    if (loc != null) cid = loc.getCid();
739                    EventLog.List val = new EventLog.List(cid,
740                            TelephonyManager.getDefault().getNetworkType());
741                    EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val);
742
743                    cleanUpConnection(true, null);
744                }
745            }
746        }
747    }
748
749    private void notifyDefaultData(String reason) {
750        setState(State.CONNECTED);
751        phone.notifyDataConnection(reason);
752        startNetStatPoll();
753        // reset reconnect timer
754        mRetryMgr.resetRetryCount();
755        mReregisterOnReconnectFailure = false;
756    }
757
758    /**
759     * This is a kludge to deal with the fact that
760     * the PDP state change notification doesn't always work
761     * with certain RIL impl's/basebands
762     *
763     */
764    private void startPeriodicPdpPoll() {
765        removeMessages(EVENT_POLL_PDP);
766
767        sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS);
768    }
769
770    private void resetPollStats() {
771        txPkts = -1;
772        rxPkts = -1;
773        sentSinceLastRecv = 0;
774        netStatPollPeriod = POLL_NETSTAT_MILLIS;
775        mNoRecvPollCount = 0;
776    }
777
778    private void doRecovery() {
779        if (state == State.CONNECTED) {
780            int maxPdpReset = Settings.Gservices.getInt(mResolver,
781                    Settings.Gservices.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT,
782                    DEFAULT_MAX_PDP_RESET_FAIL);
783            if (mPdpResetCount < maxPdpReset) {
784                mPdpResetCount++;
785                EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, sentSinceLastRecv);
786                cleanUpConnection(true, Phone.REASON_PDP_RESET);
787            } else {
788                mPdpResetCount = 0;
789                EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_REREGISTER_NETWORK, sentSinceLastRecv);
790                mGsmPhone.mSST.reRegisterNetwork(null);
791            }
792            // TODO: Add increasingly drastic recovery steps, eg,
793            // reset the radio, reset the device.
794        }
795    }
796
797    protected void startNetStatPoll() {
798        if (state == State.CONNECTED && mPingTestActive == false && netStatPollEnabled == false) {
799            Log.d(LOG_TAG, "[DataConnection] Start poll NetStat");
800            resetPollStats();
801            netStatPollEnabled = true;
802            mPollNetStat.run();
803        }
804    }
805
806    protected void stopNetStatPoll() {
807        netStatPollEnabled = false;
808        removeCallbacks(mPollNetStat);
809        Log.d(LOG_TAG, "[DataConnection] Stop poll NetStat");
810    }
811
812    protected void restartRadio() {
813        Log.d(LOG_TAG, "************TURN OFF RADIO**************");
814        cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF);
815        phone.mCM.setRadioPower(false, null);
816        /* Note: no need to call setRadioPower(true).  Assuming the desired
817         * radio power state is still ON (as tracked by ServiceStateTracker),
818         * ServiceStateTracker will call setRadioPower when it receives the
819         * RADIO_STATE_CHANGED notification for the power off.  And if the
820         * desired power state has changed in the interim, we don't want to
821         * override it with an unconditional power on.
822         */
823
824        int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0"));
825        SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1));
826    }
827
828    private Runnable mPollNetStat = new Runnable()
829    {
830
831        public void run() {
832            long sent, received;
833            long preTxPkts = -1, preRxPkts = -1;
834
835            Activity newActivity;
836
837            preTxPkts = txPkts;
838            preRxPkts = rxPkts;
839
840            try {
841                txPkts = netstat.getMobileTxPackets();
842                rxPkts = netstat.getMobileRxPackets();
843            } catch (RemoteException e) {
844                txPkts = 0;
845                rxPkts = 0;
846            }
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.Gservices.getInt(mResolver,
883                    Settings.Gservices.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(TelephonyEventLog.EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED,
890                            sentSinceLastRecv);
891                }
892
893                int noRecvPollLimit = Settings.Gservices.getInt(mResolver,
894                        Settings.Gservices.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.Gservices.getInt(mResolver,
906                            Settings.Gservices.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.Gservices.getInt(mResolver,
926                            Settings.Gservices.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
927                } else {
928                    netStatPollPeriod = Settings.Gservices.getInt(mResolver,
929                            Settings.Gservices.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.Gservices.getString(mResolver,
944                    Settings.Gservices.PDP_WATCHDOG_PING_ADDRESS);
945            int deadline = Settings.Gservices.getInt(mResolver,
946                        Settings.Gservices.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(TelephonyEventLog.EVENT_LOG_PDP_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, "PREFERED 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                int cid = -1;
1152                GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
1153                if (loc != null) cid = loc.getCid();
1154
1155                EventLog.List val = new EventLog.List(
1156                        cause.ordinal(), cid,
1157                        TelephonyManager.getDefault().getNetworkType());
1158                EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_PDP_SETUP_FAIL, val);
1159            }
1160
1161            // No try for permanent failure
1162            if (cause.isPermanentFail()) {
1163                notifyNoData(cause);
1164                if (!mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
1165                    phone.notifyDataConnection(Phone.REASON_APN_FAILED);
1166                    onEnableApn(apnTypeToId(mRequestedApnType), DISABLED);
1167                }
1168                return;
1169            }
1170
1171            waitingApns.remove(0);
1172            if (waitingApns.isEmpty()) {
1173                // No more to try, start delayed retry
1174                startDelayedRetry(cause, reason);
1175            } else {
1176                // we still have more apns to try
1177                setState(State.SCANNING);
1178                // Wait a bit before trying the next APN, so that
1179                // we're not tying up the RIL command channel
1180                sendMessageDelayed(obtainMessage(EVENT_TRY_SETUP_DATA, reason), APN_DELAY_MILLIS);
1181            }
1182        }
1183    }
1184
1185    protected void onDisconnectDone(AsyncResult ar) {
1186        String reason = null;
1187        if(DBG) log("EVENT_DISCONNECT_DONE");
1188        if (ar.userObj instanceof String) {
1189           reason = (String) ar.userObj;
1190        }
1191        setState(State.IDLE);
1192        phone.notifyDataConnection(reason);
1193        mActiveApn = null;
1194        if (retryAfterDisconnected(reason)) {
1195            trySetupData(reason);
1196        }
1197    }
1198
1199    protected void onPollPdp() {
1200        if (state == State.CONNECTED) {
1201            // only poll when connected
1202            phone.mCM.getPDPContextList(this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE));
1203            sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS);
1204        }
1205    }
1206
1207    protected void onVoiceCallStarted() {
1208        if (state == State.CONNECTED && ! mGsmPhone.mSST.isConcurrentVoiceAndData()) {
1209            stopNetStatPoll();
1210            phone.notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED);
1211        }
1212    }
1213
1214    protected void onVoiceCallEnded() {
1215        if (state == State.CONNECTED) {
1216            if (!mGsmPhone.mSST.isConcurrentVoiceAndData()) {
1217                startNetStatPoll();
1218                phone.notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED);
1219            } else {
1220                // clean slate after call end.
1221                resetPollStats();
1222            }
1223        } else {
1224            // reset reconnect timer
1225            mRetryMgr.resetRetryCount();
1226            mReregisterOnReconnectFailure = false;
1227            // in case data setup was attempted when we were on a voice call
1228            trySetupData(Phone.REASON_VOICE_CALL_ENDED);
1229        }
1230    }
1231
1232    protected void onCleanUpConnection(boolean tearDown, String reason) {
1233        cleanUpConnection(tearDown, reason);
1234    }
1235
1236    /**
1237     * Based on the sim operator numeric, create a list for all possible pdps
1238     * with all apns associated with that pdp
1239     *
1240     *
1241     */
1242    private void createAllApnList() {
1243        allApns = new ArrayList<ApnSetting>();
1244        String operator = mGsmPhone.mSIMRecords.getSIMOperatorNumeric();
1245
1246        if (operator != null) {
1247            String selection = "numeric = '" + operator + "'";
1248
1249            Cursor cursor = phone.getContext().getContentResolver().query(
1250                    Telephony.Carriers.CONTENT_URI, null, selection, null, null);
1251
1252            if (cursor != null) {
1253                if (cursor.getCount() > 0) {
1254                    allApns = createApnList(cursor);
1255                    // TODO: Figure out where this fits in.  This basically just
1256                    // writes the pap-secrets file.  No longer tied to GsmDataConnection
1257                    // object.  Not used on current platform (no ppp).
1258                    //GsmDataConnection pdp = pdpList.get(pdp_name);
1259                    //if (pdp != null && pdp.dataLink != null) {
1260                    //    pdp.dataLink.setPasswordInfo(cursor);
1261                    //}
1262                }
1263                cursor.close();
1264            }
1265        }
1266
1267        if (allApns.isEmpty()) {
1268            if (DBG) log("No APN found for carrier: " + operator);
1269            preferredApn = null;
1270            notifyNoData(GsmDataConnection.FailCause.MISSING_UKNOWN_APN);
1271        } else {
1272            preferredApn = getPreferredApn();
1273            Log.d(LOG_TAG, "Get PreferredAPN");
1274            if (preferredApn != null && !preferredApn.numeric.equals(operator)) {
1275                preferredApn = null;
1276                setPreferredApn(-1);
1277            }
1278        }
1279    }
1280
1281    private void createAllPdpList() {
1282        pdpList = new ArrayList<DataConnection>();
1283        DataConnection pdp;
1284
1285        for (int i = 0; i < PDP_CONNECTION_POOL_SIZE; i++) {
1286            pdp = GsmDataConnection.makeDataConnection(mGsmPhone);
1287            pdpList.add(pdp);
1288         }
1289    }
1290
1291    private void destroyAllPdpList() {
1292        if(pdpList != null) {
1293            GsmDataConnection pdp;
1294            pdpList.removeAll(pdpList);
1295        }
1296    }
1297
1298    /**
1299     *
1300     * @return waitingApns list to be used to create PDP
1301     *          error when waitingApns.isEmpty()
1302     */
1303    private ArrayList<ApnSetting> buildWaitingApns() {
1304        ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>();
1305        String operator = mGsmPhone.mSIMRecords.getSIMOperatorNumeric();
1306
1307        if (mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
1308            if (canSetPreferApn && preferredApn != null) {
1309                Log.i(LOG_TAG, "Preferred APN:" + operator + ":"
1310                        + preferredApn.numeric + ":" + preferredApn);
1311                if (preferredApn.numeric.equals(operator)) {
1312                    Log.i(LOG_TAG, "Waiting APN set to preferred APN");
1313                    apnList.add(preferredApn);
1314                    return apnList;
1315                } else {
1316                    setPreferredApn(-1);
1317                    preferredApn = null;
1318                }
1319            }
1320        }
1321
1322        if (allApns != null) {
1323            for (ApnSetting apn : allApns) {
1324                if (apn.canHandleType(mRequestedApnType)) {
1325                    apnList.add(apn);
1326                }
1327            }
1328        }
1329        return apnList;
1330    }
1331
1332    /**
1333     * Get next apn in waitingApns
1334     * @return the first apn found in waitingApns, null if none
1335     */
1336    private ApnSetting getNextApn() {
1337        ArrayList<ApnSetting> list = waitingApns;
1338        ApnSetting apn = null;
1339
1340        if (list != null) {
1341            if (!list.isEmpty()) {
1342                apn = list.get(0);
1343            }
1344        }
1345        return apn;
1346    }
1347
1348    private String apnListToString (ArrayList<ApnSetting> apns) {
1349        StringBuilder result = new StringBuilder();
1350        for (int i = 0, size = apns.size(); i < size; i++) {
1351            result.append('[')
1352                  .append(apns.get(i).toString())
1353                  .append(']');
1354        }
1355        return result.toString();
1356    }
1357
1358    private void startDelayedRetry(GsmDataConnection.FailCause cause, String reason) {
1359        notifyNoData(cause);
1360        reconnectAfterFail(cause, reason);
1361    }
1362
1363    private void setPreferredApn(int pos) {
1364        if (!canSetPreferApn) {
1365            return;
1366        }
1367
1368        ContentResolver resolver = phone.getContext().getContentResolver();
1369        resolver.delete(PREFERAPN_URI, null, null);
1370
1371        if (pos >= 0) {
1372            ContentValues values = new ContentValues();
1373            values.put(APN_ID, pos);
1374            resolver.insert(PREFERAPN_URI, values);
1375        }
1376    }
1377
1378    private ApnSetting getPreferredApn() {
1379        if (allApns.isEmpty()) {
1380            return null;
1381        }
1382
1383        Cursor cursor = phone.getContext().getContentResolver().query(
1384                PREFERAPN_URI, new String[] { "_id", "name", "apn" },
1385                null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
1386
1387        if (cursor != null) {
1388            canSetPreferApn = true;
1389        } else {
1390            canSetPreferApn = false;
1391        }
1392
1393        if (canSetPreferApn && cursor.getCount() > 0) {
1394            int pos;
1395            cursor.moveToFirst();
1396            pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID));
1397            for(ApnSetting p:allApns) {
1398                if (p.id == pos && p.canHandleType(mRequestedApnType)) {
1399                    cursor.close();
1400                    return p;
1401                }
1402            }
1403        }
1404
1405        if (cursor != null) {
1406            cursor.close();
1407        }
1408
1409        return null;
1410    }
1411
1412    public void handleMessage (Message msg) {
1413        if (DBG) Log.d(LOG_TAG,"GSMDataConnTrack handleMessage "+msg);
1414
1415        if (!mGsmPhone.mIsTheCurrentActivePhone) {
1416            Log.d(LOG_TAG, "Ignore GSM msgs since GSM phone is inactive");
1417            return;
1418        }
1419
1420        switch (msg.what) {
1421            case EVENT_RECORDS_LOADED:
1422                onRecordsLoaded();
1423                break;
1424
1425            case EVENT_GPRS_DETACHED:
1426                onGprsDetached();
1427                break;
1428
1429            case EVENT_GPRS_ATTACHED:
1430                onGprsAttached();
1431                break;
1432
1433            case EVENT_DATA_STATE_CHANGED:
1434                onPdpStateChanged((AsyncResult) msg.obj, false);
1435                break;
1436
1437            case EVENT_GET_PDP_LIST_COMPLETE:
1438                onPdpStateChanged((AsyncResult) msg.obj, true);
1439                break;
1440
1441            case EVENT_POLL_PDP:
1442                onPollPdp();
1443                break;
1444
1445            case EVENT_START_NETSTAT_POLL:
1446                mPingTestActive = false;
1447                startNetStatPoll();
1448                break;
1449
1450            case EVENT_START_RECOVERY:
1451                mPingTestActive = false;
1452                doRecovery();
1453                break;
1454
1455            case EVENT_APN_CHANGED:
1456                onApnChanged();
1457                break;
1458
1459            case EVENT_PS_RESTRICT_ENABLED:
1460                /**
1461                 * We don't need to explicitly to tear down the PDP context
1462                 * when PS restricted is enabled. The base band will deactive
1463                 * PDP context and notify us with PDP_CONTEXT_CHANGED.
1464                 * But we should stop the network polling and prevent reset PDP.
1465                 */
1466                Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted);
1467                stopNetStatPoll();
1468                mIsPsRestricted = true;
1469                break;
1470
1471            case EVENT_PS_RESTRICT_DISABLED:
1472                /**
1473                 * When PS restrict is removed, we need setup PDP connection if
1474                 * PDP connection is down.
1475                 */
1476                Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted);
1477                mIsPsRestricted  = false;
1478                if (state == State.CONNECTED) {
1479                    startNetStatPoll();
1480                } else {
1481                    if (state == State.FAILED) {
1482                        cleanUpConnection(false, Phone.REASON_PS_RESTRICT_ENABLED);
1483                        mRetryMgr.resetRetryCount();
1484                        mReregisterOnReconnectFailure = false;
1485                    }
1486                    trySetupData(Phone.REASON_PS_RESTRICT_ENABLED);
1487                }
1488                break;
1489
1490            default:
1491                // handle the message in the super class DataConnectionTracker
1492                super.handleMessage(msg);
1493                break;
1494        }
1495    }
1496
1497    protected void log(String s) {
1498        Log.d(LOG_TAG, "[GsmDataConnectionTracker] " + s);
1499    }
1500
1501}
1502