Merge "Introduced a common SOURCE_PACKAGE_FIELD in VoicemailContract class."
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 57f5967..d6f5643 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -23,6 +23,7 @@
 import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
 
+import com.android.internal.net.LegacyVpnInfo;
 import com.android.internal.net.VpnConfig;
 
 /**
@@ -105,5 +106,7 @@
 
     ParcelFileDescriptor establishVpn(in VpnConfig config);
 
-    void doLegacyVpn(in VpnConfig config, in String[] racoon, in String[] mtpd);
+    void startLegacyVpn(in VpnConfig config, in String[] racoon, in String[] mtpd);
+
+    LegacyVpnInfo getLegacyVpnInfo();
 }
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 9f632d1..2fda7de 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -1971,9 +1971,14 @@
     }
 
     /**
-     * Load the given data into the WebView using a 'data' scheme URL. Content
-     * loaded in this way does not have the ability to load content from the
-     * network.
+     * Load the given data into the WebView using a 'data' scheme URL.
+     * <p>
+     * Note that JavaScript's same origin policy means that script running in a
+     * page loaded using this method will be unable to access content loaded
+     * using any scheme other than 'data', including 'http(s)'. To avoid this
+     * restriction, use {@link
+     * #loadDataWithBaseURL(String,String,String,String,String)
+     * loadDataWithBaseURL()} with an appropriate base URL.
      * <p>
      * If the value of the encoding parameter is 'base64', then the data must
      * be encoded as base64. Otherwise, the data must use ASCII encoding for
@@ -2000,15 +2005,15 @@
     }
 
     /**
-     * Load the given data into the WebView, use the provided URL as the base
-     * URL for the content. The base URL is the URL that represents the page
-     * that is loaded through this interface. As such, it is used to resolve any
-     * relative URLs. The historyUrl is used for the history entry.
+     * Load the given data into the WebView, using baseUrl as the base URL for
+     * the content. The base URL is used both to resolve relative URLs and when
+     * applying JavaScript's same origin policy. The historyUrl is used for the
+     * history entry.
      * <p>
      * Note that content specified in this way can access local device files
      * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
      * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
-     * @param baseUrl Url to resolve relative paths with, if null defaults to
+     * @param baseUrl URL to use as the page's base URL. If null defaults to
      *            "about:blank"
      * @param data A String of data in the given encoding.
      * @param mimeType The MIMEType of the data. i.e. text/html. If null,
diff --git a/core/java/com/android/internal/net/LegacyVpnInfo.aidl b/core/java/com/android/internal/net/LegacyVpnInfo.aidl
new file mode 100644
index 0000000..0ca2627
--- /dev/null
+++ b/core/java/com/android/internal/net/LegacyVpnInfo.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.net;
+
+parcelable LegacyVpnInfo;
diff --git a/core/java/com/android/internal/net/LegacyVpnInfo.java b/core/java/com/android/internal/net/LegacyVpnInfo.java
new file mode 100644
index 0000000..b620abac
--- /dev/null
+++ b/core/java/com/android/internal/net/LegacyVpnInfo.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.net;
+
+import android.app.PendingIntent;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * A simple container used to carry information of the ongoing legacy VPN.
+ * Internal use only.
+ *
+ * @hide
+ */
+public class LegacyVpnInfo implements Parcelable {
+    public static final int STATE_DISCONNECTED = 0;
+    public static final int STATE_INITIALIZING = 1;
+    public static final int STATE_CONNECTING = 2;
+    public static final int STATE_CONNECTED = 3;
+    public static final int STATE_TIMEOUT = 4;
+    public static final int STATE_FAILED = 5;
+
+    public String key;
+    public int state = -1;
+    public PendingIntent intent;
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel out, int flags) {
+        out.writeString(key);
+        out.writeInt(state);
+        out.writeParcelable(intent, flags);
+    }
+
+    public static final Parcelable.Creator<LegacyVpnInfo> CREATOR =
+            new Parcelable.Creator<LegacyVpnInfo>() {
+        @Override
+        public LegacyVpnInfo createFromParcel(Parcel in) {
+            LegacyVpnInfo info = new LegacyVpnInfo();
+            info.key = in.readString();
+            info.state = in.readInt();
+            info.intent = in.readParcelable(null);
+            return info;
+        }
+
+        @Override
+        public LegacyVpnInfo[] newArray(int size) {
+            return new LegacyVpnInfo[size];
+        }
+    };
+}
diff --git a/core/java/com/android/internal/net/VpnConfig.java b/core/java/com/android/internal/net/VpnConfig.java
index 003c244..d36be10 100644
--- a/core/java/com/android/internal/net/VpnConfig.java
+++ b/core/java/com/android/internal/net/VpnConfig.java
@@ -21,7 +21,6 @@
 import android.content.Intent;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.SystemClock;
 
 import java.util.List;
 
