summaryrefslogtreecommitdiff
path: root/adservices/framework/java/com/android/adservices/AndroidServiceBinder.java
blob: 280be9a2cf7553e7a4c7b2318405c407f1a9a154 (plain)
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
/*
 * Copyright (C) 2022 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.adservices;

import static android.adservices.common.AdServicesStatusUtils.ILLEGAL_STATE_EXCEPTION_ERROR_MESSAGE;

import static com.android.adservices.AdServicesCommon.ACTION_ADID_PROVIDER_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_ADID_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_AD_EXT_DATA_STORAGE_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_AD_SELECTION_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_AD_SERVICES_COBALT_UPLOAD_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_AD_SERVICES_COMMON_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_APPSETID_PROVIDER_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_APPSETID_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_CUSTOM_AUDIENCE_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_MEASUREMENT_SERVICE;
import static com.android.adservices.AdServicesCommon.ACTION_TOPICS_SERVICE;
import static com.android.adservices.AdServicesCommon.SYSTEM_PROPERTY_FOR_DEBUGGING_FEATURE_RAM_LOW;

import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemProperties;
import android.text.TextUtils;

import com.android.internal.annotations.GuardedBy;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * Service binder that connects to a service in the APK.
 *
 * <p>TODO: Make it robust. Currently this class ignores edge cases. TODO: Clean up the log
 *
 * @hide
 */
class AndroidServiceBinder<T> extends ServiceBinder<T> {
    // TODO: Revisit it.
    private static final int BIND_FLAGS = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;

    // TODO(b/218519915): have a better timeout handling.
    private static final int BINDER_CONNECTION_TIMEOUT_MS = 5_000;

    private final String mServiceIntentAction;
    private final Function<IBinder, T> mBinderConverter;
    private final Context mContext;

    // A CountDownloadLatch which will be opened when the connection is established or any error
    // occurs.
    private CountDownLatch mConnectionCountDownLatch;

    private final Object mLock = new Object();

    @GuardedBy("mLock")
    private T mService;

    @GuardedBy("mLock")
    private ServiceConnection mServiceConnection;

    private final boolean mSimulatingLowRamDevice;

    protected AndroidServiceBinder(
            Context context, String serviceIntentAction, Function<IBinder, T> converter) {
        mServiceIntentAction = serviceIntentAction;
        mContext = context;
        mBinderConverter = converter;
        if (!isDebuggable()) {
            mSimulatingLowRamDevice = false;
        } else {
            String propValue = SystemProperties.get(SYSTEM_PROPERTY_FOR_DEBUGGING_FEATURE_RAM_LOW);
            mSimulatingLowRamDevice = !TextUtils.isEmpty(propValue) && Boolean.valueOf(propValue);
        }
        if (mSimulatingLowRamDevice) {
            LogUtil.w(
                    "Service %s disabled because of system property %s",
                    serviceIntentAction, SYSTEM_PROPERTY_FOR_DEBUGGING_FEATURE_RAM_LOW);
        }
    }

    public T getService() {
        if (mSimulatingLowRamDevice) {
            throw new IllegalStateException(
                    "Service is not bound (because of SystemProperty "
                            + SYSTEM_PROPERTY_FOR_DEBUGGING_FEATURE_RAM_LOW
                            + ")");
        }

        synchronized (mLock) {
            // If we already have a service, just return it.
            if (mService != null) {
                // Note there's a chance the service dies right after we return here,
                // but we can't avoid that.
                return mService;
            }

            // If there's no pending bindService(), we need to start one.
            if (mServiceConnection == null) {
                // There's no other pending connection, creating one.
                ComponentName componentName = getServiceComponentName();
                if (componentName == null) {
                    LogUtil.e("Failed to find AdServices service");
                    return null;
                }
                final Intent intent = new Intent(mServiceIntentAction).setComponent(componentName);

                LogUtil.d("bindService: " + mServiceIntentAction);

                // This latch will open when the connection is established or any error occurs.
                mConnectionCountDownLatch = new CountDownLatch(1);
                mServiceConnection = new AdServicesServiceConnection();

                // We use Runnable::run so that the callback is called on a binder thread.
                // Otherwise we'd use the main thread, which could cause a deadlock.
                try {
                    final boolean success =
                            mContext.bindService(
                                    intent, BIND_FLAGS, Runnable::run, mServiceConnection);
                    if (!success) {
                        LogUtil.e("Failed to bindService: " + intent);
                        mServiceConnection = null;
                        return null;
                    } else {
                        LogUtil.d("bindService() started...");
                    }
                } catch (Exception e) {
                    LogUtil.e(
                            "Caught unexpected exception during service binding: "
                                    + e.getMessage());
                    mServiceConnection = null;
                    return null;
                }
            } else {
                LogUtil.d("There is already a pending connection!");
            }
        }

        // Then wait for connection result.
        // Note: We must not hold the lock while waiting for the connection since the
        // onServiceConnected callback also needs to acquire the lock. This would cause a deadlock.
        try {
            // TODO(b/218519915): Better timeout handling
            mConnectionCountDownLatch.await(BINDER_CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException("Thread interrupted"); // TODO Handle it better.
        }

        synchronized (mLock) {
            if (mService == null) {
                throw new IllegalStateException(ILLEGAL_STATE_EXCEPTION_ERROR_MESSAGE);
            }
            return mService;
        }
    }

    // A class to handle the connection to the AdService Services.
    private class AdServicesServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.d("onServiceConnected " + mServiceIntentAction);
            synchronized (mLock) {
                mService = mBinderConverter.apply(service);
            }
            // Connection is established, open the latch.
            mConnectionCountDownLatch.countDown();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtil.d("onServiceDisconnected " + mServiceIntentAction);
            unbindFromService();
            mConnectionCountDownLatch.countDown();
        }

