1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import android.Manifest;
import android.app.AppOpsManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.service.carrier.CarrierMessagingService;
import android.telephony.TelephonyManager;
import android.util.Slog;
import com.android.internal.telephony.IMms;
import java.util.List;
/**
* This class is a proxy for MmsService APIs. We need this because MmsService runs
* in phone process and may crash anytime. This manages a connection to the actual
* MmsService and bridges the public SMS/MMS APIs with MmsService implementation.
*/
public class MmsServiceBroker extends SystemService {
private static final String TAG = "MmsServiceBroker";
private static final ComponentName MMS_SERVICE_COMPONENT =
new ComponentName("com.android.mms.service", "com.android.mms.service.MmsService");
private static final int MSG_TRY_CONNECTING = 1;
private static final Uri FAKE_SMS_SENT_URI = Uri.parse("content://sms/sent/0");
private static final Uri FAKE_MMS_SENT_URI = Uri.parse("content://mms/sent/0");
private static final Uri FAKE_SMS_DRAFT_URI = Uri.parse("content://sms/draft/0");
private static final Uri FAKE_MMS_DRAFT_URI = Uri.parse("content://mms/draft/0");
private static final long SERVICE_CONNECTION_WAIT_TIME_MS = 4 * 1000L; // 4 seconds
private static final long RETRY_DELAY_ON_DISCONNECTION_MS = 3 * 1000L; // 3 seconds
private Context mContext;
// The actual MMS service instance to invoke
private volatile IMms mService;
// Cached system service instances
private volatile AppOpsManager mAppOpsManager = null;
private volatile PackageManager mPackageManager = null;
private volatile TelephonyManager mTelephonyManager = null;
private final Handler mConnectionHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_TRY_CONNECTING:
tryConnecting();
break;
default:
Slog.e(TAG, "Unknown message");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Slog.i(TAG, "MmsService connected");
synchronized (MmsServiceBroker.this) {
mService = IMms.Stub.asInterface(service);
MmsServiceBroker.this.notifyAll();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Slog.i(TAG, "MmsService unexpectedly disconnected");
synchronized (MmsServiceBroker.this) {
mService = null;
MmsServiceBroker.this.notifyAll();
}
// Retry connecting, but not too eager (with a delay)
// since it may come back by itself.
mConnectionHandler.sendMessageDelayed(
mConnectionHandler.obtainMessage(MSG_TRY_CONNECTING),
RETRY_DELAY_ON_DISCONNECTION_MS);
}
};
public MmsServiceBroker(Context context) {
super(context);
mContext = context;
mService = null;
}
@Override
public void onStart() {
publishBinderService("imms", new BinderService());
}
public void systemRunning() {
Slog.i(TAG, "Delay connecting to MmsService until an API is called");
}
private void tryConnecting() {
Slog.i(TAG, "Connecting to MmsService");
synchronized (this) {
if (mService != null) {
Slog.d(TAG, "Already connected");
return;
}
final Intent intent = new Intent();
intent.setComponent(MMS_SERVICE_COMPONENT);
try {
if (!mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)) {
Slog.e(TAG, "Failed to bind to MmsService");
}
} catch (SecurityException e) {
Slog.e(TAG, "Forbidden to bind to MmsService", e);
}
}
}
private void ensureService() {
synchronized (this) {
if (mService == null) {
// Service is not connected. Try blocking connecting.
Slog.w(TAG, "MmsService not connected. Try connecting...");
mConnectionHandler.sendMessage(
mConnectionHandler.obtainMessage(MSG_TRY_CONNECTING));
final long shouldEnd =
SystemClock.elapsedRealtime() + SERVICE_CONNECTION_WAIT_TIME_MS;
long waitTime = SERVICE_CONNECTION_WAIT_TIME_MS;
while (waitTime > 0) {
try {
// TODO: consider using Java concurrent construct instead of raw object wait
this.wait(waitTime);
} catch (InterruptedException e) {
Slog.w(TAG, "Connection wait interrupted", e);
}
if (mService != null) {
// Success
return;
}
// Calculate remaining waiting time to make sure we wait the full timeout period
waitTime = shouldEnd - SystemClock.elapsedRealtime();
}
// Timed out. Something's really wrong.
Slog.e(TAG, "Can not connect to MmsService (timed out)");
throw new RuntimeException("Timed out in connecting to MmsService");
}
}
}
/**
* Making sure when we obtain the mService instance it is always valid.
* Throws {@link RuntimeException} when it is empty.
*/
private IMms getServiceGuarded() {
ensureService();
return mService;
}
private AppOpsManager getAppOpsManager() {
if (mAppOpsManager == null) {
mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
}
return mAppOpsManager;
}
private PackageManager getPackageManager() {
if (mPackageManager == null) {
mPackageManager = mContext.getPackageManager();
}
return mPackageManager;
}
private TelephonyManager getTelephonyManager() {
if (mTelephonyManager == null) {
mTelephonyManager = (TelephonyManager) mContext.getSystemService(
Context.TELEPHONY_SERVICE);
}
return mTelephonyManager;
}
private String getCallingPackageName() {
final String[] packages = getPackageManager().getPackagesForUid(Binder.getCallingUid());
if (packages != null && packages.length > 0) {
return packages[0];
}
return "unknown";
}
// Service API calls implementation, proxied to the real MmsService in "com.android.mms.service"
private final class BinderService extends IMms.Stub {
private static final String PHONE_PACKAGE_NAME = "com.android.phone";
@Override
public void sendMessage(int subId, String callingPkg, Uri contentUri,
String locationUrl, Bundle configOverrides, PendingIntent sentIntent)
throws RemoteException {
Slog.d(TAG, "sendMessage() by " + callingPkg);
mContext.enforceCallingPermission(Manifest.permission.SEND_SMS, "Send MMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_SEND_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return;
}
contentUri = adjustUriForUserAndGrantPermission(contentUri,
CarrierMessagingService.SERVICE_INTERFACE,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
getServiceGuarded().sendMessage(subId, callingPkg, contentUri, locationUrl,
configOverrides, sentIntent);
}
@Override
public void downloadMessage(int subId, String callingPkg, String locationUrl,
Uri contentUri, Bundle configOverrides,
PendingIntent downloadedIntent) throws RemoteException {
Slog.d(TAG, "downloadMessage() by " + callingPkg);
mContext.enforceCallingPermission(Manifest.permission.RECEIVE_MMS,
"Download MMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_RECEIVE_MMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return;
}
contentUri = adjustUriForUserAndGrantPermission(contentUri,
CarrierMessagingService.SERVICE_INTERFACE,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getServiceGuarded().downloadMessage(subId, callingPkg, locationUrl, contentUri,
configOverrides, downloadedIntent);
}
@Override
public Bundle getCarrierConfigValues(int subId) throws RemoteException {
Slog.d(TAG, "getCarrierConfigValues() by " + getCallingPackageName());
return getServiceGuarded().getCarrierConfigValues(subId);
}
@Override
public Uri importTextMessage(String callingPkg, String address, int type, String text,
long timestampMillis, boolean seen, boolean read) throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Import SMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
// Silently fail AppOps failure due to not being the default SMS app
// while writing the TelephonyProvider
return FAKE_SMS_SENT_URI;
}
return getServiceGuarded().importTextMessage(
callingPkg, address, type, text, timestampMillis, seen, read);
}
@Override
public Uri importMultimediaMessage(String callingPkg, Uri contentUri,
String messageId, long timestampSecs, boolean seen, boolean read)
throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Import MMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
// Silently fail AppOps failure due to not being the default SMS app
// while writing the TelephonyProvider
return FAKE_MMS_SENT_URI;
}
return getServiceGuarded().importMultimediaMessage(
callingPkg, contentUri, messageId, timestampSecs, seen, read);
}
@Override
public boolean deleteStoredMessage(String callingPkg, Uri messageUri)
throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS,
"Delete SMS/MMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return false;
}
return getServiceGuarded().deleteStoredMessage(callingPkg, messageUri);
}
@Override
public boolean deleteStoredConversation(String callingPkg, long conversationId)
throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Delete conversation");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return false;
}
return getServiceGuarded().deleteStoredConversation(callingPkg, conversationId);
}
@Override
public boolean updateStoredMessageStatus(String callingPkg, Uri messageUri,
ContentValues statusValues) throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS,
"Update SMS/MMS message");
return getServiceGuarded()
.updateStoredMessageStatus(callingPkg, messageUri, statusValues);
}
@Override
public boolean archiveStoredConversation(String callingPkg, long conversationId,
boolean archived) throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS,
"Update SMS/MMS message");
return getServiceGuarded()
.archiveStoredConversation(callingPkg, conversationId, archived);
}
@Override
public Uri addTextMessageDraft(String callingPkg, String address, String text)
throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Add SMS draft");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
// Silently fail AppOps failure due to not being the default SMS app
// while writing the TelephonyProvider
return FAKE_SMS_DRAFT_URI;
}
return getServiceGuarded().addTextMessageDraft(callingPkg, address, text);
}
@Override
public Uri addMultimediaMessageDraft(String callingPkg, Uri contentUri)
throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Add MMS draft");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
// Silently fail AppOps failure due to not being the default SMS app
// while writing the TelephonyProvider
return FAKE_MMS_DRAFT_URI;
}
return getServiceGuarded().addMultimediaMessageDraft(callingPkg, contentUri);
}
@Override
public void sendStoredMessage(int subId, String callingPkg, Uri messageUri,
Bundle configOverrides, PendingIntent sentIntent) throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.SEND_SMS,
"Send stored MMS message");
if (getAppOpsManager().noteOp(AppOpsManager.OP_SEND_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return;
}
getServiceGuarded().sendStoredMessage(subId, callingPkg, messageUri, configOverrides,
sentIntent);
}
@Override
public void setAutoPersisting(String callingPkg, boolean enabled) throws RemoteException {
mContext.enforceCallingPermission(Manifest.permission.WRITE_SMS, "Set auto persist");
if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SMS, Binder.getCallingUid(),
callingPkg) != AppOpsManager.MODE_ALLOWED) {
return;
}
getServiceGuarded().setAutoPersisting(callingPkg, enabled);
}
@Override
public boolean getAutoPersisting() throws RemoteException {
return getServiceGuarded().getAutoPersisting();
}
/**
* Modifies the Uri to contain the caller's userId, if necessary.
* Grants the phone package on primary user permission to access the contentUri,
* even if the caller is not in the primary user.
*
* @param contentUri The Uri to adjust
* @param action The intent action used to find the associated carrier app
* @param permission The permission to add
* @return The adjusted Uri containing the calling userId.
*/
private Uri adjustUriForUserAndGrantPermission(Uri contentUri, String action,
int permission) {
final int callingUserId = UserHandle.getCallingUserId();
if (callingUserId != UserHandle.USER_OWNER) {
contentUri = ContentProvider.maybeAddUserId(contentUri, callingUserId);
}
long token = Binder.clearCallingIdentity();
try {
mContext.grantUriPermission(PHONE_PACKAGE_NAME, contentUri, permission);
// Grant permission for the carrier app.
Intent intent = new Intent(action);
TelephonyManager telephonyManager =
(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
List<String> carrierPackages = telephonyManager.getCarrierPackageNamesForIntent(
intent);
if (carrierPackages != null && carrierPackages.size() == 1) {
mContext.grantUriPermission(carrierPackages.get(0), contentUri, permission);
}
} finally {
Binder.restoreCallingIdentity(token);
}
return contentUri;
}
}
}
|