@@ -43,14 +42,14 @@
         return intent;
     }
 
-    public static PendingIntent getIntentForNotification(Context context, VpnConfig config) {
-        config.startTime = SystemClock.elapsedRealtime();
+    public static PendingIntent getIntentForStatusPanel(Context context, VpnConfig config) {
         Intent intent = new Intent();
         intent.setClassName("com.android.vpndialogs", "com.android.vpndialogs.ManageDialog");
         intent.putExtra("config", config);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY |
                 Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
-        return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
+        return PendingIntent.getActivity(context, 0, intent, (config == null) ?
+                PendingIntent.FLAG_NO_CREATE : PendingIntent.FLAG_CANCEL_CURRENT);
     }
 
     public String packagz;
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index afc04bb..b98d2a2 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -64,6 +64,7 @@
 import android.util.Slog;
 import android.util.SparseIntArray;
 
+import com.android.internal.net.LegacyVpnInfo;
 import com.android.internal.net.VpnConfig;
 import com.android.internal.telephony.Phone;
 import com.android.server.connectivity.Tethering;
@@ -2469,8 +2470,8 @@
 
     /**
      * Protect a socket from VPN routing rules. This method is used by
-     * VpnBuilder and not available in ConnectivityManager. Permission
-     * checks are done in Vpn class.
+     * VpnBuilder and not available in ConnectivityManager. Permissions
+     * are checked in Vpn class.
      * @hide
      */
     @Override
@@ -2480,8 +2481,8 @@
 
     /**
      * Prepare for a VPN application. This method is used by VpnDialogs
-     * and not available in ConnectivityManager. Permission checks are
-     * done in Vpn class.
+     * and not available in ConnectivityManager. Permissions are checked
+     * in Vpn class.
      * @hide
      */
     @Override
@@ -2492,8 +2493,8 @@
     /**
      * Configure a TUN interface and return its file descriptor. Parameters
      * are encoded and opaque to this class. This method is used by VpnBuilder
-     * and not available in ConnectivityManager. Permission checks are done
-     * in Vpn class.
+     * and not available in ConnectivityManager. Permissions are checked in
+     * Vpn class.
      * @hide
      */
     @Override
@@ -2502,12 +2503,25 @@
     }
 
     /**
-     * Handle a legacy VPN request.
+     * Start legacy VPN and return an intent to VpnDialogs. This method is
+     * used by VpnSettings and not available in ConnectivityManager.
+     * Permissions are checked in Vpn class.
      * @hide
      */
     @Override
-    public void doLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
-        mVpn.doLegacyVpn(config, racoon, mtpd);
+    public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
+        mVpn.startLegacyVpn(config, racoon, mtpd);
+    }
+
+    /**
+     * Return the information of the ongoing legacy VPN. This method is used
+     * by VpnSettings and not available in ConnectivityManager. Permissions
+     * are checked in Vpn class.
+     * @hide
+     */
+    @Override
+    public LegacyVpnInfo getLegacyVpnInfo() {
+        return mVpn.getLegacyVpnInfo();
     }
 
     private String getDefaultInterface() {
diff --git a/services/java/com/android/server/InputMethodManagerService.java b/services/java/com/android/server/InputMethodManagerService.java
index 14abf80..2d55433 100644
--- a/services/java/com/android/server/InputMethodManagerService.java
+++ b/services/java/com/android/server/InputMethodManagerService.java
@@ -1623,8 +1623,11 @@
             if (lastImi == null) return null;
             try {
                 final int lastSubtypeHash = Integer.valueOf(lastIme.second);
-                return lastImi.getSubtypeAt(getSubtypeIdFromHashCode(
-                        lastImi, lastSubtypeHash));
+                final int lastSubtypeId = getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
+                if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
+                    return null;
+                }
+                return lastImi.getSubtypeAt(lastSubtypeId);
             } catch (NumberFormatException e) {
                 return null;
             }
