NewOutgoingCallIntentBroadcaster.java revision 11623a354be47205bf3bc686ed8fdfc278958983
1/*
2 * Copyright (C) 2014 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.server.telecom;
18
19import android.app.AppOpsManager;
20
21import android.app.Activity;
22import android.content.BroadcastReceiver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.res.Resources;
26import android.net.Uri;
27import android.os.Trace;
28import android.os.UserHandle;
29import android.telecom.GatewayInfo;
30import android.telecom.PhoneAccount;
31import android.telecom.TelecomManager;
32import android.telecom.VideoProfile;
33import android.telephony.DisconnectCause;
34import android.telephony.PhoneNumberUtils;
35import android.text.TextUtils;
36
37// TODO: Needed for move to system service: import com.android.internal.R;
38
39/**
40 * OutgoingCallIntentBroadcaster receives CALL and CALL_PRIVILEGED Intents, and broadcasts the
41 * ACTION_NEW_OUTGOING_CALL intent. ACTION_NEW_OUTGOING_CALL is an ordered broadcast intent which
42 * contains the phone number being dialed. Applications can use this intent to (1) see which numbers
43 * are being dialed, (2) redirect a call (change the number being dialed), or (3) prevent a call
44 * from being placed.
45 *
46 * After the other applications have had a chance to see the ACTION_NEW_OUTGOING_CALL intent, it
47 * finally reaches the {@link NewOutgoingCallBroadcastIntentReceiver}.
48 *
49 * Calls where no number is present (like for a CDMA "empty flash" or a nonexistent voicemail
50 * number) are exempt from being broadcast.
51 *
52 * Calls to emergency numbers are still broadcast for informative purposes. The call is placed
53 * prior to sending ACTION_NEW_OUTGOING_CALL and cannot be redirected nor prevented.
54 */
55class NewOutgoingCallIntentBroadcaster {
56    private static final String EXTRA_ACTUAL_NUMBER_TO_DIAL =
57            "android.telecom.extra.ACTUAL_NUMBER_TO_DIAL";
58
59    /**
60     * Legacy string constants used to retrieve gateway provider extras from intents. These still
61     * need to be copied from the source call intent to the destination intent in order to
62     * support third party gateway providers that are still using old string constants in
63     * Telephony.
64     */
65    public static final String EXTRA_GATEWAY_PROVIDER_PACKAGE =
66            "com.android.phone.extra.GATEWAY_PROVIDER_PACKAGE";
67    public static final String EXTRA_GATEWAY_URI = "com.android.phone.extra.GATEWAY_URI";
68    public static final String EXTRA_GATEWAY_ORIGINAL_URI =
69            "com.android.phone.extra.GATEWAY_ORIGINAL_URI";
70
71    private final CallsManager mCallsManager;
72    private final Call mCall;
73    private final Intent mIntent;
74    private final Context mContext;
75
76    /*
77     * Whether or not the outgoing call intent originated from the default phone application. If
78     * so, it will be allowed to make emergency calls, even with the ACTION_CALL intent.
79     */
80    private final boolean mIsDefaultOrSystemPhoneApp;
81
82    NewOutgoingCallIntentBroadcaster(Context context, CallsManager callsManager, Call call,
83            Intent intent, boolean isDefaultPhoneApp) {
84        mContext = context;
85        mCallsManager = callsManager;
86        mCall = call;
87        mIntent = intent;
88        mIsDefaultOrSystemPhoneApp = isDefaultPhoneApp;
89    }
90
91    /**
92     * Processes the result of the outgoing call broadcast intent, and performs callbacks to
93     * the OutgoingCallIntentBroadcasterListener as necessary.
94     */
95    private class NewOutgoingCallBroadcastIntentReceiver extends BroadcastReceiver {
96
97        @Override
98        public void onReceive(Context context, Intent intent) {
99            try {
100                Log.startSession("NOCBIR.oR");
101                Trace.beginSection("onReceiveNewOutgoingCallBroadcast");
102                Log.v(this, "onReceive: %s", intent);
103
104                // Once the NEW_OUTGOING_CALL broadcast is finished, the resultData is used as the
105                // actual number to call. (If null, no call will be placed.)
106                String resultNumber = getResultData();
107                Log.i(this, "Received new-outgoing-call-broadcast for %s with data %s", mCall,
108                        Log.pii(resultNumber));
109
110                boolean endEarly = false;
111                if (resultNumber == null) {
112                    Log.v(this, "Call cancelled (null number), returning...");
113                    endEarly = true;
114                } else if (PhoneNumberUtils.isPotentialLocalEmergencyNumber(
115                        mContext, resultNumber)) {
116                    Log.w(this, "Cannot modify outgoing call to emergency number %s.",
117                            resultNumber);
118                    endEarly = true;
119                }
120
121                if (endEarly) {
122                    if (mCall != null) {
123                        mCall.disconnect(true /* wasViaNewOutgoingCall */);
124                    }
125                    return;
126                }
127
128                Uri resultHandleUri = Uri.fromParts(PhoneNumberUtils.isUriNumber(resultNumber) ?
129                        PhoneAccount.SCHEME_SIP : PhoneAccount.SCHEME_TEL, resultNumber, null);
130
131                Uri originalUri = mIntent.getData();
132
133                if (originalUri.getSchemeSpecificPart().equals(resultNumber)) {
134                    Log.v(this, "Call number unmodified after new outgoing call intent broadcast.");
135                } else {
136                    Log.v(this, "Retrieved modified handle after outgoing call intent broadcast: "
137                                    + "Original: %s, Modified: %s",
138                            Log.pii(originalUri),
139                            Log.pii(resultHandleUri));
140                }
141
142                GatewayInfo gatewayInfo = getGateWayInfoFromIntent(intent, resultHandleUri);
143                mCallsManager.placeOutgoingCall(mCall, resultHandleUri, gatewayInfo,
144                        mIntent.getBooleanExtra(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE,
145                                false),
146                        mIntent.getIntExtra(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE,
147                                VideoProfile.STATE_AUDIO_ONLY));
148
149            } finally {
150                Trace.endSection();
151                Log.endSession();
152            }
153        }
154    }
155
156    /**
157     * Processes the supplied intent and starts the outgoing call broadcast process relevant to the
158     * intent.
159     *
160     * This method will handle three kinds of actions:
161     *
162     * - CALL (intent launched by all third party dialers)
163     * - CALL_PRIVILEGED (intent launched by system apps e.g. system Dialer, voice Dialer)
164     * - CALL_EMERGENCY (intent launched by lock screen emergency dialer)
165     *
166     * @return {@link DisconnectCause#NOT_DISCONNECTED} if the call succeeded, and an appropriate
167     *         {@link DisconnectCause} if the call did not, describing why it failed.
168     */
169    int processIntent() {
170        Log.v(this, "Processing call intent in OutgoingCallIntentBroadcaster.");
171
172        Intent intent = mIntent;
173        String action = intent.getAction();
174        final Uri handle = intent.getData();
175
176        if (handle == null) {
177            Log.w(this, "Empty handle obtained from the call intent.");
178            return DisconnectCause.INVALID_NUMBER;
179        }
180
181        boolean isVoicemailNumber = PhoneAccount.SCHEME_VOICEMAIL.equals(handle.getScheme());
182        if (isVoicemailNumber) {
183            if (Intent.ACTION_CALL.equals(action)
184                    || Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
185                // Voicemail calls will be handled directly by the telephony connection manager
186                Log.i(this, "Placing call immediately instead of waiting for "
187                        + " OutgoingCallBroadcastReceiver: %s", intent);
188
189                boolean speakerphoneOn = mIntent.getBooleanExtra(
190                        TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false);
191                mCallsManager.placeOutgoingCall(mCall, handle, null, speakerphoneOn,
192                        VideoProfile.STATE_AUDIO_ONLY);
193
194                return DisconnectCause.NOT_DISCONNECTED;
195            } else {
196                Log.i(this, "Unhandled intent %s. Ignoring and not placing call.", intent);
197                return DisconnectCause.OUTGOING_CANCELED;
198            }
199        }
200
201        String number = PhoneNumberUtils.getNumberFromIntent(intent, mContext);
202        if (TextUtils.isEmpty(number)) {
203            Log.w(this, "Empty number obtained from the call intent.");
204            return DisconnectCause.NO_PHONE_NUMBER_SUPPLIED;
205        }
206
207        boolean isUriNumber = PhoneNumberUtils.isUriNumber(number);
208        if (!isUriNumber) {
209            number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
210            number = PhoneNumberUtils.stripSeparators(number);
211        }
212
213        final boolean isPotentialEmergencyNumber = isPotentialEmergencyNumber(number);
214        Log.v(this, "isPotentialEmergencyNumber = %s", isPotentialEmergencyNumber);
215
216        rewriteCallIntentAction(intent, isPotentialEmergencyNumber);
217        action = intent.getAction();
218        // True for certain types of numbers that are not intended to be intercepted or modified
219        // by third parties (e.g. emergency numbers).
220        boolean callImmediately = false;
221
222        if (Intent.ACTION_CALL.equals(action)) {
223            if (isPotentialEmergencyNumber) {
224                if (!mIsDefaultOrSystemPhoneApp) {
225                    Log.w(this, "Cannot call potential emergency number %s with CALL Intent %s "
226                            + "unless caller is system or default dialer.", number, intent);
227                    launchSystemDialer(intent.getData());
228                    return DisconnectCause.OUTGOING_CANCELED;
229                } else {
230                    callImmediately = true;
231                }
232            }
233        } else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) {
234            if (!isPotentialEmergencyNumber) {
235                Log.w(this, "Cannot call non-potential-emergency number %s with EMERGENCY_CALL "
236                        + "Intent %s.", number, intent);
237                return DisconnectCause.OUTGOING_CANCELED;
238            }
239            callImmediately = true;
240        } else {
241            Log.w(this, "Unhandled Intent %s. Ignoring and not placing call.", intent);
242            return DisconnectCause.INVALID_NUMBER;
243        }
244
245        if (callImmediately) {
246            Log.i(this, "Placing call immediately instead of waiting for "
247                    + " OutgoingCallBroadcastReceiver: %s", intent);
248            String scheme = isUriNumber ? PhoneAccount.SCHEME_SIP : PhoneAccount.SCHEME_TEL;
249            boolean speakerphoneOn = mIntent.getBooleanExtra(
250                    TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false);
251            int videoState = mIntent.getIntExtra(
252                    TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE,
253                    VideoProfile.STATE_AUDIO_ONLY);
254            mCallsManager.placeOutgoingCall(mCall, Uri.fromParts(scheme, number, null), null,
255                    speakerphoneOn, videoState);
256
257            // Don't return but instead continue and send the ACTION_NEW_OUTGOING_CALL broadcast
258            // so that third parties can still inspect (but not intercept) the outgoing call. When
259            // the broadcast finally reaches the OutgoingCallBroadcastReceiver, we'll know not to
260            // initiate the call again because of the presence of the EXTRA_ALREADY_CALLED extra.
261        }
262
263        Log.i(this, "Sending NewOutgoingCallBroadcast for %s", mCall);
264        broadcastIntent(intent, number, !callImmediately);
265        return DisconnectCause.NOT_DISCONNECTED;
266    }
267
268    /**
269     * Sends a new outgoing call ordered broadcast so that third party apps can cancel the
270     * placement of the call or redirect it to a different number.
271     *
272     * @param originalCallIntent The original call intent.
273     * @param number Call number that was stored in the original call intent.
274     * @param receiverRequired Whether or not the result from the ordered broadcast should be
275     *     processed using a {@link NewOutgoingCallIntentBroadcaster}.
276     */
277    private void broadcastIntent(
278            Intent originalCallIntent,
279            String number,
280            boolean receiverRequired) {
281        Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
282        if (number != null) {
283            broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
284        }
285
286        // Force receivers of this broadcast intent to run at foreground priority because we
287        // want to finish processing the broadcast intent as soon as possible.
288        broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
289        Log.v(this, "Broadcasting intent: %s.", broadcastIntent);
290
291        checkAndCopyProviderExtras(originalCallIntent, broadcastIntent);
292
293        mContext.sendOrderedBroadcastAsUser(
294                broadcastIntent,
295                UserHandle.CURRENT,
296                android.Manifest.permission.PROCESS_OUTGOING_CALLS,
297                AppOpsManager.OP_PROCESS_OUTGOING_CALLS,
298                receiverRequired ? new NewOutgoingCallBroadcastIntentReceiver() : null,
299                null,  // scheduler
300                Activity.RESULT_OK,  // initialCode
301                number,  // initialData: initial value for the result data (number to be modified)
302                null);  // initialExtras
303    }
304
305    /**
306     * Copy all the expected extras set when a 3rd party gateway provider is to be used, from the
307     * source intent to the destination one.
308     *
309     * @param src Intent which may contain the provider's extras.
310     * @param dst Intent where a copy of the extras will be added if applicable.
311     */
312    public void checkAndCopyProviderExtras(Intent src, Intent dst) {
313        if (src == null) {
314            return;
315        }
316        if (hasGatewayProviderExtras(src)) {
317            dst.putExtra(EXTRA_GATEWAY_PROVIDER_PACKAGE,
318                    src.getStringExtra(EXTRA_GATEWAY_PROVIDER_PACKAGE));
319            dst.putExtra(EXTRA_GATEWAY_URI,
320                    src.getStringExtra(EXTRA_GATEWAY_URI));
321            Log.d(this, "Found and copied gateway provider extras to broadcast intent.");
322            return;
323        }
324
325        Log.d(this, "No provider extras found in call intent.");
326    }
327
328    /**
329     * Check if valid gateway provider information is stored as extras in the intent
330     *
331     * @param intent to check for
332     * @return true if the intent has all the gateway information extras needed.
333     */
334    private boolean hasGatewayProviderExtras(Intent intent) {
335        final String name = intent.getStringExtra(EXTRA_GATEWAY_PROVIDER_PACKAGE);
336        final String uriString = intent.getStringExtra(EXTRA_GATEWAY_URI);
337
338        return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(uriString);
339    }
340
341    private static Uri getGatewayUriFromString(String gatewayUriString) {
342        return TextUtils.isEmpty(gatewayUriString) ? null : Uri.parse(gatewayUriString);
343    }
344
345    /**
346     * Extracts gateway provider information from a provided intent..
347     *
348     * @param intent to extract gateway provider information from.
349     * @param trueHandle The actual call handle that the user is trying to dial
350     * @return GatewayInfo object containing extracted gateway provider information as well as
351     *     the actual handle the user is trying to dial.
352     */
353    public static GatewayInfo getGateWayInfoFromIntent(Intent intent, Uri trueHandle) {
354        if (intent == null) {
355            return null;
356        }
357
358        // Check if gateway extras are present.
359        String gatewayPackageName = intent.getStringExtra(EXTRA_GATEWAY_PROVIDER_PACKAGE);
360        Uri gatewayUri = getGatewayUriFromString(intent.getStringExtra(EXTRA_GATEWAY_URI));
361        if (!TextUtils.isEmpty(gatewayPackageName) && gatewayUri != null) {
362            return new GatewayInfo(gatewayPackageName, gatewayUri, trueHandle);
363        }
364
365        return null;
366    }
367
368    private void launchSystemDialer(Uri handle) {
369        Intent systemDialerIntent = new Intent();
370        final Resources resources = mContext.getResources();
371        systemDialerIntent.setClassName(
372                resources.getString(R.string.ui_default_package),
373                resources.getString(R.string.dialer_default_class));
374        systemDialerIntent.setAction(Intent.ACTION_DIAL);
375        systemDialerIntent.setData(handle);
376        systemDialerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
377        Log.v(this, "calling startActivity for default dialer: %s", systemDialerIntent);
378        mContext.startActivityAsUser(systemDialerIntent, UserHandle.CURRENT);
379    }
380
381    /**
382     * Check whether or not this is an emergency number, in order to enforce the restriction
383     * that only the CALL_PRIVILEGED and CALL_EMERGENCY intents are allowed to make emergency
384     * calls.
385     *
386     * To prevent malicious 3rd party apps from making emergency calls by passing in an
387     * "invalid" number like "9111234" (that isn't technically an emergency number but might
388     * still result in an emergency call with some networks), we use
389     * isPotentialLocalEmergencyNumber instead of isLocalEmergencyNumber.
390     *
391     * @param number number to inspect in order to determine whether or not an emergency number
392     * is potentially being dialed
393     * @return True if the handle is potentially an emergency number.
394     */
395    private boolean isPotentialEmergencyNumber(String number) {
396        Log.v(this, "Checking restrictions for number : %s", Log.pii(number));
397        return (number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(mContext,
398                number);
399    }
400
401    /**
402     * Given a call intent and whether or not the number to dial is an emergency number, rewrite
403     * the call intent action to an appropriate one.
404     *
405     * @param intent Intent to rewrite the action for
406     * @param isPotentialEmergencyNumber Whether or not the number is potentially an emergency
407     * number.
408     */
409    private void rewriteCallIntentAction(Intent intent, boolean isPotentialEmergencyNumber) {
410        String action = intent.getAction();
411
412        /* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */
413        if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
414            if (isPotentialEmergencyNumber) {
415                Log.i(this, "ACTION_CALL_PRIVILEGED is used while the number is a potential"
416                        + " emergency number. Using ACTION_CALL_EMERGENCY as an action instead.");
417                action = Intent.ACTION_CALL_EMERGENCY;
418            } else {
419                action = Intent.ACTION_CALL;
420            }
421            Log.v(this, " - updating action from CALL_PRIVILEGED to %s", action);
422            intent.setAction(action);
423        }
424    }
425}
426