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