        @Override
        public void onBindingDied(ComponentName name) {
            LogUtil.d("onBindingDied " + mServiceIntentAction);
            unbindFromService();
            mConnectionCountDownLatch.countDown();
        }

        @Override
        public void onNullBinding(ComponentName name) {
            LogUtil.e("onNullBinding " + mServiceIntentAction);
            unbindFromService();
            mConnectionCountDownLatch.countDown();
        }
    }

    @Nullable
    private ComponentName getServiceComponentName() {
        if (!mServiceIntentAction.equals(ACTION_TOPICS_SERVICE)
                && !mServiceIntentAction.equals(ACTION_MEASUREMENT_SERVICE)
                && !mServiceIntentAction.equals(ACTION_CUSTOM_AUDIENCE_SERVICE)
                && !mServiceIntentAction.equals(ACTION_AD_SELECTION_SERVICE)
                && !mServiceIntentAction.equals(ACTION_ADID_SERVICE)
                && !mServiceIntentAction.equals(ACTION_ADID_PROVIDER_SERVICE)
                && !mServiceIntentAction.equals(ACTION_APPSETID_SERVICE)
                && !mServiceIntentAction.equals(ACTION_APPSETID_PROVIDER_SERVICE)
                && !mServiceIntentAction.equals(ACTION_AD_SERVICES_COBALT_UPLOAD_SERVICE)
                && !mServiceIntentAction.equals(ACTION_AD_SERVICES_COMMON_SERVICE)
                && !mServiceIntentAction.equals(ACTION_AD_EXT_DATA_STORAGE_SERVICE)) {
            LogUtil.e("Bad service intent action: " + mServiceIntentAction);
            return null;
        }
        final Intent intent = new Intent(mServiceIntentAction);

        final List<ResolveInfo> resolveInfos =
                mContext.getPackageManager()
                        .queryIntentServices(intent, PackageManager.MATCH_SYSTEM_ONLY);
        final ServiceInfo serviceInfo =
                AdServicesCommon.resolveAdServicesService(resolveInfos, mServiceIntentAction);
        if (serviceInfo == null) {
            LogUtil.e("Failed to find serviceInfo for adServices service");
            return null;
        }
        return new ComponentName(serviceInfo.packageName, serviceInfo.name);
    }

    @Override
    public void unbindFromService() {
        if (mSimulatingLowRamDevice) {
            LogUtil.d(
                    "unbindFromService(): ignored because it's disabled by system property %s",
                    SYSTEM_PROPERTY_FOR_DEBUGGING_FEATURE_RAM_LOW);
            return;
        }
        synchronized (mLock) {
            if (mServiceConnection != null) {
                LogUtil.d("unbinding...");
                mContext.unbindService(mServiceConnection);
            }
            mServiceConnection = null;
            mService = null;
        }
    }

    // TODO(b/293894199, b/284744130): members below were adapted from BuildCompatUtils, it would
    // be better to move BuildCompatUtils to this package

    private static final boolean IS_DEBUGGABLE = computeIsDebuggable();

    private static boolean isDebuggable() {
        return IS_DEBUGGABLE;
    }

    private static boolean computeIsDebuggable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return Build.isDebuggable();
        }

        // Build.isDebuggable was added in S; duplicate that functionality for R.
        return SystemProperties.getInt("ro.debuggable", 0) == 1;
    }
}