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