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