diff --git a/services/java/com/android/server/connectivity/Vpn.java b/services/java/com/android/server/connectivity/Vpn.java
index bb3ce28..c185012 100644
--- a/services/java/com/android/server/connectivity/Vpn.java
+++ b/services/java/com/android/server/connectivity/Vpn.java
@@ -37,6 +37,7 @@
 import android.util.Log;
 
 import com.android.internal.R;
+import com.android.internal.net.LegacyVpnInfo;
 import com.android.internal.net.VpnConfig;
 import com.android.server.ConnectivityService.VpnCallback;
 
@@ -250,6 +251,7 @@
                     mContext.getString(R.string.vpn_title_long, label);
             String text = (config.session == null) ? mContext.getString(R.string.vpn_text) :
                     mContext.getString(R.string.vpn_text_long, config.session);
+            config.startTime = SystemClock.elapsedRealtime();
 
             long identity = Binder.clearCallingIdentity();
             Notification notification = new Notification.Builder(mContext)
@@ -257,7 +259,7 @@
                     .setLargeIcon(icon)
                     .setContentTitle(title)
                     .setContentText(text)
-                    .setContentIntent(VpnConfig.getIntentForNotification(mContext, config))
+                    .setContentIntent(VpnConfig.getIntentForStatusPanel(mContext, config))
                     .setDefaults(Notification.DEFAULT_ALL)
                     .setOngoing(true)
                     .getNotification();
@@ -284,24 +286,35 @@
     private native void jniProtect(int socket, String interfaze);
 
     /**
-     * Handle a legacy VPN request. This method stops the daemons and restart
-     * them if arguments are not null. Heavy things are offloaded to another
+     * Start legacy VPN. This method stops the daemons and restart them
+     * if arguments are not null. Heavy things are offloaded to another
      * thread, so callers will not be blocked for a long time.
      *
      * @param config The parameters to configure the network.
      * @param raoocn The arguments to be passed to racoon.
      * @param mtpd The arguments to be passed to mtpd.
      */
-    public synchronized void doLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
+    public synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
         // Prepare for the new request. This also checks the caller.
         prepare(null, VpnConfig.LEGACY_VPN);
 
