|
| 1 | +package io.grpc.binder.internal; |
| 2 | + |
| 3 | +import static android.content.Intent.URI_INTENT_SCHEME; |
| 4 | +import static com.google.common.base.Preconditions.checkNotNull; |
| 5 | +import static com.google.common.base.Preconditions.checkState; |
| 6 | +import static io.grpc.binder.internal.SystemApis.createContextAsUser; |
| 7 | + |
| 8 | +import android.annotation.SuppressLint; |
| 9 | +import android.content.BroadcastReceiver; |
| 10 | +import android.content.ComponentName; |
| 11 | +import android.content.Context; |
| 12 | +import android.content.Intent; |
| 13 | +import android.content.IntentFilter; |
| 14 | +import android.content.pm.PackageManager; |
| 15 | +import android.content.pm.ResolveInfo; |
| 16 | +import android.os.Build; |
| 17 | +import android.os.UserHandle; |
| 18 | +import com.google.common.collect.ImmutableMap; |
| 19 | +import com.google.common.util.concurrent.FutureCallback; |
| 20 | +import com.google.common.util.concurrent.Futures; |
| 21 | +import com.google.common.util.concurrent.ListenableFuture; |
| 22 | +import com.google.common.util.concurrent.MoreExecutors; |
| 23 | +import io.grpc.Attributes; |
| 24 | +import io.grpc.EquivalentAddressGroup; |
| 25 | +import io.grpc.NameResolver; |
| 26 | +import io.grpc.Status; |
| 27 | +import io.grpc.StatusException; |
| 28 | +import io.grpc.StatusOr; |
| 29 | +import io.grpc.SynchronizationContext; |
| 30 | +import io.grpc.binder.AndroidComponentAddress; |
| 31 | +import io.grpc.binder.ApiConstants; |
| 32 | +import java.net.URI; |
| 33 | +import java.net.URISyntaxException; |
| 34 | +import java.util.ArrayList; |
| 35 | +import java.util.List; |
| 36 | +import java.util.Set; |
| 37 | +import java.util.concurrent.Executor; |
| 38 | +import javax.annotation.Nullable; |
| 39 | + |
| 40 | +/** |
| 41 | + * A {@link NameResolver} that resolves Android-standard "intent:" target URIs to the list of {@link |
| 42 | + * AndroidComponentAddress} that match it by manifest intent filter. |
| 43 | + */ |
| 44 | +final class IntentNameResolver extends NameResolver { |
| 45 | + private final URI targetUri; |
| 46 | + @Nullable private final UserHandle targetUser; // null means same user that hosts this process. |
| 47 | + private final Context targetUserContext; |
| 48 | + private final Executor offloadExecutor; |
| 49 | + private final Executor sequentialExecutor; |
| 50 | + private final SynchronizationContext syncContext; |
| 51 | + private final ServiceConfigParser serviceConfigParser; |
| 52 | + |
| 53 | + // Accessed only on `sequentialExecutor` |
| 54 | + @Nullable private PackageChangeReceiver receiver; |
| 55 | + |
| 56 | + // Accessed only on 'syncContext'. |
| 57 | + private boolean shutdown; |
| 58 | + private boolean lookupNeeded; |
| 59 | + @Nullable private Listener2 listener; |
| 60 | + |
| 61 | + @Nullable |
| 62 | + private ListenableFuture<ResolutionResult> lookupResultFuture; // != null when lookup in progress. |
| 63 | + |
| 64 | + // Servers discovered in PackageManager are especially untrusted. After all, an app can declare |
| 65 | + // any intent filter it wants. Use pre-auth to avoid giving unauthorized apps a chance to run. |
| 66 | + @EquivalentAddressGroup.Attr |
| 67 | + private static final Attributes CONSTANT_EAG_ATTRS = |
| 68 | + Attributes.newBuilder().set(ApiConstants.PRE_AUTH_SERVER_OVERRIDE, true).build(); |
| 69 | + |
| 70 | + IntentNameResolver(Context context, URI targetUri, Args args) { |
| 71 | + this.targetUri = targetUri; |
| 72 | + this.targetUser = args.getArg(ApiConstants.TARGET_ANDROID_USER); |
| 73 | + this.targetUserContext = |
| 74 | + targetUser != null |
| 75 | + ? createContextAsUser(context, targetUser, /* flags= */ 0) // @SystemApi since R. |
| 76 | + : context; |
| 77 | + // This Executor is nominally optional but all grpc-java Channels provide it since 1.25. |
| 78 | + this.offloadExecutor = |
| 79 | + checkNotNull(args.getOffloadExecutor(), "NameResolver.Args.getOffloadExecutor()"); |
| 80 | + // Ensures start()'s work runs before resolve()'s' work, and both run before shutdown()'s. |
| 81 | + this.sequentialExecutor = MoreExecutors.newSequentialExecutor(offloadExecutor); |
| 82 | + this.syncContext = args.getSynchronizationContext(); |
| 83 | + this.serviceConfigParser = args.getServiceConfigParser(); |
| 84 | + } |
| 85 | + |
| 86 | + @Override |
| 87 | + public void start(Listener2 listener) { |
| 88 | + checkState(this.listener == null, "Already started!"); |
| 89 | + checkState(!shutdown, "Resolver is shutdown"); |
| 90 | + this.listener = checkNotNull(listener); |
| 91 | + sequentialExecutor.execute(this::registerReceiver); |
| 92 | + resolve(); |
| 93 | + } |
| 94 | + |
| 95 | + @Override |
| 96 | + public void refresh() { |
| 97 | + checkState(listener != null, "Not started!"); |
| 98 | + resolve(); |
| 99 | + } |
| 100 | + |
| 101 | + private void resolve() { |
| 102 | + syncContext.throwIfNotInThisSynchronizationContext(); |
| 103 | + |
| 104 | + if (shutdown) { |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + // We can't block here in 'syncContext' so we offload PackageManager lookups to an Executor. |
| 109 | + // But offloading complicates things a bit because other calls can arrive while we wait for the |
| 110 | + // results. We keep 'listener' up-to-date with the latest state in PackageManager by doing: |
| 111 | + // 1. Only one lookup-and-report-to-listener operation at a time. |
| 112 | + // 2. At least one lookup-and-report-to-listener AFTER every PackageManager state change. |
| 113 | + if (lookupResultFuture == null) { |
| 114 | + lookupResultFuture = Futures.submit(this::lookupAndroidComponentAddress, sequentialExecutor); |
| 115 | + lookupResultFuture.addListener(this::onLookupComplete, syncContext); |
| 116 | + } else { |
| 117 | + // There's already a lookup in-flight but (2) says we need at least one more. Our sequential |
| 118 | + // Executor would be enough to ensure (1) but we also don't want a backlog of work to build up |
| 119 | + // if things change rapidly. Just make a note to start a new lookup when this one finishes. |
| 120 | + lookupNeeded = true; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + private void onLookupComplete() { |
| 125 | + syncContext.throwIfNotInThisSynchronizationContext(); |
| 126 | + checkState(lookupResultFuture != null); |
| 127 | + checkState(lookupResultFuture.isDone()); |
| 128 | + |
| 129 | + // Capture non-final `listener` here while we're on 'syncContext'. |
| 130 | + Listener2 listener = checkNotNull(this.listener); |
| 131 | + Futures.addCallback( |
| 132 | + lookupResultFuture, // Already isDone() so this execute()s immediately. |
| 133 | + new FutureCallback<ResolutionResult>() { |
| 134 | + @Override |
| 135 | + public void onSuccess(ResolutionResult result) { |
| 136 | + listener.onResult(result); |
| 137 | + } |
| 138 | + |
| 139 | + @Override |
| 140 | + public void onFailure(Throwable t) { |
| 141 | + listener.onError(Status.fromThrowable(t)); |
| 142 | + } |
| 143 | + }, |
| 144 | + sequentialExecutor); |
| 145 | + lookupResultFuture = null; |
| 146 | + |
| 147 | + if (lookupNeeded) { |
| 148 | + // One or more resolve() requests arrived while we were working on the last one. Just one |
| 149 | + // follow-on lookup can subsume all of them. |
| 150 | + lookupNeeded = false; |
| 151 | + resolve(); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + @Override |
| 156 | + public String getServiceAuthority() { |
| 157 | + return "localhost"; |
| 158 | + } |
| 159 | + |
| 160 | + @Override |
| 161 | + public void shutdown() { |
| 162 | + syncContext.throwIfNotInThisSynchronizationContext(); |
| 163 | + if (!shutdown) { |
| 164 | + shutdown = true; |
| 165 | + sequentialExecutor.execute(this::maybeUnregisterReceiver); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + private ResolutionResult lookupAndroidComponentAddress() throws StatusException { |
| 170 | + Intent targetIntent = parseUri(targetUri); |
| 171 | + |
| 172 | + // Avoid a spurious UnsafeIntentLaunchViolation later. Since S, Android's StrictMode is very |
| 173 | + // conservative, marking any Intent parsed from a string as suspicious and complaining when you |
| 174 | + // bind to it. But all this is pointless with grpc-binder, which already goes even further by |
| 175 | + // not trusting addresses at all! Instead, we rely on SecurityPolicy, which won't allow a |
| 176 | + // connection to an unauthorized server UID no matter how you got there. |
| 177 | + targetIntent = sanitize(targetIntent); |
| 178 | + |
| 179 | + List<ResolveInfo> resolveInfoList = lookupServices(targetIntent); |
| 180 | + |
| 181 | + // Model each matching android.app.Service as an individual gRPC server with a single address. |
| 182 | + List<EquivalentAddressGroup> servers = new ArrayList<>(); |
| 183 | + for (ResolveInfo resolveInfo : resolveInfoList) { |
| 184 | + targetIntent.setComponent( |
| 185 | + new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name)); |
| 186 | + servers.add( |
| 187 | + new EquivalentAddressGroup( |
| 188 | + AndroidComponentAddress.newBuilder() |
| 189 | + .setBindIntent(targetIntent) // Makes a copy. |
| 190 | + .setTargetUser(targetUser) |
| 191 | + .build(), |
| 192 | + CONSTANT_EAG_ATTRS)); |
| 193 | + } |
| 194 | + |
| 195 | + return ResolutionResult.newBuilder() |
| 196 | + .setAddressesOrError(StatusOr.fromValue(servers)) |
| 197 | + // Empty service config means we get the default 'pick_first' load balancing policy. |
| 198 | + .setServiceConfig(serviceConfigParser.parseServiceConfig(ImmutableMap.of())) |
| 199 | + .build(); |
| 200 | + } |
| 201 | + |
| 202 | + private List<ResolveInfo> lookupServices(Intent intent) throws StatusException { |
| 203 | + int flags = 0; |
| 204 | + if (Build.VERSION.SDK_INT >= 29) { |
| 205 | + // Don't match direct-boot-unaware Services that can't presently be created. We'll query again |
| 206 | + // after the user is unlocked. The MATCH_DIRECT_BOOT_AUTO behavior is actually the default but |
| 207 | + // being explicit here avoids an android.os.strictmode.ImplicitDirectBootViolation. |
| 208 | + flags |= PackageManager.MATCH_DIRECT_BOOT_AUTO; |
| 209 | + } |
| 210 | + List<ResolveInfo> intentServices = |
| 211 | + targetUserContext.getPackageManager().queryIntentServices(intent, flags); |
| 212 | + |
| 213 | + if (intentServices.isEmpty()) { |
| 214 | + throw Status.UNIMPLEMENTED |
| 215 | + .withDescription("Service not found for intent " + intent) |
| 216 | + .asException(); |
| 217 | + } |
| 218 | + return intentServices; |
| 219 | + } |
| 220 | + |
| 221 | + private static Intent parseUri(URI targetUri) throws StatusException { |
| 222 | + try { |
| 223 | + return Intent.parseUri(targetUri.toString(), URI_INTENT_SCHEME); |
| 224 | + } catch (URISyntaxException uriSyntaxException) { |
| 225 | + throw Status.INVALID_ARGUMENT |
| 226 | + .withCause(uriSyntaxException) |
| 227 | + .withDescription("Failed to parse target URI " + targetUri + " as intent") |
| 228 | + .asException(); |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + // Returns a new Intent with the same action, data and categories as 'input'. |
| 233 | + private static Intent sanitize(Intent input) { |
| 234 | + Intent output = new Intent(); |
| 235 | + output.setAction(input.getAction()); |
| 236 | + output.setData(input.getData()); |
| 237 | + |
| 238 | + Set<String> categories = input.getCategories(); |
| 239 | + if (categories != null) { |
| 240 | + for (String category : categories) { |
| 241 | + output.addCategory(category); |
| 242 | + } |
| 243 | + } |
| 244 | + // Don't bother copying extras and flags since AndroidComponentAddress (rightly) ignores them. |
| 245 | + // Don't bother copying package or ComponentName either, since we're about to set that. |
| 246 | + return output; |
| 247 | + } |
| 248 | + |
| 249 | + final class PackageChangeReceiver extends BroadcastReceiver { |
| 250 | + @Override |
| 251 | + public void onReceive(Context context, Intent intent) { |
| 252 | + // Get off the main thread and into the correct SynchronizationContext. |
| 253 | + syncContext.executeLater(IntentNameResolver.this::resolve); |
| 254 | + offloadExecutor.execute(syncContext::drain); |
| 255 | + } |
| 256 | + } |
| 257 | + |
| 258 | + @SuppressLint("UnprotectedReceiver") // All of these are protected system broadcasts. |
| 259 | + private void registerReceiver() { |
| 260 | + checkState(receiver == null, "Already registered!"); |
| 261 | + receiver = new PackageChangeReceiver(); |
| 262 | + IntentFilter filter = new IntentFilter(); |
| 263 | + filter.addDataScheme("package"); |
| 264 | + filter.addAction(Intent.ACTION_PACKAGE_ADDED); |
| 265 | + filter.addAction(Intent.ACTION_PACKAGE_CHANGED); |
| 266 | + filter.addAction(Intent.ACTION_PACKAGE_REMOVED); |
| 267 | + filter.addAction(Intent.ACTION_PACKAGE_REPLACED); |
| 268 | + |
| 269 | + targetUserContext.registerReceiver(receiver, filter); |
| 270 | + |
| 271 | + if (Build.VERSION.SDK_INT >= 24) { |
| 272 | + // Clients running in direct boot mode must refresh() when the user is unlocked because |
| 273 | + // that's when `directBootAware=false` services become visible in queryIntentServices() |
| 274 | + // results. ACTION_BOOT_COMPLETED would work too but it's delivered with lower priority. |
| 275 | + targetUserContext.registerReceiver(receiver, new IntentFilter(Intent.ACTION_USER_UNLOCKED)); |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + private void maybeUnregisterReceiver() { |
| 280 | + if (receiver != null) { // NameResolver API contract appears to allow shutdown without start(). |
| 281 | + targetUserContext.unregisterReceiver(receiver); |
| 282 | + receiver = null; |
| 283 | + } |
| 284 | + } |
| 285 | +} |
0 commit comments