1 /*
2  * Copyright (C) 2017 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 android.telephony;
18 
19 import static com.android.internal.util.Preconditions.checkNotNull;
20 
21 import android.content.Context;
22 import android.os.Binder;
23 import android.os.Bundle;
24 import android.os.Handler;
25 import android.os.HandlerThread;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.os.Messenger;
29 import android.os.Parcelable;
30 import android.os.RemoteException;
31 import android.os.ServiceManager;
32 import android.util.SparseArray;
33 
34 import com.android.internal.annotations.GuardedBy;
35 import com.android.internal.telephony.ITelephony;
36 import com.android.telephony.Rlog;
37 
38 import java.util.Arrays;
39 import java.util.List;
40 import java.util.concurrent.Executor;
41 
42 /**
43  * Manages the radio access network scan requests and callbacks.
44  */
45 public final class TelephonyScanManager {
46 
47     private static final String TAG = "TelephonyScanManager";
48 
49     /** @hide */
50     public static final String SCAN_RESULT_KEY = "scanResult";
51 
52     /** @hide */
53     public static final int CALLBACK_SCAN_RESULTS = 1;
54     /** @hide */
55     public static final int CALLBACK_SCAN_ERROR = 2;
56     /** @hide */
57     public static final int CALLBACK_SCAN_COMPLETE = 3;
58     /** @hide */
59     public static final int CALLBACK_RESTRICTED_SCAN_RESULTS = 4;
60     /** @hide */
61     public static final int CALLBACK_TELEPHONY_DIED = 5;
62 
63     /** @hide */
64     public static final int INVALID_SCAN_ID = -1;
65 
66     /**
67      * The caller of
68      * {@link
69      * TelephonyManager#requestNetworkScan(NetworkScanRequest, Executor, NetworkScanCallback)}
70      * should implement and provide this callback so that the scan results or errors can be
71      * returned.
72      */
73     public static abstract class NetworkScanCallback {
74         /** Returns the scan results to the user, this callback will be called multiple times. */
onResults(List<CellInfo> results)75         public void onResults(List<CellInfo> results) {}
76 
77         /**
78          * Informs the user that the scan has stopped.
79          *
80          * This callback will be called when the scan is finished or cancelled by the user.
81          * The related NetworkScanRequest will be deleted after this callback.
82          */
onComplete()83         public void onComplete() {}
84 
85         /**
86          * Informs the user that there is some error about the scan.
87          *
88          * This callback will be called whenever there is any error about the scan, and the scan
89          * will be terminated. onComplete() will NOT be called.
90          *
91          * @param error Error code when the scan is failed, as defined in {@link NetworkScan}.
92          */
onError(@etworkScan.ScanErrorCode int error)93         public void onError(@NetworkScan.ScanErrorCode int error) {}
94     }
95 
96     private static class NetworkScanInfo {
97         private final NetworkScanRequest mRequest;
98         private final Executor mExecutor;
99         private final NetworkScanCallback mCallback;
100 
NetworkScanInfo( NetworkScanRequest request, Executor executor, NetworkScanCallback callback)101         NetworkScanInfo(
102                 NetworkScanRequest request, Executor executor, NetworkScanCallback callback) {
103             mRequest = request;
104             mExecutor = executor;
105             mCallback = callback;
106         }
107     }
108 
109     private final Looper mLooper;
110     private final Handler mHandler;
111     private final Messenger mMessenger;
112     private final SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>();
113     private final Binder.DeathRecipient mDeathRecipient;
114 
TelephonyScanManager()115     public TelephonyScanManager() {
116         HandlerThread thread = new HandlerThread(TAG);
117         thread.start();
118         mLooper = thread.getLooper();
119         mHandler = new Handler(mLooper) {
120             @Override
121             public void handleMessage(Message message) {
122                 checkNotNull(message, "message cannot be null");
123                 if (message.what == CALLBACK_TELEPHONY_DIED) {
124                     // If there are no objects in mScanInfo then binder death will simply return.
125                     synchronized (mScanInfo) {
126                         for (int i = 0; i < mScanInfo.size(); i++) {
127                             NetworkScanInfo nsi = mScanInfo.valueAt(i);
128                             // At this point we go into panic mode and ignore errors that would
129                             // normally stop the show in order to try and clean up as gracefully
130                             // as possible.
131                             if (nsi == null) continue; // shouldn't be possible
132                             Executor e = nsi.mExecutor;
133                             NetworkScanCallback cb = nsi.mCallback;
134                             if (e == null || cb == null) continue;
135                             try {
136                                 e.execute(
137                                         () -> cb.onError(NetworkScan.ERROR_MODEM_UNAVAILABLE));
138                             } catch (java.util.concurrent.RejectedExecutionException ignore) {
139                                 // ignore so that we can continue
140                             }
141                         }
142 
143                         mScanInfo.clear();
144                     }
145                     return;
146                 }
147 
148                 NetworkScanInfo nsi;
149                 synchronized (mScanInfo) {
150                     nsi = mScanInfo.get(message.arg2);
151                 }
152                 if (nsi == null) {
153                     throw new RuntimeException(
154                         "Failed to find NetworkScanInfo with id " + message.arg2);
155                 }
156                 NetworkScanCallback callback = nsi.mCallback;
157                 Executor executor = nsi.mExecutor;
158                 if (callback == null) {
159                     throw new RuntimeException(
160                         "Failed to find NetworkScanCallback with id " + message.arg2);
161                 }
162                 if (executor == null) {
163                     throw new RuntimeException(
164                         "Failed to find Executor with id " + message.arg2);
165                 }
166 
167                 switch (message.what) {
168                     case CALLBACK_RESTRICTED_SCAN_RESULTS:
169                     case CALLBACK_SCAN_RESULTS:
170                         try {
171                             final Bundle b = message.getData();
172                             final Parcelable[] parcelables = b.getParcelableArray(SCAN_RESULT_KEY);
173                             CellInfo[] ci = new CellInfo[parcelables.length];
174                             for (int i = 0; i < parcelables.length; i++) {
175                                 ci[i] = (CellInfo) parcelables[i];
176                             }
177                             executor.execute(() -> {
178                                 Rlog.d(TAG, "onResults: " + ci.toString());
179                                 callback.onResults(Arrays.asList(ci));
180                             });
181                         } catch (Exception e) {
182                             Rlog.e(TAG, "Exception in networkscan callback onResults", e);
183                         }
184                         break;
185                     case CALLBACK_SCAN_ERROR:
186                         try {
187                             final int errorCode = message.arg1;
188                             executor.execute(() -> {
189                                 Rlog.d(TAG, "onError: " + errorCode);
190                                 callback.onError(errorCode);
191                             });
192                             synchronized (mScanInfo) {
193                                 mScanInfo.remove(message.arg2);
194                             }
195                         } catch (Exception e) {
196                             Rlog.e(TAG, "Exception in networkscan callback onError", e);
197                         }
198                         break;
199                     case CALLBACK_SCAN_COMPLETE:
200                         try {
201                             executor.execute(() -> {
202                                 Rlog.d(TAG, "onComplete");
203                                 callback.onComplete();
204                             });
205                             synchronized (mScanInfo) {
206                                 mScanInfo.remove(message.arg2);
207                             }
208                         } catch (Exception e) {
209                             Rlog.e(TAG, "Exception in networkscan callback onComplete", e);
210                         }
211                         break;
212                     default:
213                         Rlog.e(TAG, "Unhandled message " + Integer.toHexString(message.what));
214                         break;
215                 }
216             }
217         };
218         mMessenger = new Messenger(mHandler);
219         mDeathRecipient = new Binder.DeathRecipient() {
220             @Override
221             public void binderDied() {
222                 mHandler.obtainMessage(CALLBACK_TELEPHONY_DIED).sendToTarget();
223             }
224         };
225     }
226 
227     /**
228      * Request a network scan.
229      *
230      * This method is asynchronous, so the network scan results will be returned by callback.
231      * The returned NetworkScan will contain a callback method which can be used to stop the scan.
232      *
233      * <p>
234      * Requires Permission:
235      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
236      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
237      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
238      *
239      * @param request Contains all the RAT with bands/channels that need to be scanned.
240      * @param callback Returns network scan results or errors.
241      * @return A NetworkScan obj which contains a callback which can stop the scan.
242      * @hide
243      */
requestNetworkScan(int subId, NetworkScanRequest request, Executor executor, NetworkScanCallback callback, String callingPackage, String callingFeatureId)244     public NetworkScan requestNetworkScan(int subId,
245             NetworkScanRequest request, Executor executor, NetworkScanCallback callback,
246             String callingPackage, String callingFeatureId) {
247         try {
248             final ITelephony telephony = getITelephony();
249             if (telephony == null) return null;
250 
251             int scanId = telephony.requestNetworkScan(
252                     subId, request, mMessenger, new Binder(), callingPackage,
253                     callingFeatureId);
254             if (scanId == INVALID_SCAN_ID) {
255                 Rlog.e(TAG, "Failed to initiate network scan");
256                 return null;
257             }
258             synchronized (mScanInfo) {
259                 // We link to death whenever a scan is started to ensure that we are linked
260                 // at the point that phone process death might matter.
261                 // We never unlink because:
262                 // - Duplicate links to death with the same callback do not result in
263                 //   extraneous callbacks (the tracking de-dupes).
264                 // - Receiving binderDeath() when no scans are active is a no-op.
265                 telephony.asBinder().linkToDeath(mDeathRecipient, 0);
266                 saveScanInfo(scanId, request, executor, callback);
267                 return new NetworkScan(scanId, subId);
268             }
269         } catch (RemoteException ex) {
270             Rlog.e(TAG, "requestNetworkScan RemoteException", ex);
271         } catch (NullPointerException ex) {
272             Rlog.e(TAG, "requestNetworkScan NPE", ex);
273         }
274         return null;
275     }
276 
277     @GuardedBy("mScanInfo")
saveScanInfo( int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback)278     private void saveScanInfo(
279             int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback) {
280         mScanInfo.put(id, new NetworkScanInfo(request, executor, callback));
281     }
282 
getITelephony()283     private ITelephony getITelephony() {
284         return ITelephony.Stub.asInterface(
285             ServiceManager.getService(Context.TELEPHONY_SERVICE));
286     }
287 }
288