-        // Start a new runner and we are done!
+        // Start a new LegacyVpnRunner and we are done!
         mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
         mLegacyVpnRunner.start();
     }
 
     /**
+     * Return the information of the current ongoing legacy VPN.
+     */
+    public synchronized LegacyVpnInfo getLegacyVpnInfo() {
+        // Only system user can call this method.
+        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
+            throw new SecurityException("Unauthorized Caller");
+        }
+        return (mLegacyVpnRunner == null) ? null : mLegacyVpnRunner.getInfo();
+    }
+
+    /**
      * Bringing up a VPN connection takes time, and that is all this thread
      * does. Here we have plenty of time. The only thing we need to take
      * care of is responding to interruptions as soon as possible. Otherwise
@@ -315,6 +328,8 @@
         private final VpnConfig mConfig;
         private final String[] mDaemons;
         private final String[][] mArguments;
+        private final LegacyVpnInfo mInfo;
+
         private long mTimer = -1;
 
         public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
@@ -322,7 +337,10 @@
             mConfig = config;
             mDaemons = new String[] {"racoon", "mtpd"};
             mArguments = new String[][] {racoon, mtpd};
+            mInfo = new LegacyVpnInfo();
 
+            // Legacy VPN is not a real package, so we use it to carry the key.
+            mInfo.key = mConfig.packagz;
             mConfig.packagz = VpnConfig.LEGACY_VPN;
         }
 
@@ -334,14 +352,22 @@
             interrupt();
         }
 
+        public LegacyVpnInfo getInfo() {
+            // Update the info when VPN is disconnected.
+            if (mInfo.state == LegacyVpnInfo.STATE_CONNECTED && mInterface == null) {
+                mInfo.state = LegacyVpnInfo.STATE_DISCONNECTED;
+                mInfo.intent = null;
+            }
+            return mInfo;
+        }
+
         @Override
         public void run() {
             // Wait for the previous thread since it has been interrupted.
-            Log.v(TAG, "wait");
+            Log.v(TAG, "Waiting");
             synchronized (TAG) {
-                Log.v(TAG, "begin");
+                Log.v(TAG, "Executing");
                 execute();
-                Log.v(TAG, "end");
             }
         }
 
@@ -353,7 +379,8 @@
             } else if (now - mTimer <= 30000) {
                 Thread.sleep(yield ? 200 : 1);
             } else {
-                throw new InterruptedException("time is up");
+                mInfo.state = LegacyVpnInfo.STATE_TIMEOUT;
+                throw new IllegalStateException("time is up");
             }
         }
 
@@ -362,6 +389,7 @@
             try {
                 // Initialize the timer.
                 checkpoint(false);
+                mInfo.state = LegacyVpnInfo.STATE_INITIALIZING;
 
                 // First stop the daemons.
                 for (String daemon : mDaemons) {
@@ -390,8 +418,10 @@
                     restart = restart || (arguments != null);
                 }
                 if (!restart) {
+                    mInfo.state = LegacyVpnInfo.STATE_DISCONNECTED;
                     return;
                 }
+                mInfo.state = LegacyVpnInfo.STATE_CONNECTING;
 
                 // Start the daemon with arguments.
                 for (int i = 0; i < mDaemons.length; ++i) {
@@ -459,7 +489,7 @@
                         String daemon = mDaemons[i];
                         if (mArguments[i] != null && !"running".equals(
                                 SystemProperties.get("init.svc." + daemon))) {
-                            throw new IllegalArgumentException(daemon + " is dead");
+                            throw new IllegalStateException(daemon + " is dead");
                         }
                     }
                     checkpoint(true);
@@ -492,11 +522,20 @@
                     mInterface = mConfig.interfaze;
                     mCallback.override(mConfig.dnsServers, mConfig.searchDomains);
                     showNotification(mConfig, null, null);
+
+                    Log.i(TAG, "Connected!");
+                    mInfo.state = LegacyVpnInfo.STATE_CONNECTED;
+                    mInfo.intent = VpnConfig.getIntentForStatusPanel(mContext, null);
                 }
-                Log.i(TAG, "Connected!");
             } catch (Exception e) {
-                Log.i(TAG, "Abort because " + e.getMessage());
+                Log.i(TAG, "Aborting", e);
                 exit();
+            } finally {
+                // Do not leave an unstable state.
+                if (mInfo.state == LegacyVpnInfo.STATE_INITIALIZING ||
+                        mInfo.state == LegacyVpnInfo.STATE_CONNECTING) {
+                    mInfo.state = LegacyVpnInfo.STATE_FAILED;
+                }
             }
         }
     }
diff --git a/voip/java/com/android/server/sip/SipService.java b/voip/java/com/android/server/sip/SipService.java
index ddc8031..c553947 100644
--- a/voip/java/com/android/server/sip/SipService.java
+++ b/voip/java/com/android/server/sip/SipService.java
@@ -74,6 +74,7 @@
     private static final int SHORT_EXPIRY_TIME = 10;
     private static final int MIN_EXPIRY_TIME = 60;
     private static final int DEFAULT_KEEPALIVE_INTERVAL = 10; // in seconds
+    private static final int DEFAULT_MAX_KEEPALIVE_INTERVAL = 120; // in seconds
 
     private Context mContext;
     private String mLocalIp;
@@ -101,6 +102,7 @@
     private boolean mWifiEnabled;
     private SipWakeLock mMyWakeLock;
     private int mKeepAliveInterval;
+    private int mLastGoodKeepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL;
 
     /**
      * Starts the SIP service. Do nothing if the SIP API is not supported on the
@@ -448,6 +450,7 @@
             if (connected) {
                 mLocalIp = determineLocalIp();
                 mKeepAliveInterval = -1;
+                mLastGoodKeepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL;
                 for (SipSessionGroupExt group : mSipGroups.values()) {
                     group.onConnectivityChanged(true);
                 }
@@ -471,7 +474,8 @@
 
     private void startPortMappingLifetimeMeasurement(
             SipProfile localProfile) {
-        startPortMappingLifetimeMeasurement(localProfile, -1);
+        startPortMappingLifetimeMeasurement(localProfile,
+                DEFAULT_MAX_KEEPALIVE_INTERVAL);
     }
 
     private void startPortMappingLifetimeMeasurement(
@@ -482,8 +486,16 @@
             Log.d(TAG, "start NAT port mapping timeout measurement on "
                     + localProfile.getUriString());
 
-            mIntervalMeasurementProcess =
-                    new IntervalMeasurementProcess(localProfile, maxInterval);
+            int minInterval = mLastGoodKeepAliveInterval;
+            if (minInterval >= maxInterval) {
+                // If mLastGoodKeepAliveInterval also does not work, reset it
+                // to the default min
+                minInterval = mLastGoodKeepAliveInterval
+                        = DEFAULT_KEEPALIVE_INTERVAL;
+                Log.d(TAG, "  reset min interval to " + minInterval);
+            }
+            mIntervalMeasurementProcess = new IntervalMeasurementProcess(
+                    localProfile, minInterval, maxInterval);
             mIntervalMeasurementProcess.start();
         }
     }
@@ -539,7 +551,7 @@
 
     private int getKeepAliveInterval() {
         return (mKeepAliveInterval < 0)
-                ? DEFAULT_KEEPALIVE_INTERVAL
+                ? mLastGoodKeepAliveInterval
                 : mKeepAliveInterval;
     }
 
@@ -768,27 +780,33 @@
     private class IntervalMeasurementProcess implements Runnable,
             SipSessionGroup.KeepAliveProcessCallback {
         private static final String TAG = "SipKeepAliveInterval";
-        private static final int MAX_INTERVAL = 120; // in seconds
         private static final int MIN_INTERVAL = 5; // in seconds
         private static final int PASS_THRESHOLD = 10;
         private static final int MAX_RETRY_COUNT = 5;
         private static final int NAT_MEASUREMENT_RETRY_INTERVAL = 120; // in seconds
         private SipSessionGroupExt mGroup;
         private SipSessionGroup.SipSessionImpl mSession;
-        private int mMinInterval = DEFAULT_KEEPALIVE_INTERVAL; // in seconds
+        private int mMinInterval;
         private int mMaxInterval;
         private int mInterval;
         private int mPassCount = 0;
 
-        public IntervalMeasurementProcess(SipProfile localProfile, int maxInterval) {
-            mMaxInterval = (maxInterval < 0) ? MAX_INTERVAL : maxInterval;
-            mInterval = (mMaxInterval + mMinInterval) / 2;
+        public IntervalMeasurementProcess(SipProfile localProfile,
+                int minInterval, int maxInterval) {
+            mMaxInterval = maxInterval;
+            mMinInterval = minInterval;
+            mInterval = (maxInterval + minInterval) / 2;
 
             // Don't start measurement if the interval is too small
-            if (mInterval < MIN_INTERVAL) {
+            if (mInterval < DEFAULT_KEEPALIVE_INTERVAL) {
                 Log.w(TAG, "interval is too small; measurement aborted; "
                         + "maxInterval=" + mMaxInterval);
                 return;
+            } else if (checkTermination()) {
+                Log.w(TAG, "interval is too small; measurement aborted; "
+                        + "interval=[" + mMinInterval + "," + mMaxInterval
+                        + "]");
+                return;
             }
 
             try {
@@ -842,6 +860,10 @@
             }
         }
 
+        private boolean checkTermination() {
+            return ((mMaxInterval - mMinInterval) < MIN_INTERVAL);
+        }
+
         // SipSessionGroup.KeepAliveProcessCallback
         @Override
         public void onResponse(boolean portChanged) {
@@ -850,6 +872,9 @@
                     if (++mPassCount != PASS_THRESHOLD) return;
                     // update the interval, since the current interval is good to
                     // keep the port mapping.
+                    if (mKeepAliveInterval > 0) {
+                        mLastGoodKeepAliveInterval = mKeepAliveInterval;
+                    }
                     mKeepAliveInterval = mMinInterval = mInterval;
                     if (DEBUG) {
                         Log.d(TAG, "measured good keepalive interval: "
@@ -860,9 +885,13 @@
                     // Since the rport is changed, shorten the interval.
                     mMaxInterval = mInterval;
                 }
-                if ((mMaxInterval - mMinInterval) < MIN_INTERVAL) {
+                if (checkTermination()) {
                     // update mKeepAliveInterval and stop measurement.
                     stop();
+                    // If all the measurements failed, we still set it to
+                    // mMinInterval; If mMinInterval still doesn't work, a new
+                    // measurement with min interval=DEFAULT_KEEPALIVE_INTERVAL
+                    // will be conducted.
                     mKeepAliveInterval = mMinInterval;
                     if (DEBUG) {
                         Log.d(TAG, "measured keepalive interval: "