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