GsmDataConnectionTracker.java revision 9ac95783fc5aab204077d7c81e17e1b4f8afb3c1
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.TelephonyEventLog; 56import com.android.internal.telephony.DataConnection.FailCause; 57 58import java.io.IOException; 59import java.util.ArrayList; 60 61/** 62 * {@hide} 63 */ 64public final class GsmDataConnectionTracker extends DataConnectionTracker { 65 private static final String LOG_TAG = "GSM"; 66 private static final boolean DBG = true; 67 68 /** 69 * Handles changes to the APN db. 70 */ 71 private class ApnChangeObserver extends ContentObserver { 72 public ApnChangeObserver () { 73 super(mDataConnectionTracker); 74 } 75 76 @Override 77 public void onChange(boolean selfChange) { 78 sendMessage(obtainMessage(EVENT_APN_CHANGED)); 79 } 80 } 81 82 //***** Instance Variables 83 84 INetStatService netstat; 85 // Indicates baseband will not auto-attach 86 private boolean noAutoAttach = false; 87 long nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 88 private ContentResolver mResolver; 89 90 private boolean mPingTestActive = false; 91 // Count of PDP reset attempts; reset when we see incoming, 92 // call reRegisterNetwork, or pingTest succeeds. 93 private int mPdpResetCount = 0; 94 private boolean mIsScreenOn = true; 95 96 //useful for debugging 97 boolean failNextConnect = false; 98 99 /** 100 * allApns holds all apns for this sim spn, retrieved from 101 * the Carrier DB. 102 * 103 * Create once after simcard info is loaded 104 */ 105 private ArrayList<ApnSetting> allApns = null; 106 107 /** 108 * waitingApns holds all apns that are waiting to be connected 109 * 110 * It is a subset of allApns and has the same format 111 */ 112 private ArrayList<ApnSetting> waitingApns = null; 113 114 private ApnSetting preferredApn = null; 115 116 /** 117 * pdpList holds all the PDP connection, i.e. IP Link in GPRS 118 */ 119 private ArrayList<DataConnection> pdpList; 120 121 /** Currently requested APN type */ 122 private String mRequestedApnType = Phone.APN_TYPE_DEFAULT; 123 124 /** Currently active APN */ 125 private ApnSetting mActiveApn; 126 127 /** Currently active PdpConnection */ 128 private PdpConnection mActivePdp; 129 130 private static int APN_DEFAULT_ID = 0; 131 private static int APN_MMS_ID = 1; 132 private static int APN_SUPL_ID = 2; 133 private static int APN_NUM_TYPES = 3; 134 135 private boolean[] dataEnabled = new boolean[APN_NUM_TYPES]; 136 137 /** Is packet service restricted by network */ 138 private boolean mIsPsRestricted = false; 139 140 //***** Constants 141 142 // TODO: Increase this to match the max number of simultaneous 143 // PDP contexts we plan to support. 144 /** 145 * Pool size of PdpConnection objects. 146 */ 147 private static final int PDP_CONNECTION_POOL_SIZE = 1; 148 149 private static final int POLL_PDP_MILLIS = 5 * 1000; 150 151 private static final String INTENT_RECONNECT_ALARM = "com.android.internal.telephony.gprs-reconnect"; 152 private static final String INTENT_RECONNECT_ALARM_EXTRA_REASON = "reason"; 153 154 static final Uri PREFERAPN_URI = Uri.parse("content://telephony/carriers/preferapn"); 155 static final String APN_ID = "apn_id"; 156 private boolean canSetPreferApn = false; 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 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 p.getContext().registerReceiver(mIntentReceiver, filter, null, p.h); 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 dataEnabled[APN_DEFAULT_ID] = !sp.getBoolean(GSMPhone.DATA_DISABLED_ON_BOOT_KEY, false); 246 noAutoAttach = !dataEnabled[APN_DEFAULT_ID]; 247 } 248 249 public void dispose() { 250 //Unregister for all events 251 phone.mCM.unregisterForAvailable(this); 252 phone.mCM.unregisterForOffOrNotAvailable(this); 253 ((GSMPhone) phone).mSIMRecords.unregisterForRecordsLoaded(this); 254 phone.mCM.unregisterForDataStateChanged(this); 255 ((GSMPhone) phone).mCT.unregisterForVoiceCallEnded(this); 256 ((GSMPhone) phone).mCT.unregisterForVoiceCallStarted(this); 257 ((GSMPhone) phone).mSST.unregisterForGprsAttached(this); 258 ((GSMPhone) phone).mSST.unregisterForGprsDetached(this); 259 ((GSMPhone) phone).mSST.unregisterForRoamingOn(this); 260 ((GSMPhone) phone).mSST.unregisterForRoamingOff(this); 261 ((GSMPhone) phone).mSST.unregisterForPsRestrictedEnabled(this); 262 ((GSMPhone) phone).mSST.unregisterForPsRestrictedDisabled(this); 263 264 phone.getContext().unregisterReceiver(this.mIntentReceiver); 265 phone.getContext().getContentResolver().unregisterContentObserver(this.apnObserver); 266 267 destroyAllPdpList(); 268 } 269 270 protected void finalize() { 271 if(DBG) Log.d(LOG_TAG, "GsmDataConnectionTracker finalized"); 272 } 273 274 void setState(State s) { 275 if (DBG) log ("setState: " + s); 276 if (state != s) { 277 if (s == State.INITING) { // request PDP context 278 Checkin.updateStats( 279 phone.getContext().getContentResolver(), 280 Checkin.Stats.Tag.PHONE_GPRS_ATTEMPTED, 1, 0.0); 281 } 282 283 if (s == State.CONNECTED) { // pppd is up 284 Checkin.updateStats( 285 phone.getContext().getContentResolver(), 286 Checkin.Stats.Tag.PHONE_GPRS_CONNECTED, 1, 0.0); 287 } 288 } 289 290 state = s; 291 292 if (state == State.FAILED) { 293 if (waitingApns != null) 294 waitingApns.clear(); // when teardown the connection and set to IDLE 295 } 296 } 297 298 String[] getActiveApnTypes() { 299 String[] result; 300 if (mActiveApn != null) { 301 result = mActiveApn.types; 302 } else { 303 result = new String[1]; 304 result[0] = Phone.APN_TYPE_DEFAULT; 305 } 306 return result; 307 } 308 309 protected String getActiveApnString() { 310 String result = null; 311 if (mActiveApn != null) { 312 result = mActiveApn.apn; 313 } 314 return result; 315 } 316 317 /** 318 * Ensure that we are connected to an APN of the specified type. 319 * @param type the APN type (currently the only valid values 320 * are {@link Phone#APN_TYPE_MMS} and {@link Phone#APN_TYPE_SUPL}) 321 * @return the result of the operation. Success is indicated by 322 * a return value of either {@code Phone.APN_ALREADY_ACTIVE} or 323 * {@code Phone.APN_REQUEST_STARTED}. In the latter case, a broadcast 324 * will be sent by the ConnectivityManager when a connection to 325 * the APN has been established. 326 */ 327 protected int enableApnType(String type) { 328 if (!TextUtils.equals(type, Phone.APN_TYPE_MMS) && 329 !TextUtils.equals(type, Phone.APN_TYPE_SUPL)) { 330 return Phone.APN_REQUEST_FAILED; 331 } 332 333 // If already active, return 334 Log.d(LOG_TAG, "enableApnType("+type+")"); 335 if (isApnTypeActive(type)) { 336 setEnabled(type, true); 337 removeMessages(EVENT_RESTORE_DEFAULT_APN); 338 /** 339 * We're being asked to enable a non-default APN that's already in use. 340 * This means we should restart the timer that will automatically 341 * switch back to the default APN and disable the non-default APN 342 * when it expires. 343 */ 344 sendMessageDelayed( 345 obtainMessage(EVENT_RESTORE_DEFAULT_APN), 346 getRestoreDefaultApnDelay()); 347 if (state == State.INITING) return Phone.APN_REQUEST_STARTED; 348 else if (state == State.CONNECTED) return Phone.APN_ALREADY_ACTIVE; 349 } 350 351 if (!isApnTypeAvailable(type)) { 352 return Phone.APN_TYPE_NOT_AVAILABLE; 353 } 354 355 setEnabled(type, true); 356 mRequestedApnType = type; 357 sendMessage(obtainMessage(EVENT_ENABLE_NEW_APN)); 358 return Phone.APN_REQUEST_STARTED; 359 } 360 361 /** 362 * The APN of the specified type is no longer needed. Ensure that if 363 * use of the default APN has not been explicitly disabled, we are connected 364 * to the default APN. 365 * @param type the APN type. The only valid values are currently 366 * {@link Phone#APN_TYPE_MMS} and {@link Phone#APN_TYPE_SUPL}. 367 * @return 368 */ 369 protected int disableApnType(String type) { 370 Log.d(LOG_TAG, "disableApnType("+type+")"); 371 if ((TextUtils.equals(type, Phone.APN_TYPE_MMS) || 372 TextUtils.equals(type, Phone.APN_TYPE_SUPL)) 373 && isEnabled(type)) { 374 removeMessages(EVENT_RESTORE_DEFAULT_APN); 375 setEnabled(type, false); 376 if (isApnTypeActive(Phone.APN_TYPE_DEFAULT)) { 377 if (dataEnabled[APN_DEFAULT_ID]) { 378 return Phone.APN_ALREADY_ACTIVE; 379 } else { 380 cleanUpConnection(true, Phone.REASON_DATA_DISABLED); 381 return Phone.APN_REQUEST_STARTED; 382 } 383 } else { 384 /* 385 * Note that if default data is disabled, the following 386 * has the effect of disabling the MMS APN, and then 387 * ignoring the request to enable the default APN. 388 * The net result is that data is completely disabled. 389 */ 390 sendMessage(obtainMessage(EVENT_RESTORE_DEFAULT_APN)); 391 return Phone.APN_REQUEST_STARTED; 392 } 393 } else { 394 return Phone.APN_REQUEST_FAILED; 395 } 396 } 397 398 /** 399 * The data connection is expected to be setup while device 400 * 1. has sim card 401 * 2. registered to gprs service 402 * 3. user doesn't explicitly disable data service 403 * 4. wifi is not on 404 * 405 * @return false while no data connection if all above requirements are met. 406 */ 407 public boolean isDataConnectionAsDesired() { 408 boolean roaming = phone.getServiceState().getRoaming(); 409 410 if (((GSMPhone) phone).mSIMRecords.getRecordsLoaded() && 411 ((GSMPhone) phone).mSST.getCurrentGprsState() == ServiceState.STATE_IN_SERVICE && 412 (!roaming || getDataOnRoamingEnabled()) && 413 !mIsWifiConnected && 414 !mIsPsRestricted ) { 415 return (state == State.CONNECTED); 416 } 417 return true; 418 } 419 420 private boolean isApnTypeActive(String type) { 421 // TODO: to support simultaneous, mActiveApn can be a List instead. 422 return mActiveApn != null && mActiveApn.canHandleType(type); 423 } 424 425 private boolean isApnTypeAvailable(String type) { 426 if (allApns != null) { 427 for (ApnSetting apn : allApns) { 428 if (apn.canHandleType(type)) { 429 return true; 430 } 431 } 432 } 433 return false; 434 } 435 436 private boolean isEnabled(String apnType) { 437 if (TextUtils.equals(apnType, Phone.APN_TYPE_DEFAULT)) { 438 return dataEnabled[APN_DEFAULT_ID]; 439 } else if (TextUtils.equals(apnType, Phone.APN_TYPE_MMS)) { 440 return dataEnabled[APN_MMS_ID]; 441 } else if (TextUtils.equals(apnType, Phone.APN_TYPE_SUPL)) { 442 return dataEnabled[APN_SUPL_ID]; 443 } else { 444 return false; 445 } 446 } 447 448 private void setEnabled(String apnType, boolean enable) { 449 Log.d(LOG_TAG, "setEnabled(" + apnType + ", " + enable + ')'); 450 if (TextUtils.equals(apnType, Phone.APN_TYPE_DEFAULT)) { 451 dataEnabled[APN_DEFAULT_ID] = enable; 452 } else if (TextUtils.equals(apnType, Phone.APN_TYPE_MMS)) { 453 dataEnabled[APN_MMS_ID] = enable; 454 } else if (TextUtils.equals(apnType, Phone.APN_TYPE_SUPL)) { 455 dataEnabled[APN_SUPL_ID] = enable; 456 } 457 Log.d(LOG_TAG, "dataEnabled[DEFAULT_APN]=" + dataEnabled[APN_DEFAULT_ID] + 458 " dataEnabled[MMS_APN]=" + dataEnabled[APN_MMS_ID] + 459 " dataEnabled[SUPL_APN]=" + dataEnabled[APN_SUPL_ID]); 460 } 461 462 /** 463 * Prevent mobile data connections from being established, 464 * or once again allow mobile data connections. If the state 465 * toggles, then either tear down or set up data, as 466 * appropriate to match the new state. 467 * <p>This operation only affects the default APN, and if the same APN is 468 * currently being used for MMS traffic, the teardown will not happen 469 * even when {@code enable} is {@code false}.</p> 470 * @param enable indicates whether to enable ({@code true}) or disable ({@code false}) data 471 * @return {@code true} if the operation succeeded 472 */ 473 public boolean setDataEnabled(boolean enable) { 474 boolean isEnabled = isEnabled(Phone.APN_TYPE_DEFAULT); 475 Log.d(LOG_TAG, "setDataEnabled("+enable+") isEnabled=" + isEnabled); 476 if (!isEnabled && enable) { 477 setEnabled(Phone.APN_TYPE_DEFAULT, true); 478 // trySetupData() will be a no-op if we are currently 479 // connected to the MMS APN 480 sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA)); 481 return true; 482 } else if (!enable) { 483 setEnabled(Phone.APN_TYPE_DEFAULT, false); 484 // Don't tear down if there is an active APN and it handles MMS or SUPL. 485 // TODO: This isn't very general. 486 if ((isApnTypeActive(Phone.APN_TYPE_MMS) && isEnabled(Phone.APN_TYPE_MMS)) || 487 (isApnTypeActive(Phone.APN_TYPE_SUPL) && isEnabled(Phone.APN_TYPE_SUPL))) { 488 return false; 489 } 490 Message msg = obtainMessage(EVENT_CLEAN_UP_CONNECTION); 491 msg.arg1 = 1; // tearDown is true 492 msg.obj = Phone.REASON_DATA_DISABLED; 493 sendMessage(msg); 494 return true; 495 } else { 496 // isEnabled && enable 497 return true; 498 } 499 } 500 501 /** 502 * Report the current state of data connectivity (enabled or disabled) for 503 * the default APN. 504 * @return {@code false} if data connectivity has been explicitly disabled, 505 * {@code true} otherwise. 506 */ 507 public boolean getDataEnabled() { 508 return dataEnabled[APN_DEFAULT_ID]; 509 } 510 511 /** 512 * Report on whether data connectivity is enabled for any APN. 513 * @return {@code false} if data connectivity has been explicitly disabled, 514 * {@code true} otherwise. 515 */ 516 public boolean getAnyDataEnabled() { 517 return dataEnabled[APN_DEFAULT_ID] || dataEnabled[APN_MMS_ID] || dataEnabled[APN_SUPL_ID]; 518 } 519 520 /** 521 * Formerly this method was ArrayList<PdpConnection> getAllPdps() 522 */ 523 public ArrayList<DataConnection> getAllDataConnections() { 524 ArrayList<DataConnection> pdps = (ArrayList<DataConnection>)pdpList.clone(); 525 return pdps; 526 } 527 528 private boolean isDataAllowed() { 529 boolean roaming = phone.getServiceState().getRoaming(); 530 return getAnyDataEnabled() && (!roaming || getDataOnRoamingEnabled()); 531 } 532 533 //****** Called from ServiceStateTracker 534 /** 535 * Invoked when ServiceStateTracker observes a transition from GPRS 536 * attach to detach. 537 */ 538 protected void onGprsDetached() { 539 /* 540 * We presently believe it is unnecessary to tear down the PDP context 541 * when GPRS detaches, but we should stop the network polling. 542 */ 543 stopNetStatPoll(); 544 phone.notifyDataConnection(Phone.REASON_GPRS_DETACHED); 545 } 546 547 private void onGprsAttached() { 548 if (state == State.CONNECTED) { 549 startNetStatPoll(); 550 phone.notifyDataConnection(Phone.REASON_GPRS_ATTACHED); 551 } else { 552 if (state == State.FAILED) { 553 cleanUpConnection(false, Phone.REASON_GPRS_ATTACHED); 554 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 555 } 556 trySetupData(Phone.REASON_GPRS_ATTACHED); 557 } 558 } 559 560 private boolean trySetupData(String reason) { 561 if (DBG) log("***trySetupData due to " + (reason == null ? "(unspecified)" : reason)); 562 563 Log.d(LOG_TAG, "[DSAC DEB] " + "trySetupData with mIsPsRestricted=" + mIsPsRestricted); 564 565 if (phone.getSimulatedRadioControl() != null) { 566 // Assume data is connected on the simulator 567 // FIXME this can be improved 568 setState(State.CONNECTED); 569 phone.notifyDataConnection(reason); 570 571 Log.i(LOG_TAG, "(fix?) We're on the simulator; assuming data is connected"); 572 return true; 573 } 574 575 int gprsState = ((GSMPhone) phone).mSST.getCurrentGprsState(); 576 boolean roaming = phone.getServiceState().getRoaming(); 577 boolean desiredPowerState = ((GSMPhone) phone).mSST.getDesiredPowerState(); 578 579 if ((state == State.IDLE || state == State.SCANNING) 580 && (gprsState == ServiceState.STATE_IN_SERVICE || noAutoAttach) 581 && ((GSMPhone) phone).mSIMRecords.getRecordsLoaded() 582 && phone.getState() == Phone.State.IDLE 583 && isDataAllowed() 584 && !mIsPsRestricted 585 && desiredPowerState ) { 586 587 if (state == State.IDLE) { 588 waitingApns = buildWaitingApns(); 589 if (waitingApns.isEmpty()) { 590 if (DBG) log("No APN found"); 591 notifyNoData(PdpConnection.FailCause.BAD_APN); 592 return false; 593 } else { 594 log ("Create from allApns : " + apnListToString(allApns)); 595 } 596 } 597 598 if (DBG) { 599 log ("Setup watingApns : " + apnListToString(waitingApns)); 600 } 601 return setupData(reason); 602 } else { 603 if (DBG) 604 log("trySetupData: Not ready for data: " + 605 " dataState=" + state + 606 " gprsState=" + gprsState + 607 " sim=" + ((GSMPhone) phone).mSIMRecords.getRecordsLoaded() + 608 " UMTS=" + ((GSMPhone) phone).mSST.isConcurrentVoiceAndData() + 609 " phoneState=" + phone.getState() + 610 " dataEnabled=" + getAnyDataEnabled() + 611 " roaming=" + roaming + 612 " dataOnRoamingEnable=" + getDataOnRoamingEnabled() + 613 " ps restricted=" + mIsPsRestricted + 614 " desiredPowerState=" + desiredPowerState); 615 return false; 616 } 617 } 618 619 /** 620 * If tearDown is true, this only tears down a CONNECTED session. Presently, 621 * there is no mechanism for abandoning an INITING/CONNECTING session, 622 * but would likely involve cancelling pending async requests or 623 * setting a flag or new state to ignore them when they came in 624 * @param tearDown true if the underlying PdpConnection should be 625 * disconnected. 626 * @param reason reason for the clean up. 627 */ 628 private void cleanUpConnection(boolean tearDown, String reason) { 629 if (DBG) log("Clean up connection due to " + reason); 630 631 // Clear the reconnect alarm, if set. 632 if (mReconnectIntent != null) { 633 AlarmManager am = 634 (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE); 635 am.cancel(mReconnectIntent); 636 mReconnectIntent = null; 637 } 638 639 for (DataConnection conn : pdpList) { 640 PdpConnection pdp = (PdpConnection) conn; 641 if (tearDown) { 642 Message msg = obtainMessage(EVENT_DISCONNECT_DONE, reason); 643 pdp.disconnect(msg); 644 } else { 645 pdp.clearSettings(); 646 } 647 } 648 stopNetStatPoll(); 649 650 /* 651 * If we've been asked to tear down the connection, 652 * set the state to DISCONNECTING. However, there's 653 * a race that can occur if for some reason we were 654 * already in the IDLE state. In that case, the call 655 * to pdp.disconnect() above will immediately post 656 * a message to the handler thread that the disconnect 657 * is done, and if the handler runs before the code 658 * below does, the handler will have set the state to 659 * IDLE before the code below runs. If we didn't check 660 * for that, future calls to trySetupData would fail, 661 * and we would never get out of the DISCONNECTING state. 662 */ 663 if (!tearDown) { 664 setState(State.IDLE); 665 phone.notifyDataConnection(reason); 666 mActiveApn = null; 667 } else if (state != State.IDLE) { 668 setState(State.DISCONNECTING); 669 } 670 } 671 672 /** 673 * @param types comma delimited list of APN types 674 * @return array of APN types 675 */ 676 private String[] parseTypes(String types) { 677 String[] result; 678 // If unset, set to DEFAULT. 679 if (types == null || types.equals("")) { 680 result = new String[1]; 681 result[0] = Phone.APN_TYPE_ALL; 682 } else { 683 result = types.split(","); 684 } 685 return result; 686 } 687 688 private ArrayList<ApnSetting> createApnList(Cursor cursor) { 689 ArrayList<ApnSetting> result = new ArrayList<ApnSetting>(); 690 if (cursor.moveToFirst()) { 691 do { 692 String[] types = parseTypes( 693 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE))); 694 ApnSetting apn = new ApnSetting( 695 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)), 696 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)), 697 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)), 698 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)), 699 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY)), 700 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)), 701 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC)), 702 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY)), 703 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)), 704 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)), 705 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)), 706 types); 707 result.add(apn); 708 } while (cursor.moveToNext()); 709 } 710 return result; 711 } 712 713 private PdpConnection findFreePdp() { 714 for (DataConnection conn : pdpList) { 715 PdpConnection pdp = (PdpConnection) conn; 716 if (pdp.getState() == DataConnection.State.INACTIVE) { 717 return pdp; 718 } 719 } 720 return null; 721 } 722 723 private boolean setupData(String reason) { 724 ApnSetting apn; 725 PdpConnection pdp; 726 727 apn = getNextApn(); 728 if (apn == null) return false; 729 pdp = findFreePdp(); 730 if (pdp == null) { 731 if (DBG) log("setupData: No free PdpConnection found!"); 732 return false; 733 } 734 mActiveApn = apn; 735 mActivePdp = pdp; 736 737 Message msg = obtainMessage(); 738 msg.what = EVENT_DATA_SETUP_COMPLETE; 739 msg.obj = reason; 740 pdp.connect(apn, msg); 741 742 setState(State.INITING); 743 phone.notifyDataConnection(reason); 744 return true; 745 } 746 747 String getInterfaceName(String apnType) { 748 if (mActivePdp != null 749 && (apnType == null || mActiveApn.canHandleType(apnType))) { 750 return mActivePdp.getInterface(); 751 } 752 return null; 753 } 754 755 protected String getIpAddress(String apnType) { 756 if (mActivePdp != null 757 && (apnType == null || mActiveApn.canHandleType(apnType))) { 758 return mActivePdp.getIpAddress(); 759 } 760 return null; 761 } 762 763 String getGateway(String apnType) { 764 if (mActivePdp != null 765 && (apnType == null || mActiveApn.canHandleType(apnType))) { 766 return mActivePdp.getGatewayAddress(); 767 } 768 return null; 769 } 770 771 protected String[] getDnsServers(String apnType) { 772 if (mActivePdp != null 773 && (apnType == null || mActiveApn.canHandleType(apnType))) { 774 return mActivePdp.getDnsServers(); 775 } 776 return null; 777 } 778 779 private boolean 780 pdpStatesHasCID (ArrayList<DataCallState> states, int cid) { 781 for (int i = 0, s = states.size() ; i < s ; i++) { 782 if (states.get(i).cid == cid) return true; 783 } 784 785 return false; 786 } 787 788 private boolean 789 pdpStatesHasActiveCID (ArrayList<DataCallState> states, int cid) { 790 for (int i = 0, s = states.size() ; i < s ; i++) { 791 if ((states.get(i).cid == cid) && (states.get(i).active != 0)) { 792 return true; 793 } 794 } 795 796 return false; 797 } 798 799 /** 800 * Handles changes to the APN database. 801 */ 802 private void onApnChanged() { 803 boolean isConnected; 804 805 isConnected = (state != State.IDLE && state != State.FAILED); 806 807 // The "current" may no longer be valid. MMS depends on this to send properly. 808 ((GSMPhone) phone).updateCurrentCarrierInProvider(); 809 810 // TODO: It'd be nice to only do this if the changed entrie(s) 811 // match the current operator. 812 createAllApnList(); 813 if (state != State.DISCONNECTING) { 814 cleanUpConnection(isConnected, Phone.REASON_APN_CHANGED); 815 if (!isConnected) { 816 trySetupData(Phone.REASON_APN_CHANGED); 817 } 818 } 819 } 820 821 /** 822 * @param explicitPoll if true, indicates that *we* polled for this 823 * update while state == CONNECTED rather than having it delivered 824 * via an unsolicited response (which could have happened at any 825 * previous state 826 */ 827 protected void onPdpStateChanged (AsyncResult ar, boolean explicitPoll) { 828 ArrayList<DataCallState> pdpStates; 829 830 pdpStates = (ArrayList<DataCallState>)(ar.result); 831 832 if (ar.exception != null) { 833 // This is probably "radio not available" or something 834 // of that sort. If so, the whole connection is going 835 // to come down soon anyway 836 return; 837 } 838 839 if (state == State.CONNECTED) { 840 // The way things are supposed to work, the PDP list 841 // should not contain the CID after it disconnects. 842 // However, the way things really work, sometimes the PDP 843 // context is still listed with active = false, which 844 // makes it hard to distinguish an activating context from 845 // an activated-and-then deactivated one. 846 if (!pdpStatesHasCID(pdpStates, cidActive)) { 847 // It looks like the PDP context has deactivated. 848 // Tear everything down and try to reconnect. 849 850 Log.i(LOG_TAG, "PDP connection has dropped. Reconnecting"); 851 852 // Add an event log when the network drops PDP 853 int cid = -1; 854 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 855 if (loc != null) cid = loc.getCid(); 856 EventLog.List val = new EventLog.List(cid, 857 TelephonyManager.getDefault().getNetworkType()); 858 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); 859 860 cleanUpConnection(true, null); 861 return; 862 } else if (!pdpStatesHasActiveCID(pdpStates, cidActive)) { 863 // Here, we only consider this authoritative if we asked for the 864 // PDP list. If it was an unsolicited response, we poll again 865 // to make sure everyone agrees on the initial state. 866 867 if (!explicitPoll) { 868 // We think it disconnected but aren't sure...poll from our side 869 phone.mCM.getPDPContextList( 870 this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 871 } else { 872 Log.i(LOG_TAG, "PDP connection has dropped (active=false case). " 873 + " Reconnecting"); 874 875 // Log the network drop on the event log. 876 int cid = -1; 877 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 878 if (loc != null) cid = loc.getCid(); 879 EventLog.List val = new EventLog.List(cid, 880 TelephonyManager.getDefault().getNetworkType()); 881 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); 882 883 cleanUpConnection(true, null); 884 } 885 } 886 } 887 } 888 889 private void notifyDefaultData(String reason) { 890 setupDnsProperties(); 891 setState(State.CONNECTED); 892 phone.notifyDataConnection(reason); 893 startNetStatPoll(); 894 // reset reconnect timer 895 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 896 } 897 898 private void setupDnsProperties() { 899 int mypid = android.os.Process.myPid(); 900 String[] servers = getDnsServers(null); 901 String propName; 902 String propVal; 903 int count; 904 905 count = 0; 906 for (int i = 0; i < servers.length; i++) { 907 String serverAddr = servers[i]; 908 if (!TextUtils.equals(serverAddr, "0.0.0.0")) { 909 SystemProperties.set("net.dns" + (i+1) + "." + mypid, serverAddr); 910 count++; 911 } 912 } 913 for (int i = count+1; i <= 4; i++) { 914 propName = "net.dns" + i + "." + mypid; 915 propVal = SystemProperties.get(propName); 916 if (propVal.length() != 0) { 917 SystemProperties.set(propName, ""); 918 } 919 } 920 /* 921 * Bump the property that tells the name resolver library 922 * to reread the DNS server list from the properties. 923 */ 924 propVal = SystemProperties.get("net.dnschange"); 925 if (propVal.length() != 0) { 926 try { 927 int n = Integer.parseInt(propVal); 928 SystemProperties.set("net.dnschange", "" + (n+1)); 929 } catch (NumberFormatException e) { 930 } 931 } 932 } 933 934 /** 935 * This is a kludge to deal with the fact that 936 * the PDP state change notification doesn't always work 937 * with certain RIL impl's/basebands 938 * 939 */ 940 private void startPeriodicPdpPoll() { 941 removeMessages(EVENT_POLL_PDP); 942 943 sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS); 944 } 945 946 private void resetPollStats() { 947 txPkts = -1; 948 rxPkts = -1; 949 sentSinceLastRecv = 0; 950 netStatPollPeriod = POLL_NETSTAT_MILLIS; 951 mNoRecvPollCount = 0; 952 } 953 954 private void doRecovery() { 955 if (state == State.CONNECTED) { 956 int maxPdpReset = Settings.Gservices.getInt(mResolver, 957 Settings.Gservices.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT, 958 DEFAULT_MAX_PDP_RESET_FAIL); 959 if (mPdpResetCount < maxPdpReset) { 960 mPdpResetCount++; 961 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, sentSinceLastRecv); 962 cleanUpConnection(true, Phone.REASON_PDP_RESET); 963 } else { 964 mPdpResetCount = 0; 965 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_REREGISTER_NETWORK, sentSinceLastRecv); 966 ((GSMPhone) phone).mSST.reRegisterNetwork(null); 967 } 968 // TODO: Add increasingly drastic recovery steps, eg, 969 // reset the radio, reset the device. 970 } 971 } 972 973 protected void startNetStatPoll() { 974 if (state == State.CONNECTED && mPingTestActive == false && netStatPollEnabled == false) { 975 Log.d(LOG_TAG, "[DataConnection] Start poll NetStat"); 976 resetPollStats(); 977 netStatPollEnabled = true; 978 mPollNetStat.run(); 979 } 980 } 981 982 protected void stopNetStatPoll() { 983 netStatPollEnabled = false; 984 removeCallbacks(mPollNetStat); 985 Log.d(LOG_TAG, "[DataConnection] Stop poll NetStat"); 986 } 987 988 protected void restartRadio() { 989 Log.d(LOG_TAG, "************TURN OFF RADIO**************"); 990 cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); 991 phone.mCM.setRadioPower(false, null); 992 /* Note: no need to call setRadioPower(true). Assuming the desired 993 * radio power state is still ON (as tracked by ServiceStateTracker), 994 * ServiceStateTracker will call setRadioPower when it receives the 995 * RADIO_STATE_CHANGED notification for the power off. And if the 996 * desired power state has changed in the interim, we don't want to 997 * override it with an unconditional power on. 998 */ 999 1000 int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0")); 1001 SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1)); 1002 } 1003 1004 private Runnable mPollNetStat = new Runnable() 1005 { 1006 1007 public void run() { 1008 long sent, received; 1009 long preTxPkts = -1, preRxPkts = -1; 1010 1011 Activity newActivity; 1012 1013 preTxPkts = txPkts; 1014 preRxPkts = rxPkts; 1015 1016 try { 1017 txPkts = netstat.getMobileTxPackets(); 1018 rxPkts = netstat.getMobileRxPackets(); 1019 } catch (RemoteException e) { 1020 txPkts = 0; 1021 rxPkts = 0; 1022 } 1023 1024 //Log.d(LOG_TAG, "rx " + String.valueOf(rxPkts) + " tx " + String.valueOf(txPkts)); 1025 1026 if (netStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) { 1027 sent = txPkts - preTxPkts; 1028 received = rxPkts - preRxPkts; 1029 1030 if ( sent > 0 && received > 0 ) { 1031 sentSinceLastRecv = 0; 1032 newActivity = Activity.DATAINANDOUT; 1033 mPdpResetCount = 0; 1034 } else if (sent > 0 && received == 0) { 1035 if (phone.getState() == Phone.State.IDLE) { 1036 sentSinceLastRecv += sent; 1037 } else { 1038 sentSinceLastRecv = 0; 1039 } 1040 newActivity = Activity.DATAOUT; 1041 } else if (sent == 0 && received > 0) { 1042 sentSinceLastRecv = 0; 1043 newActivity = Activity.DATAIN; 1044 mPdpResetCount = 0; 1045 } else if (sent == 0 && received == 0) { 1046 newActivity = Activity.NONE; 1047 } else { 1048 sentSinceLastRecv = 0; 1049 newActivity = Activity.NONE; 1050 } 1051 1052 if (activity != newActivity && mIsScreenOn) { 1053 activity = newActivity; 1054 phone.notifyDataActivity(); 1055 } 1056 } 1057 1058 int watchdogTrigger = Settings.Gservices.getInt(mResolver, 1059 Settings.Gservices.PDP_WATCHDOG_TRIGGER_PACKET_COUNT, 1060 NUMBER_SENT_PACKETS_OF_HANG); 1061 1062 if (sentSinceLastRecv >= watchdogTrigger) { 1063 // we already have NUMBER_SENT_PACKETS sent without ack 1064 if (mNoRecvPollCount == 0) { 1065 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED, 1066 sentSinceLastRecv); 1067 } 1068 1069 int noRecvPollLimit = Settings.Gservices.getInt(mResolver, 1070 Settings.Gservices.PDP_WATCHDOG_ERROR_POLL_COUNT, NO_RECV_POLL_LIMIT); 1071 1072 if (mNoRecvPollCount < noRecvPollLimit) { 1073 // It's possible the PDP context went down and we weren't notified. 1074 // Start polling the context list in an attempt to recover. 1075 if (DBG) log("no DATAIN in a while; polling PDP"); 1076 phone.mCM.getDataCallList(obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 1077 1078 mNoRecvPollCount++; 1079 1080 // Slow down the poll interval to let things happen 1081 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1082 Settings.Gservices.PDP_WATCHDOG_ERROR_POLL_INTERVAL_MS, 1083 POLL_NETSTAT_SLOW_MILLIS); 1084 } else { 1085 if (DBG) log("Sent " + String.valueOf(sentSinceLastRecv) + 1086 " pkts since last received"); 1087 // We've exceeded the threshold. Run ping test as a final check; 1088 // it will proceed with recovery if ping fails. 1089 stopNetStatPoll(); 1090 Thread pingTest = new Thread() { 1091 public void run() { 1092 runPingTest(); 1093 } 1094 }; 1095 mPingTestActive = true; 1096 pingTest.start(); 1097 } 1098 } else { 1099 mNoRecvPollCount = 0; 1100 if (mIsScreenOn) { 1101 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1102 Settings.Gservices.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS); 1103 } else { 1104 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1105 Settings.Gservices.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS, 1106 POLL_NETSTAT_SCREEN_OFF_MILLIS); 1107 } 1108 } 1109 1110 if (netStatPollEnabled) { 1111 mDataConnectionTracker.postDelayed(this, netStatPollPeriod); 1112 } 1113 } 1114 }; 1115 1116 private void runPingTest () { 1117 int status = -1; 1118 try { 1119 String address = Settings.Gservices.getString(mResolver, 1120 Settings.Gservices.PDP_WATCHDOG_PING_ADDRESS); 1121 int deadline = Settings.Gservices.getInt(mResolver, 1122 Settings.Gservices.PDP_WATCHDOG_PING_DEADLINE, DEFAULT_PING_DEADLINE); 1123 if (DBG) log("pinging " + address + " for " + deadline + "s"); 1124 if (address != null && !NULL_IP.equals(address)) { 1125 Process p = Runtime.getRuntime() 1126 .exec("ping -c 1 -i 1 -w "+ deadline + " " + address); 1127 status = p.waitFor(); 1128 } 1129 } catch (IOException e) { 1130 Log.w(LOG_TAG, "ping failed: IOException"); 1131 } catch (Exception e) { 1132 Log.w(LOG_TAG, "exception trying to ping"); 1133 } 1134 1135 if (status == 0) { 1136 // ping succeeded. False alarm. Reset netStatPoll. 1137 // ("-1" for this event indicates a false alarm) 1138 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, -1); 1139 mPdpResetCount = 0; 1140 sendMessage(obtainMessage(EVENT_START_NETSTAT_POLL)); 1141 } else { 1142 // ping failed. Proceed with recovery. 1143 sendMessage(obtainMessage(EVENT_START_RECOVERY)); 1144 } 1145 } 1146 1147 /** 1148 * Returns true if the last fail cause is something that 1149 * seems like it deserves an error notification. 1150 * Transient errors are ignored 1151 */ 1152 private boolean shouldPostNotification(PdpConnection.FailCause cause) { 1153 boolean shouldPost = true; 1154 // TODO CHECK 1155 // if (dataLink != null) { 1156 // shouldPost = dataLink.getLastLinkExitCode() != DataLink.EXIT_OPEN_FAILED; 1157 //} 1158 return (shouldPost && cause != PdpConnection.FailCause.UNKNOWN); 1159 } 1160 1161 /** 1162 * Return true if data connection need to be setup after disconnected due to 1163 * reason. 1164 * 1165 * @param reason the reason why data is disconnected 1166 * @return true if try setup data connection is need for this reason 1167 */ 1168 private boolean retryAfterDisconnected(String reason) { 1169 boolean retry = true; 1170 1171 if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) || 1172 Phone.REASON_DATA_DISABLED.equals(reason) ) { 1173 retry = false; 1174 } 1175 return retry; 1176 } 1177 1178 private void reconnectAfterFail(FailCause lastFailCauseCode, String reason) { 1179 if (state == State.FAILED) { 1180 Log.d(LOG_TAG, "PDP activate failed. Scheduling next attempt for " 1181 + (nextReconnectDelay / 1000) + "s"); 1182 1183 AlarmManager am = 1184 (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE); 1185 Intent intent = new Intent(INTENT_RECONNECT_ALARM); 1186 intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON, reason); 1187 mReconnectIntent = PendingIntent.getBroadcast( 1188 phone.getContext(), 0, intent, 0); 1189 am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1190 SystemClock.elapsedRealtime() + nextReconnectDelay, 1191 mReconnectIntent); 1192 1193 // double it for next time 1194 nextReconnectDelay *= 2; 1195 if (nextReconnectDelay > RECONNECT_DELAY_MAX_MILLIS) { 1196 nextReconnectDelay = RECONNECT_DELAY_MAX_MILLIS; 1197 } 1198 1199 if (!shouldPostNotification(lastFailCauseCode)) { 1200 Log.d(LOG_TAG,"NOT Posting GPRS Unavailable notification " 1201 + "-- likely transient error"); 1202 } else { 1203 notifyNoData(lastFailCauseCode); 1204 } 1205 } 1206 } 1207 1208 private void notifyNoData(PdpConnection.FailCause lastFailCauseCode) { 1209 setState(State.FAILED); 1210 } 1211 1212 protected void onRecordsLoaded() { 1213 createAllApnList(); 1214 if (state == State.FAILED) { 1215 cleanUpConnection(false, null); 1216 } 1217 sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA, Phone.REASON_SIM_LOADED)); 1218 } 1219 1220 protected void onEnableNewApn() { 1221 // TODO: To support simultaneous PDP contexts, this should really only call 1222 // cleanUpConnection if it needs to free up a PdpConnection. 1223 cleanUpConnection(true, Phone.REASON_APN_SWITCHED); 1224 } 1225 1226 protected void onTrySetupData(String reason) { 1227 trySetupData(reason); 1228 } 1229 1230 protected void onRestoreDefaultApn() { 1231 if (DBG) Log.d(LOG_TAG, "Restore default APN"); 1232 setEnabled(Phone.APN_TYPE_MMS, false); 1233 1234 if (!isApnTypeActive(Phone.APN_TYPE_DEFAULT)) { 1235 cleanUpConnection(true, Phone.REASON_RESTORE_DEFAULT_APN); 1236 mRequestedApnType = Phone.APN_TYPE_DEFAULT; 1237 } 1238 } 1239 1240 protected void onRoamingOff() { 1241 trySetupData(Phone.REASON_ROAMING_OFF); 1242 } 1243 1244 protected void onRoamingOn() { 1245 if (getDataOnRoamingEnabled()) { 1246 trySetupData(Phone.REASON_ROAMING_ON); 1247 } else { 1248 if (DBG) log("Tear down data connection on roaming."); 1249 cleanUpConnection(true, Phone.REASON_ROAMING_ON); 1250 } 1251 } 1252 1253 protected void onRadioAvailable() { 1254 if (phone.getSimulatedRadioControl() != null) { 1255 // Assume data is connected on the simulator 1256 // FIXME this can be improved 1257 setState(State.CONNECTED); 1258 phone.notifyDataConnection(null); 1259 1260 Log.i(LOG_TAG, "We're on the simulator; assuming data is connected"); 1261 } 1262 1263 if (state != State.IDLE) { 1264 cleanUpConnection(true, null); 1265 } 1266 } 1267 1268 protected void onRadioOffOrNotAvailable() { 1269 // Make sure our reconnect delay starts at the initial value 1270 // next time the radio comes on 1271 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 1272 1273 if (phone.getSimulatedRadioControl() != null) { 1274 // Assume data is connected on the simulator 1275 // FIXME this can be improved 1276 Log.i(LOG_TAG, "We're on the simulator; assuming radio off is meaningless"); 1277 } else { 1278 if (DBG) log("Radio is off and clean up all connection"); 1279 // TODO: Should we reset mRequestedApnType to "default"? 1280 cleanUpConnection(false, Phone.REASON_RADIO_TURNED_OFF); 1281 } 1282 } 1283 1284 protected void onDataSetupComplete(AsyncResult ar) { 1285 String reason = null; 1286 if (ar.userObj instanceof String) { 1287 reason = (String) ar.userObj; 1288 } 1289 1290 if (ar.exception == null) { 1291 // everything is setup 1292 1293 /* 1294 * We may have switched away from the default PDP context 1295 * in order to enable a "special" APN (e.g., for MMS 1296 * traffic). Set a timer to switch back and/or disable the 1297 * special APN, so that a negligient application doesn't 1298 * permanently prevent data connectivity. What we are 1299 * protecting against here is not malicious apps, but 1300 * rather an app that inadvertantly fails to reset to the 1301 * default APN, or that dies before doing so. 1302 */ 1303 if (dataEnabled[APN_MMS_ID] || dataEnabled[APN_SUPL_ID]) { 1304 removeMessages(EVENT_RESTORE_DEFAULT_APN); 1305 sendMessageDelayed(obtainMessage(EVENT_RESTORE_DEFAULT_APN), 1306 getRestoreDefaultApnDelay()); 1307 } 1308 if (isApnTypeActive(Phone.APN_TYPE_DEFAULT)) { 1309 SystemProperties.set("gsm.defaultpdpcontext.active", "true"); 1310 if (canSetPreferApn && preferredApn == null) { 1311 Log.d(LOG_TAG, "PREFERED APN is null"); 1312 preferredApn = mActiveApn; 1313 setPreferredApn(preferredApn.id); 1314 } 1315 } else { 1316 SystemProperties.set("gsm.defaultpdpcontext.active", "false"); 1317 } 1318 notifyDefaultData(reason); 1319 1320 // TODO: For simultaneous PDP support, we need to build another 1321 // trigger another TRY_SETUP_DATA for the next APN type. (Note 1322 // that the existing connection may service that type, in which 1323 // case we should try the next type, etc. 1324 } else { 1325 PdpConnection.FailCause cause; 1326 cause = (PdpConnection.FailCause) (ar.result); 1327 if(DBG) log("PDP setup failed " + cause); 1328 // Log this failure to the Event Logs. 1329 if (cause == PdpConnection.FailCause.BAD_APN || 1330 cause == PdpConnection.FailCause.BAD_PAP_SECRET || 1331 cause == PdpConnection.FailCause.BARRED || 1332 cause == PdpConnection.FailCause.RADIO_ERROR_RETRY || 1333 cause == PdpConnection.FailCause.SUSPENED_TEMPORARY || 1334 cause == PdpConnection.FailCause.UNKNOWN || 1335 cause == PdpConnection.FailCause.USER_AUTHENTICATION) { 1336 int cid = -1; 1337 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 1338 if (loc != null) cid = loc.getCid(); 1339 1340 EventLog.List val = new EventLog.List( 1341 cause.ordinal(), cid, 1342 TelephonyManager.getDefault().getNetworkType()); 1343 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_PDP_SETUP_FAIL, val); 1344 } 1345 1346 // No try for permanent failure 1347 if (cause.isPermanentFail()) { 1348 notifyNoData(cause); 1349 } 1350 1351 if (tryNextApn(cause)) { 1352 waitingApns.remove(0); 1353 if (waitingApns.isEmpty()) { 1354 // No more to try, start delayed retry 1355 startDelayedRetry(cause, reason); 1356 } else { 1357 // we still have more apns to try 1358 setState(State.SCANNING); 1359 // Wait a bit before trying the next APN, so that 1360 // we're not tying up the RIL command channel 1361 sendMessageDelayed(obtainMessage(EVENT_TRY_SETUP_DATA, reason), 1362 RECONNECT_DELAY_INITIAL_MILLIS); 1363 } 1364 } else { 1365 startDelayedRetry(cause, reason); 1366 } 1367 } 1368 } 1369 1370 protected void onDisconnectDone(AsyncResult ar) { 1371 String reason = null; 1372 if(DBG) log("EVENT_DISCONNECT_DONE"); 1373 if (ar.userObj instanceof String) { 1374 reason = (String) ar.userObj; 1375 } 1376 setState(State.IDLE); 1377 phone.notifyDataConnection(reason); 1378 mActiveApn = null; 1379 if (retryAfterDisconnected(reason)) { 1380 trySetupData(reason); 1381 } 1382 } 1383 1384 protected void onPollPdp() { 1385 if (state == State.CONNECTED) { 1386 // only poll when connected 1387 phone.mCM.getPDPContextList(this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 1388 sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS); 1389 } 1390 } 1391 1392 protected void onVoiceCallStarted() { 1393 if (state == State.CONNECTED && !((GSMPhone) phone).mSST.isConcurrentVoiceAndData()) { 1394 stopNetStatPoll(); 1395 phone.notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED); 1396 } 1397 } 1398 1399 protected void onVoiceCallEnded() { 1400 if (state == State.CONNECTED) { 1401 if (!((GSMPhone) phone).mSST.isConcurrentVoiceAndData()) { 1402 startNetStatPoll(); 1403 phone.notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED); 1404 } else { 1405 // clean slate after call end. 1406 resetPollStats(); 1407 } 1408 } else { 1409 // in case data setup was attempted when we were on a voice call 1410 trySetupData(Phone.REASON_VOICE_CALL_ENDED); 1411 } 1412 } 1413 1414 protected void onCleanUpConnection(boolean tearDown, String reason) { 1415 cleanUpConnection(tearDown, reason); 1416 } 1417 1418 private boolean tryNextApn(FailCause cause) { 1419 return (cause != FailCause.RADIO_NOT_AVAILABLE) 1420 && (cause != FailCause.RADIO_OFF) 1421 && (cause != FailCause.RADIO_ERROR_RETRY) 1422 && (cause != FailCause.NO_SIGNAL) 1423 && (cause != FailCause.SIM_LOCKED); 1424 } 1425 1426 private int getRestoreDefaultApnDelay() { 1427 String restoreApnDelayStr = SystemProperties.get(APN_RESTORE_DELAY_PROP_NAME); 1428 1429 if (restoreApnDelayStr != null && restoreApnDelayStr.length() != 0) { 1430 try { 1431 return Integer.valueOf(restoreApnDelayStr); 1432 } catch (NumberFormatException e) { 1433 } 1434 } 1435 return RESTORE_DEFAULT_APN_DELAY; 1436 } 1437 1438 /** 1439 * Based on the sim operator numeric, create a list for all possible pdps 1440 * with all apns associated with that pdp 1441 * 1442 * 1443 */ 1444 private void createAllApnList() { 1445 allApns = new ArrayList<ApnSetting>(); 1446 String operator = ((GSMPhone) phone).mSIMRecords.getSIMOperatorNumeric(); 1447 1448 if (operator != null) { 1449 String selection = "numeric = '" + operator + "'"; 1450 1451 Cursor cursor = phone.getContext().getContentResolver().query( 1452 Telephony.Carriers.CONTENT_URI, null, selection, null, null); 1453 1454 if (cursor != null) { 1455 if (cursor.getCount() > 0) { 1456 allApns = createApnList(cursor); 1457 // TODO: Figure out where this fits in. This basically just 1458 // writes the pap-secrets file. No longer tied to PdpConnection 1459 // object. Not used on current platform (no ppp). 1460 //PdpConnection pdp = pdpList.get(pdp_name); 1461 //if (pdp != null && pdp.dataLink != null) { 1462 // pdp.dataLink.setPasswordInfo(cursor); 1463 //} 1464 } 1465 cursor.close(); 1466 } 1467 } 1468 1469 if (allApns.isEmpty()) { 1470 if (DBG) log("No APN found for carrier: " + operator); 1471 preferredApn = null; 1472 notifyNoData(PdpConnection.FailCause.BAD_APN); 1473 } else { 1474 preferredApn = getPreferredApn(); 1475 Log.d(LOG_TAG, "Get PreferredAPN"); 1476 if (preferredApn != null && !preferredApn.numeric.equals(operator)) { 1477 preferredApn = null; 1478 setPreferredApn(-1); 1479 } 1480 } 1481 } 1482 1483 private void createAllPdpList() { 1484 pdpList = new ArrayList<DataConnection>(); 1485 DataConnection pdp; 1486 1487 for (int i = 0; i < PDP_CONNECTION_POOL_SIZE; i++) { 1488 pdp = new PdpConnection((GSMPhone) phone); 1489 pdpList.add(pdp); 1490 } 1491 } 1492 1493 private void destroyAllPdpList() { 1494 if(pdpList != null) { 1495 PdpConnection pdp; 1496 pdpList.removeAll(pdpList); 1497 } 1498 } 1499 1500 /** 1501 * 1502 * @return waitingApns list to be used to create PDP 1503 * error when waitingApns.isEmpty() 1504 */ 1505 private ArrayList<ApnSetting> buildWaitingApns() { 1506 ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>(); 1507 String operator = ((GSMPhone )phone).mSIMRecords.getSIMOperatorNumeric(); 1508 1509 if (mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) { 1510 if (canSetPreferApn && preferredApn != null) { 1511 Log.i(LOG_TAG, "Preferred APN:" + operator + ":" 1512 + preferredApn.numeric + ":" + preferredApn); 1513 if (preferredApn.numeric.equals(operator)) { 1514 Log.i(LOG_TAG, "Waiting APN set to preferred APN"); 1515 apnList.add(preferredApn); 1516 return apnList; 1517 } else { 1518 setPreferredApn(-1); 1519 preferredApn = null; 1520 } 1521 } 1522 } 1523 1524 if (allApns != null) { 1525 for (ApnSetting apn : allApns) { 1526 if (apn.canHandleType(mRequestedApnType)) { 1527 apnList.add(apn); 1528 } 1529 } 1530 } 1531 return apnList; 1532 } 1533 1534 /** 1535 * Get next apn in waitingApns 1536 * @return the first apn found in waitingApns, null if none 1537 */ 1538 private ApnSetting getNextApn() { 1539 ArrayList<ApnSetting> list = waitingApns; 1540 ApnSetting apn = null; 1541 1542 if (list != null) { 1543 if (!list.isEmpty()) { 1544 apn = list.get(0); 1545 } 1546 } 1547 return apn; 1548 } 1549 1550 private String apnListToString (ArrayList<ApnSetting> apns) { 1551 StringBuilder result = new StringBuilder(); 1552 for (int i = 0, size = apns.size(); i < size; i++) { 1553 result.append('[') 1554 .append(apns.get(i).toString()) 1555 .append(']'); 1556 } 1557 return result.toString(); 1558 } 1559 1560 private void startDelayedRetry(PdpConnection.FailCause cause, String reason) { 1561 notifyNoData(cause); 1562 if (mRequestedApnType != Phone.APN_TYPE_DEFAULT) { 1563 sendMessage(obtainMessage(EVENT_RESTORE_DEFAULT_APN)); 1564 } 1565 else { 1566 reconnectAfterFail(cause, reason); 1567 } 1568 } 1569 1570 private void setPreferredApn(int pos) { 1571 if (!canSetPreferApn) { 1572 return; 1573 } 1574 1575 ContentResolver resolver = phone.getContext().getContentResolver(); 1576 resolver.delete(PREFERAPN_URI, null, null); 1577 1578 if (pos >= 0) { 1579 ContentValues values = new ContentValues(); 1580 values.put(APN_ID, pos); 1581 resolver.insert(PREFERAPN_URI, values); 1582 } 1583 } 1584 1585 private ApnSetting getPreferredApn() { 1586 if (allApns.isEmpty()) { 1587 return null; 1588 } 1589 1590 Cursor cursor = phone.getContext().getContentResolver().query( 1591 PREFERAPN_URI, new String[] { "_id", "name", "apn" }, 1592 null, null, Telephony.Carriers.DEFAULT_SORT_ORDER); 1593 1594 if (cursor != null) { 1595 canSetPreferApn = true; 1596 } else { 1597 canSetPreferApn = false; 1598 } 1599 1600 if (canSetPreferApn && cursor.getCount() > 0) { 1601 int pos; 1602 cursor.moveToFirst(); 1603 pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)); 1604 for(ApnSetting p:allApns) { 1605 if (p.id == pos && p.canHandleType(mRequestedApnType)) { 1606 cursor.close(); 1607 return p; 1608 } 1609 } 1610 } 1611 1612 if (cursor != null) { 1613 cursor.close(); 1614 } 1615 1616 return null; 1617 } 1618 1619 public void handleMessage (Message msg) { 1620 1621 switch (msg.what) { 1622 case EVENT_RECORDS_LOADED: 1623 onRecordsLoaded(); 1624 break; 1625 1626 case EVENT_ENABLE_NEW_APN: 1627 onEnableNewApn(); 1628 break; 1629 1630 case EVENT_RESTORE_DEFAULT_APN: 1631 onRestoreDefaultApn(); 1632 break; 1633 1634 case EVENT_GPRS_DETACHED: 1635 onGprsDetached(); 1636 break; 1637 1638 case EVENT_GPRS_ATTACHED: 1639 onGprsAttached(); 1640 break; 1641 1642 case EVENT_DATA_STATE_CHANGED: 1643 onPdpStateChanged((AsyncResult) msg.obj, false); 1644 break; 1645 1646 case EVENT_GET_PDP_LIST_COMPLETE: 1647 onPdpStateChanged((AsyncResult) msg.obj, true); 1648 break; 1649 1650 case EVENT_POLL_PDP: 1651 onPollPdp(); 1652 break; 1653 1654 case EVENT_START_NETSTAT_POLL: 1655 mPingTestActive = false; 1656 startNetStatPoll(); 1657 break; 1658 1659 case EVENT_START_RECOVERY: 1660 mPingTestActive = false; 1661 doRecovery(); 1662 break; 1663 1664 case EVENT_APN_CHANGED: 1665 onApnChanged(); 1666 break; 1667 1668 case EVENT_PS_RESTRICT_ENABLED: 1669 /** 1670 * We don't need to explicitly to tear down the PDP context 1671 * when PS restricted is enabled. The base band will deactive 1672 * PDP context and notify us with PDP_CONTEXT_CHANGED. 1673 * But we should stop the network polling and prevent reset PDP. 1674 */ 1675 Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted); 1676 stopNetStatPoll(); 1677 mIsPsRestricted = true; 1678 break; 1679 1680 case EVENT_PS_RESTRICT_DISABLED: 1681 /** 1682 * When PS restrict is removed, we need setup PDP connection if 1683 * PDP connection is down. 1684 */ 1685 Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted); 1686 mIsPsRestricted = false; 1687 if (state == State.CONNECTED) { 1688 startNetStatPoll(); 1689 } else { 1690 if (state == State.FAILED) { 1691 cleanUpConnection(false, Phone.REASON_PS_RESTRICT_ENABLED); 1692 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 1693 } 1694 trySetupData(Phone.REASON_PS_RESTRICT_ENABLED); 1695 } 1696 break; 1697 1698 default: 1699 // handle the message in the super class DataConnectionTracker 1700 super.handleMessage(msg); 1701 break; 1702 } 1703 } 1704 1705 protected void log(String s) { 1706 Log.d(LOG_TAG, "[GsmDataConnectionTracker] " + s); 1707 } 1708 1709} 1710