GsmDataConnectionTracker.java revision bbf7c00e06c0f6f39e26f7fdedbc7105b2f5c415
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 setState(State.DISCONNECTING); 640 641 for (DataConnection conn : pdpList) { 642 PdpConnection pdp = (PdpConnection) conn; 643 if (tearDown) { 644 Message msg = obtainMessage(EVENT_DISCONNECT_DONE, reason); 645 pdp.disconnect(msg); 646 } else { 647 pdp.clearSettings(); 648 } 649 } 650 stopNetStatPoll(); 651 652 if (!tearDown) { 653 setState(State.IDLE); 654 phone.notifyDataConnection(reason); 655 mActiveApn = null; 656 } 657 } 658 659 /** 660 * @param types comma delimited list of APN types 661 * @return array of APN types 662 */ 663 private String[] parseTypes(String types) { 664 String[] result; 665 // If unset, set to DEFAULT. 666 if (types == null || types.equals("")) { 667 result = new String[1]; 668 result[0] = Phone.APN_TYPE_ALL; 669 } else { 670 result = types.split(","); 671 } 672 return result; 673 } 674 675 private ArrayList<ApnSetting> createApnList(Cursor cursor) { 676 ArrayList<ApnSetting> result = new ArrayList<ApnSetting>(); 677 if (cursor.moveToFirst()) { 678 do { 679 String[] types = parseTypes( 680 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE))); 681 ApnSetting apn = new ApnSetting( 682 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)), 683 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)), 684 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)), 685 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)), 686 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY)), 687 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)), 688 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC)), 689 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY)), 690 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)), 691 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)), 692 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)), 693 types); 694 result.add(apn); 695 } while (cursor.moveToNext()); 696 } 697 return result; 698 } 699 700 private PdpConnection findFreePdp() { 701 for (DataConnection conn : pdpList) { 702 PdpConnection pdp = (PdpConnection) conn; 703 if (pdp.getState() == DataConnection.State.INACTIVE) { 704 return pdp; 705 } 706 } 707 return null; 708 } 709 710 private boolean setupData(String reason) { 711 ApnSetting apn; 712 PdpConnection pdp; 713 714 apn = getNextApn(); 715 if (apn == null) return false; 716 pdp = findFreePdp(); 717 if (pdp == null) { 718 if (DBG) log("setupData: No free PdpConnection found!"); 719 return false; 720 } 721 mActiveApn = apn; 722 mActivePdp = pdp; 723 724 Message msg = obtainMessage(); 725 msg.what = EVENT_DATA_SETUP_COMPLETE; 726 msg.obj = reason; 727 pdp.connect(apn, msg); 728 729 setState(State.INITING); 730 phone.notifyDataConnection(reason); 731 return true; 732 } 733 734 String getInterfaceName(String apnType) { 735 if (mActivePdp != null 736 && (apnType == null || mActiveApn.canHandleType(apnType))) { 737 return mActivePdp.getInterface(); 738 } 739 return null; 740 } 741 742 protected String getIpAddress(String apnType) { 743 if (mActivePdp != null 744 && (apnType == null || mActiveApn.canHandleType(apnType))) { 745 return mActivePdp.getIpAddress(); 746 } 747 return null; 748 } 749 750 String getGateway(String apnType) { 751 if (mActivePdp != null 752 && (apnType == null || mActiveApn.canHandleType(apnType))) { 753 return mActivePdp.getGatewayAddress(); 754 } 755 return null; 756 } 757 758 protected String[] getDnsServers(String apnType) { 759 if (mActivePdp != null 760 && (apnType == null || mActiveApn.canHandleType(apnType))) { 761 return mActivePdp.getDnsServers(); 762 } 763 return null; 764 } 765 766 private boolean 767 pdpStatesHasCID (ArrayList<DataCallState> states, int cid) { 768 for (int i = 0, s = states.size() ; i < s ; i++) { 769 if (states.get(i).cid == cid) return true; 770 } 771 772 return false; 773 } 774 775 private boolean 776 pdpStatesHasActiveCID (ArrayList<DataCallState> states, int cid) { 777 for (int i = 0, s = states.size() ; i < s ; i++) { 778 if ((states.get(i).cid == cid) && (states.get(i).active != 0)) { 779 return true; 780 } 781 } 782 783 return false; 784 } 785 786 /** 787 * Handles changes to the APN database. 788 */ 789 private void onApnChanged() { 790 boolean isConnected; 791 792 isConnected = (state != State.IDLE && state != State.FAILED); 793 794 // The "current" may no longer be valid. MMS depends on this to send properly. 795 ((GSMPhone) phone).updateCurrentCarrierInProvider(); 796 797 // TODO: It'd be nice to only do this if the changed entrie(s) 798 // match the current operator. 799 createAllApnList(); 800 if (state != State.DISCONNECTING) { 801 cleanUpConnection(isConnected, Phone.REASON_APN_CHANGED); 802 if (!isConnected) { 803 // reset reconnect timer 804 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 805 trySetupData(Phone.REASON_APN_CHANGED); 806 } 807 } 808 } 809 810 /** 811 * @param explicitPoll if true, indicates that *we* polled for this 812 * update while state == CONNECTED rather than having it delivered 813 * via an unsolicited response (which could have happened at any 814 * previous state 815 */ 816 protected void onPdpStateChanged (AsyncResult ar, boolean explicitPoll) { 817 ArrayList<DataCallState> pdpStates; 818 819 pdpStates = (ArrayList<DataCallState>)(ar.result); 820 821 if (ar.exception != null) { 822 // This is probably "radio not available" or something 823 // of that sort. If so, the whole connection is going 824 // to come down soon anyway 825 return; 826 } 827 828 if (state == State.CONNECTED) { 829 // The way things are supposed to work, the PDP list 830 // should not contain the CID after it disconnects. 831 // However, the way things really work, sometimes the PDP 832 // context is still listed with active = false, which 833 // makes it hard to distinguish an activating context from 834 // an activated-and-then deactivated one. 835 if (!pdpStatesHasCID(pdpStates, cidActive)) { 836 // It looks like the PDP context has deactivated. 837 // Tear everything down and try to reconnect. 838 839 Log.i(LOG_TAG, "PDP connection has dropped. Reconnecting"); 840 841 // Add an event log when the network drops PDP 842 int cid = -1; 843 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 844 if (loc != null) cid = loc.getCid(); 845 EventLog.List val = new EventLog.List(cid, 846 TelephonyManager.getDefault().getNetworkType()); 847 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); 848 849 cleanUpConnection(true, null); 850 return; 851 } else if (!pdpStatesHasActiveCID(pdpStates, cidActive)) { 852 // Here, we only consider this authoritative if we asked for the 853 // PDP list. If it was an unsolicited response, we poll again 854 // to make sure everyone agrees on the initial state. 855 856 if (!explicitPoll) { 857 // We think it disconnected but aren't sure...poll from our side 858 phone.mCM.getPDPContextList( 859 this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 860 } else { 861 Log.i(LOG_TAG, "PDP connection has dropped (active=false case). " 862 + " Reconnecting"); 863 864 // Log the network drop on the event log. 865 int cid = -1; 866 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 867 if (loc != null) cid = loc.getCid(); 868 EventLog.List val = new EventLog.List(cid, 869 TelephonyManager.getDefault().getNetworkType()); 870 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_NETWORK_DROP, val); 871 872 cleanUpConnection(true, null); 873 } 874 } 875 } 876 } 877 878 private void notifyDefaultData(String reason) { 879 setupDnsProperties(); 880 setState(State.CONNECTED); 881 phone.notifyDataConnection(reason); 882 startNetStatPoll(); 883 // reset reconnect timer 884 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 885 } 886 887 private void setupDnsProperties() { 888 int mypid = android.os.Process.myPid(); 889 String[] servers = getDnsServers(null); 890 String propName; 891 String propVal; 892 int count; 893 894 count = 0; 895 for (int i = 0; i < servers.length; i++) { 896 String serverAddr = servers[i]; 897 if (!TextUtils.equals(serverAddr, "0.0.0.0")) { 898 SystemProperties.set("net.dns" + (i+1) + "." + mypid, serverAddr); 899 count++; 900 } 901 } 902 for (int i = count+1; i <= 4; i++) { 903 propName = "net.dns" + i + "." + mypid; 904 propVal = SystemProperties.get(propName); 905 if (propVal.length() != 0) { 906 SystemProperties.set(propName, ""); 907 } 908 } 909 /* 910 * Bump the property that tells the name resolver library 911 * to reread the DNS server list from the properties. 912 */ 913 propVal = SystemProperties.get("net.dnschange"); 914 if (propVal.length() != 0) { 915 try { 916 int n = Integer.parseInt(propVal); 917 SystemProperties.set("net.dnschange", "" + (n+1)); 918 } catch (NumberFormatException e) { 919 } 920 } 921 } 922 923 /** 924 * This is a kludge to deal with the fact that 925 * the PDP state change notification doesn't always work 926 * with certain RIL impl's/basebands 927 * 928 */ 929 private void startPeriodicPdpPoll() { 930 removeMessages(EVENT_POLL_PDP); 931 932 sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS); 933 } 934 935 private void resetPollStats() { 936 txPkts = -1; 937 rxPkts = -1; 938 sentSinceLastRecv = 0; 939 netStatPollPeriod = POLL_NETSTAT_MILLIS; 940 mNoRecvPollCount = 0; 941 } 942 943 private void doRecovery() { 944 if (state == State.CONNECTED) { 945 int maxPdpReset = Settings.Gservices.getInt(mResolver, 946 Settings.Gservices.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT, 947 DEFAULT_MAX_PDP_RESET_FAIL); 948 if (mPdpResetCount < maxPdpReset) { 949 mPdpResetCount++; 950 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, sentSinceLastRecv); 951 cleanUpConnection(true, Phone.REASON_PDP_RESET); 952 } else { 953 mPdpResetCount = 0; 954 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_REREGISTER_NETWORK, sentSinceLastRecv); 955 ((GSMPhone) phone).mSST.reRegisterNetwork(null); 956 } 957 // TODO: Add increasingly drastic recovery steps, eg, 958 // reset the radio, reset the device. 959 } 960 } 961 962 protected void startNetStatPoll() { 963 if (state == State.CONNECTED && mPingTestActive == false && netStatPollEnabled == false) { 964 Log.d(LOG_TAG, "[DataConnection] Start poll NetStat"); 965 resetPollStats(); 966 netStatPollEnabled = true; 967 mPollNetStat.run(); 968 } 969 } 970 971 protected void stopNetStatPoll() { 972 netStatPollEnabled = false; 973 removeCallbacks(mPollNetStat); 974 Log.d(LOG_TAG, "[DataConnection] Stop poll NetStat"); 975 } 976 977 protected void restartRadio() { 978 Log.d(LOG_TAG, "************TURN OFF RADIO**************"); 979 cleanUpConnection(true, Phone.REASON_RADIO_TURNED_OFF); 980 phone.mCM.setRadioPower(false, null); 981 /* Note: no need to call setRadioPower(true). Assuming the desired 982 * radio power state is still ON (as tracked by ServiceStateTracker), 983 * ServiceStateTracker will call setRadioPower when it receives the 984 * RADIO_STATE_CHANGED notification for the power off. And if the 985 * desired power state has changed in the interim, we don't want to 986 * override it with an unconditional power on. 987 */ 988 989 int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0")); 990 SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1)); 991 } 992 993 private Runnable mPollNetStat = new Runnable() 994 { 995 996 public void run() { 997 long sent, received; 998 long preTxPkts = -1, preRxPkts = -1; 999 1000 Activity newActivity; 1001 1002 preTxPkts = txPkts; 1003 preRxPkts = rxPkts; 1004 1005 try { 1006 txPkts = netstat.getMobileTxPackets(); 1007 rxPkts = netstat.getMobileRxPackets(); 1008 } catch (RemoteException e) { 1009 txPkts = 0; 1010 rxPkts = 0; 1011 } 1012 1013 //Log.d(LOG_TAG, "rx " + String.valueOf(rxPkts) + " tx " + String.valueOf(txPkts)); 1014 1015 if (netStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) { 1016 sent = txPkts - preTxPkts; 1017 received = rxPkts - preRxPkts; 1018 1019 if ( sent > 0 && received > 0 ) { 1020 sentSinceLastRecv = 0; 1021 newActivity = Activity.DATAINANDOUT; 1022 mPdpResetCount = 0; 1023 } else if (sent > 0 && received == 0) { 1024 if (phone.getState() == Phone.State.IDLE) { 1025 sentSinceLastRecv += sent; 1026 } else { 1027 sentSinceLastRecv = 0; 1028 } 1029 newActivity = Activity.DATAOUT; 1030 } else if (sent == 0 && received > 0) { 1031 sentSinceLastRecv = 0; 1032 newActivity = Activity.DATAIN; 1033 mPdpResetCount = 0; 1034 } else if (sent == 0 && received == 0) { 1035 newActivity = Activity.NONE; 1036 } else { 1037 sentSinceLastRecv = 0; 1038 newActivity = Activity.NONE; 1039 } 1040 1041 if (activity != newActivity && mIsScreenOn) { 1042 activity = newActivity; 1043 phone.notifyDataActivity(); 1044 } 1045 } 1046 1047 int watchdogTrigger = Settings.Gservices.getInt(mResolver, 1048 Settings.Gservices.PDP_WATCHDOG_TRIGGER_PACKET_COUNT, 1049 NUMBER_SENT_PACKETS_OF_HANG); 1050 1051 if (sentSinceLastRecv >= watchdogTrigger) { 1052 // we already have NUMBER_SENT_PACKETS sent without ack 1053 if (mNoRecvPollCount == 0) { 1054 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_RESET_COUNTDOWN_TRIGGERED, 1055 sentSinceLastRecv); 1056 } 1057 1058 int noRecvPollLimit = Settings.Gservices.getInt(mResolver, 1059 Settings.Gservices.PDP_WATCHDOG_ERROR_POLL_COUNT, NO_RECV_POLL_LIMIT); 1060 1061 if (mNoRecvPollCount < noRecvPollLimit) { 1062 // It's possible the PDP context went down and we weren't notified. 1063 // Start polling the context list in an attempt to recover. 1064 if (DBG) log("no DATAIN in a while; polling PDP"); 1065 phone.mCM.getDataCallList(obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 1066 1067 mNoRecvPollCount++; 1068 1069 // Slow down the poll interval to let things happen 1070 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1071 Settings.Gservices.PDP_WATCHDOG_ERROR_POLL_INTERVAL_MS, 1072 POLL_NETSTAT_SLOW_MILLIS); 1073 } else { 1074 if (DBG) log("Sent " + String.valueOf(sentSinceLastRecv) + 1075 " pkts since last received"); 1076 // We've exceeded the threshold. Run ping test as a final check; 1077 // it will proceed with recovery if ping fails. 1078 stopNetStatPoll(); 1079 Thread pingTest = new Thread() { 1080 public void run() { 1081 runPingTest(); 1082 } 1083 }; 1084 mPingTestActive = true; 1085 pingTest.start(); 1086 } 1087 } else { 1088 mNoRecvPollCount = 0; 1089 if (mIsScreenOn) { 1090 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1091 Settings.Gservices.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS); 1092 } else { 1093 netStatPollPeriod = Settings.Gservices.getInt(mResolver, 1094 Settings.Gservices.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS, 1095 POLL_NETSTAT_SCREEN_OFF_MILLIS); 1096 } 1097 } 1098 1099 if (netStatPollEnabled) { 1100 mDataConnectionTracker.postDelayed(this, netStatPollPeriod); 1101 } 1102 } 1103 }; 1104 1105 private void runPingTest () { 1106 int status = -1; 1107 try { 1108 String address = Settings.Gservices.getString(mResolver, 1109 Settings.Gservices.PDP_WATCHDOG_PING_ADDRESS); 1110 int deadline = Settings.Gservices.getInt(mResolver, 1111 Settings.Gservices.PDP_WATCHDOG_PING_DEADLINE, DEFAULT_PING_DEADLINE); 1112 if (DBG) log("pinging " + address + " for " + deadline + "s"); 1113 if (address != null && !NULL_IP.equals(address)) { 1114 Process p = Runtime.getRuntime() 1115 .exec("ping -c 1 -i 1 -w "+ deadline + " " + address); 1116 status = p.waitFor(); 1117 } 1118 } catch (IOException e) { 1119 Log.w(LOG_TAG, "ping failed: IOException"); 1120 } catch (Exception e) { 1121 Log.w(LOG_TAG, "exception trying to ping"); 1122 } 1123 1124 if (status == 0) { 1125 // ping succeeded. False alarm. Reset netStatPoll. 1126 // ("-1" for this event indicates a false alarm) 1127 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_PDP_RESET, -1); 1128 mPdpResetCount = 0; 1129 sendMessage(obtainMessage(EVENT_START_NETSTAT_POLL)); 1130 } else { 1131 // ping failed. Proceed with recovery. 1132 sendMessage(obtainMessage(EVENT_START_RECOVERY)); 1133 } 1134 } 1135 1136 /** 1137 * Returns true if the last fail cause is something that 1138 * seems like it deserves an error notification. 1139 * Transient errors are ignored 1140 */ 1141 private boolean shouldPostNotification(PdpConnection.FailCause cause) { 1142 boolean shouldPost = true; 1143 // TODO CHECK 1144 // if (dataLink != null) { 1145 // shouldPost = dataLink.getLastLinkExitCode() != DataLink.EXIT_OPEN_FAILED; 1146 //} 1147 return (shouldPost && cause != PdpConnection.FailCause.UNKNOWN); 1148 } 1149 1150 /** 1151 * Return true if data connection need to be setup after disconnected due to 1152 * reason. 1153 * 1154 * @param reason the reason why data is disconnected 1155 * @return true if try setup data connection is need for this reason 1156 */ 1157 private boolean retryAfterDisconnected(String reason) { 1158 boolean retry = true; 1159 1160 if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) || 1161 Phone.REASON_DATA_DISABLED.equals(reason) ) { 1162 retry = false; 1163 } 1164 return retry; 1165 } 1166 1167 private void reconnectAfterFail(FailCause lastFailCauseCode, String reason) { 1168 if (state == State.FAILED) { 1169 Log.d(LOG_TAG, "PDP activate failed. Scheduling next attempt for " 1170 + (nextReconnectDelay / 1000) + "s"); 1171 1172 AlarmManager am = 1173 (AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE); 1174 Intent intent = new Intent(INTENT_RECONNECT_ALARM); 1175 intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON, reason); 1176 mReconnectIntent = PendingIntent.getBroadcast( 1177 phone.getContext(), 0, intent, 0); 1178 am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1179 SystemClock.elapsedRealtime() + nextReconnectDelay, 1180 mReconnectIntent); 1181 1182 // double it for next time 1183 nextReconnectDelay *= 2; 1184 if (nextReconnectDelay > RECONNECT_DELAY_MAX_MILLIS) { 1185 nextReconnectDelay = RECONNECT_DELAY_MAX_MILLIS; 1186 } 1187 1188 if (!shouldPostNotification(lastFailCauseCode)) { 1189 Log.d(LOG_TAG,"NOT Posting GPRS Unavailable notification " 1190 + "-- likely transient error"); 1191 } else { 1192 notifyNoData(lastFailCauseCode); 1193 } 1194 } 1195 } 1196 1197 private void notifyNoData(PdpConnection.FailCause lastFailCauseCode) { 1198 setState(State.FAILED); 1199 } 1200 1201 protected void onRecordsLoaded() { 1202 createAllApnList(); 1203 if (state == State.FAILED) { 1204 cleanUpConnection(false, null); 1205 } 1206 sendMessage(obtainMessage(EVENT_TRY_SETUP_DATA, Phone.REASON_SIM_LOADED)); 1207 } 1208 1209 protected void onEnableNewApn() { 1210 // TODO: To support simultaneous PDP contexts, this should really only call 1211 // cleanUpConnection if it needs to free up a PdpConnection. 1212 cleanUpConnection(true, Phone.REASON_APN_SWITCHED); 1213 } 1214 1215 protected void onTrySetupData(String reason) { 1216 trySetupData(reason); 1217 } 1218 1219 protected void onRestoreDefaultApn() { 1220 if (DBG) Log.d(LOG_TAG, "Restore default APN"); 1221 setEnabled(Phone.APN_TYPE_MMS, false); 1222 1223 if (!isApnTypeActive(Phone.APN_TYPE_DEFAULT)) { 1224 cleanUpConnection(true, Phone.REASON_RESTORE_DEFAULT_APN); 1225 mRequestedApnType = Phone.APN_TYPE_DEFAULT; 1226 } 1227 } 1228 1229 protected void onRoamingOff() { 1230 trySetupData(Phone.REASON_ROAMING_OFF); 1231 } 1232 1233 protected void onRoamingOn() { 1234 if (getDataOnRoamingEnabled()) { 1235 trySetupData(Phone.REASON_ROAMING_ON); 1236 } else { 1237 if (DBG) log("Tear down data connection on roaming."); 1238 cleanUpConnection(true, Phone.REASON_ROAMING_ON); 1239 } 1240 } 1241 1242 protected void onRadioAvailable() { 1243 if (phone.getSimulatedRadioControl() != null) { 1244 // Assume data is connected on the simulator 1245 // FIXME this can be improved 1246 setState(State.CONNECTED); 1247 phone.notifyDataConnection(null); 1248 1249 Log.i(LOG_TAG, "We're on the simulator; assuming data is connected"); 1250 } 1251 1252 if (state != State.IDLE) { 1253 cleanUpConnection(true, null); 1254 } 1255 } 1256 1257 protected void onRadioOffOrNotAvailable() { 1258 // Make sure our reconnect delay starts at the initial value 1259 // next time the radio comes on 1260 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 1261 1262 if (phone.getSimulatedRadioControl() != null) { 1263 // Assume data is connected on the simulator 1264 // FIXME this can be improved 1265 Log.i(LOG_TAG, "We're on the simulator; assuming radio off is meaningless"); 1266 } else { 1267 if (DBG) log("Radio is off and clean up all connection"); 1268 // TODO: Should we reset mRequestedApnType to "default"? 1269 cleanUpConnection(false, Phone.REASON_RADIO_TURNED_OFF); 1270 } 1271 } 1272 1273 protected void onDataSetupComplete(AsyncResult ar) { 1274 String reason = null; 1275 if (ar.userObj instanceof String) { 1276 reason = (String) ar.userObj; 1277 } 1278 1279 if (ar.exception == null) { 1280 // everything is setup 1281 1282 /* 1283 * We may have switched away from the default PDP context 1284 * in order to enable a "special" APN (e.g., for MMS 1285 * traffic). Set a timer to switch back and/or disable the 1286 * special APN, so that a negligient application doesn't 1287 * permanently prevent data connectivity. What we are 1288 * protecting against here is not malicious apps, but 1289 * rather an app that inadvertantly fails to reset to the 1290 * default APN, or that dies before doing so. 1291 */ 1292 if (dataEnabled[APN_MMS_ID] || dataEnabled[APN_SUPL_ID]) { 1293 removeMessages(EVENT_RESTORE_DEFAULT_APN); 1294 sendMessageDelayed(obtainMessage(EVENT_RESTORE_DEFAULT_APN), 1295 getRestoreDefaultApnDelay()); 1296 } 1297 if (isApnTypeActive(Phone.APN_TYPE_DEFAULT)) { 1298 SystemProperties.set("gsm.defaultpdpcontext.active", "true"); 1299 if (canSetPreferApn && preferredApn == null) { 1300 Log.d(LOG_TAG, "PREFERED APN is null"); 1301 preferredApn = mActiveApn; 1302 setPreferredApn(preferredApn.id); 1303 } 1304 } else { 1305 SystemProperties.set("gsm.defaultpdpcontext.active", "false"); 1306 } 1307 notifyDefaultData(reason); 1308 1309 // TODO: For simultaneous PDP support, we need to build another 1310 // trigger another TRY_SETUP_DATA for the next APN type. (Note 1311 // that the existing connection may service that type, in which 1312 // case we should try the next type, etc. 1313 } else { 1314 PdpConnection.FailCause cause; 1315 cause = (PdpConnection.FailCause) (ar.result); 1316 if(DBG) log("PDP setup failed " + cause); 1317 // Log this failure to the Event Logs. 1318 if (cause == PdpConnection.FailCause.BAD_APN || 1319 cause == PdpConnection.FailCause.BAD_PAP_SECRET || 1320 cause == PdpConnection.FailCause.BARRED || 1321 cause == PdpConnection.FailCause.RADIO_ERROR_RETRY || 1322 cause == PdpConnection.FailCause.SUSPENED_TEMPORARY || 1323 cause == PdpConnection.FailCause.UNKNOWN || 1324 cause == PdpConnection.FailCause.USER_AUTHENTICATION) { 1325 int cid = -1; 1326 GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation()); 1327 if (loc != null) cid = loc.getCid(); 1328 1329 EventLog.List val = new EventLog.List( 1330 cause.ordinal(), cid, 1331 TelephonyManager.getDefault().getNetworkType()); 1332 EventLog.writeEvent(TelephonyEventLog.EVENT_LOG_RADIO_PDP_SETUP_FAIL, val); 1333 } 1334 1335 // No try for permanent failure 1336 if (cause.isPermanentFail()) { 1337 notifyNoData(cause); 1338 } 1339 1340 if (tryNextApn(cause)) { 1341 waitingApns.remove(0); 1342 if (waitingApns.isEmpty()) { 1343 // No more to try, start delayed retry 1344 startDelayedRetry(cause, reason); 1345 } else { 1346 // we still have more apns to try 1347 setState(State.SCANNING); 1348 // Wait a bit before trying the next APN, so that 1349 // we're not tying up the RIL command channel 1350 sendMessageDelayed(obtainMessage(EVENT_TRY_SETUP_DATA, reason), 1351 RECONNECT_DELAY_INITIAL_MILLIS); 1352 } 1353 } else { 1354 startDelayedRetry(cause, reason); 1355 } 1356 } 1357 } 1358 1359 protected void onDisconnectDone(AsyncResult ar) { 1360 String reason = null; 1361 if(DBG) log("EVENT_DISCONNECT_DONE"); 1362 if (ar.userObj instanceof String) { 1363 reason = (String) ar.userObj; 1364 } 1365 setState(State.IDLE); 1366 phone.notifyDataConnection(reason); 1367 mActiveApn = null; 1368 if (retryAfterDisconnected(reason)) { 1369 trySetupData(reason); 1370 } 1371 } 1372 1373 protected void onPollPdp() { 1374 if (state == State.CONNECTED) { 1375 // only poll when connected 1376 phone.mCM.getPDPContextList(this.obtainMessage(EVENT_GET_PDP_LIST_COMPLETE)); 1377 sendMessageDelayed(obtainMessage(EVENT_POLL_PDP), POLL_PDP_MILLIS); 1378 } 1379 } 1380 1381 protected void onVoiceCallStarted() { 1382 if (state == State.CONNECTED && !((GSMPhone) phone).mSST.isConcurrentVoiceAndData()) { 1383 stopNetStatPoll(); 1384 phone.notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED); 1385 } 1386 } 1387 1388 protected void onVoiceCallEnded() { 1389 if (state == State.CONNECTED) { 1390 if (!((GSMPhone) phone).mSST.isConcurrentVoiceAndData()) { 1391 startNetStatPoll(); 1392 phone.notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED); 1393 } else { 1394 // clean slate after call end. 1395 resetPollStats(); 1396 } 1397 } else { 1398 // reset reconnect timer 1399 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 1400 // in case data setup was attempted when we were on a voice call 1401 trySetupData(Phone.REASON_VOICE_CALL_ENDED); 1402 } 1403 } 1404 1405 protected void onCleanUpConnection(boolean tearDown, String reason) { 1406 cleanUpConnection(tearDown, reason); 1407 } 1408 1409 private boolean tryNextApn(FailCause cause) { 1410 return (cause != FailCause.RADIO_NOT_AVAILABLE) 1411 && (cause != FailCause.RADIO_OFF) 1412 && (cause != FailCause.RADIO_ERROR_RETRY) 1413 && (cause != FailCause.NO_SIGNAL) 1414 && (cause != FailCause.SIM_LOCKED); 1415 } 1416 1417 private int getRestoreDefaultApnDelay() { 1418 String restoreApnDelayStr = SystemProperties.get(APN_RESTORE_DELAY_PROP_NAME); 1419 1420 if (restoreApnDelayStr != null && restoreApnDelayStr.length() != 0) { 1421 try { 1422 return Integer.valueOf(restoreApnDelayStr); 1423 } catch (NumberFormatException e) { 1424 } 1425 } 1426 return RESTORE_DEFAULT_APN_DELAY; 1427 } 1428 1429 /** 1430 * Based on the sim operator numeric, create a list for all possible pdps 1431 * with all apns associated with that pdp 1432 * 1433 * 1434 */ 1435 private void createAllApnList() { 1436 allApns = new ArrayList<ApnSetting>(); 1437 String operator = ((GSMPhone) phone).mSIMRecords.getSIMOperatorNumeric(); 1438 1439 if (operator != null) { 1440 String selection = "numeric = '" + operator + "'"; 1441 1442 Cursor cursor = phone.getContext().getContentResolver().query( 1443 Telephony.Carriers.CONTENT_URI, null, selection, null, null); 1444 1445 if (cursor != null) { 1446 if (cursor.getCount() > 0) { 1447 allApns = createApnList(cursor); 1448 // TODO: Figure out where this fits in. This basically just 1449 // writes the pap-secrets file. No longer tied to PdpConnection 1450 // object. Not used on current platform (no ppp). 1451 //PdpConnection pdp = pdpList.get(pdp_name); 1452 //if (pdp != null && pdp.dataLink != null) { 1453 // pdp.dataLink.setPasswordInfo(cursor); 1454 //} 1455 } 1456 cursor.close(); 1457 } 1458 } 1459 1460 if (allApns.isEmpty()) { 1461 if (DBG) log("No APN found for carrier: " + operator); 1462 preferredApn = null; 1463 notifyNoData(PdpConnection.FailCause.BAD_APN); 1464 } else { 1465 preferredApn = getPreferredApn(); 1466 Log.d(LOG_TAG, "Get PreferredAPN"); 1467 if (preferredApn != null && !preferredApn.numeric.equals(operator)) { 1468 preferredApn = null; 1469 setPreferredApn(-1); 1470 } 1471 } 1472 } 1473 1474 private void createAllPdpList() { 1475 pdpList = new ArrayList<DataConnection>(); 1476 DataConnection pdp; 1477 1478 for (int i = 0; i < PDP_CONNECTION_POOL_SIZE; i++) { 1479 pdp = new PdpConnection((GSMPhone) phone); 1480 pdpList.add(pdp); 1481 } 1482 } 1483 1484 private void destroyAllPdpList() { 1485 if(pdpList != null) { 1486 PdpConnection pdp; 1487 pdpList.removeAll(pdpList); 1488 } 1489 } 1490 1491 /** 1492 * 1493 * @return waitingApns list to be used to create PDP 1494 * error when waitingApns.isEmpty() 1495 */ 1496 private ArrayList<ApnSetting> buildWaitingApns() { 1497 ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>(); 1498 String operator = ((GSMPhone )phone).mSIMRecords.getSIMOperatorNumeric(); 1499 1500 if (mRequestedApnType.equals(Phone.APN_TYPE_DEFAULT)) { 1501 if (canSetPreferApn && preferredApn != null) { 1502 Log.i(LOG_TAG, "Preferred APN:" + operator + ":" 1503 + preferredApn.numeric + ":" + preferredApn); 1504 if (preferredApn.numeric.equals(operator)) { 1505 Log.i(LOG_TAG, "Waiting APN set to preferred APN"); 1506 apnList.add(preferredApn); 1507 return apnList; 1508 } else { 1509 setPreferredApn(-1); 1510 preferredApn = null; 1511 } 1512 } 1513 } 1514 1515 if (allApns != null) { 1516 for (ApnSetting apn : allApns) { 1517 if (apn.canHandleType(mRequestedApnType)) { 1518 apnList.add(apn); 1519 } 1520 } 1521 } 1522 return apnList; 1523 } 1524 1525 /** 1526 * Get next apn in waitingApns 1527 * @return the first apn found in waitingApns, null if none 1528 */ 1529 private ApnSetting getNextApn() { 1530 ArrayList<ApnSetting> list = waitingApns; 1531 ApnSetting apn = null; 1532 1533 if (list != null) { 1534 if (!list.isEmpty()) { 1535 apn = list.get(0); 1536 } 1537 } 1538 return apn; 1539 } 1540 1541 private String apnListToString (ArrayList<ApnSetting> apns) { 1542 StringBuilder result = new StringBuilder(); 1543 for (int i = 0, size = apns.size(); i < size; i++) { 1544 result.append('[') 1545 .append(apns.get(i).toString()) 1546 .append(']'); 1547 } 1548 return result.toString(); 1549 } 1550 1551 private void startDelayedRetry(PdpConnection.FailCause cause, String reason) { 1552 notifyNoData(cause); 1553 if (mRequestedApnType != Phone.APN_TYPE_DEFAULT) { 1554 sendMessage(obtainMessage(EVENT_RESTORE_DEFAULT_APN)); 1555 } 1556 else { 1557 reconnectAfterFail(cause, reason); 1558 } 1559 } 1560 1561 private void setPreferredApn(int pos) { 1562 if (!canSetPreferApn) { 1563 return; 1564 } 1565 1566 ContentResolver resolver = phone.getContext().getContentResolver(); 1567 resolver.delete(PREFERAPN_URI, null, null); 1568 1569 if (pos >= 0) { 1570 ContentValues values = new ContentValues(); 1571 values.put(APN_ID, pos); 1572 resolver.insert(PREFERAPN_URI, values); 1573 } 1574 } 1575 1576 private ApnSetting getPreferredApn() { 1577 if (allApns.isEmpty()) { 1578 return null; 1579 } 1580 1581 Cursor cursor = phone.getContext().getContentResolver().query( 1582 PREFERAPN_URI, new String[] { "_id", "name", "apn" }, 1583 null, null, Telephony.Carriers.DEFAULT_SORT_ORDER); 1584 1585 if (cursor != null) { 1586 canSetPreferApn = true; 1587 } else { 1588 canSetPreferApn = false; 1589 } 1590 1591 if (canSetPreferApn && cursor.getCount() > 0) { 1592 int pos; 1593 cursor.moveToFirst(); 1594 pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)); 1595 for(ApnSetting p:allApns) { 1596 if (p.id == pos && p.canHandleType(mRequestedApnType)) { 1597 cursor.close(); 1598 return p; 1599 } 1600 } 1601 } 1602 1603 if (cursor != null) { 1604 cursor.close(); 1605 } 1606 1607 return null; 1608 } 1609 1610 public void handleMessage (Message msg) { 1611 1612 switch (msg.what) { 1613 case EVENT_RECORDS_LOADED: 1614 onRecordsLoaded(); 1615 break; 1616 1617 case EVENT_ENABLE_NEW_APN: 1618 onEnableNewApn(); 1619 break; 1620 1621 case EVENT_RESTORE_DEFAULT_APN: 1622 onRestoreDefaultApn(); 1623 break; 1624 1625 case EVENT_GPRS_DETACHED: 1626 onGprsDetached(); 1627 break; 1628 1629 case EVENT_GPRS_ATTACHED: 1630 onGprsAttached(); 1631 break; 1632 1633 case EVENT_DATA_STATE_CHANGED: 1634 onPdpStateChanged((AsyncResult) msg.obj, false); 1635 break; 1636 1637 case EVENT_GET_PDP_LIST_COMPLETE: 1638 onPdpStateChanged((AsyncResult) msg.obj, true); 1639 break; 1640 1641 case EVENT_POLL_PDP: 1642 onPollPdp(); 1643 break; 1644 1645 case EVENT_START_NETSTAT_POLL: 1646 mPingTestActive = false; 1647 startNetStatPoll(); 1648 break; 1649 1650 case EVENT_START_RECOVERY: 1651 mPingTestActive = false; 1652 doRecovery(); 1653 break; 1654 1655 case EVENT_APN_CHANGED: 1656 onApnChanged(); 1657 break; 1658 1659 case EVENT_PS_RESTRICT_ENABLED: 1660 /** 1661 * We don't need to explicitly to tear down the PDP context 1662 * when PS restricted is enabled. The base band will deactive 1663 * PDP context and notify us with PDP_CONTEXT_CHANGED. 1664 * But we should stop the network polling and prevent reset PDP. 1665 */ 1666 Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted); 1667 stopNetStatPoll(); 1668 mIsPsRestricted = true; 1669 break; 1670 1671 case EVENT_PS_RESTRICT_DISABLED: 1672 /** 1673 * When PS restrict is removed, we need setup PDP connection if 1674 * PDP connection is down. 1675 */ 1676 Log.d(LOG_TAG, "[DSAC DEB] " + "EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted); 1677 mIsPsRestricted = false; 1678 if (state == State.CONNECTED) { 1679 startNetStatPoll(); 1680 } else { 1681 if (state == State.FAILED) { 1682 cleanUpConnection(false, Phone.REASON_PS_RESTRICT_ENABLED); 1683 nextReconnectDelay = RECONNECT_DELAY_INITIAL_MILLIS; 1684 } 1685 trySetupData(Phone.REASON_PS_RESTRICT_ENABLED); 1686 } 1687 break; 1688 1689 default: 1690 // handle the message in the super class DataConnectionTracker 1691 super.handleMessage(msg); 1692 break; 1693 } 1694 } 1695 1696 protected void log(String s) { 1697 Log.d(LOG_TAG, "[GsmDataConnectionTracker] " + s); 1698 } 1699 1700} 1701