summaryrefslogtreecommitdiff
path: root/MdnsOffloadManagerService/src/com/android/tv/mdnsoffloadmanager/MdnsOffloadManagerService.java
blob: c554cf8a1c16f4ef130f8babd5d60526491322ab (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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/*
 * Copyright (C) 2023 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.tv.mdnsoffloadmanager;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.annotation.WorkerThread;

import com.android.tv.mdnsoffloadmanager.util.WakeLockWrapper;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import device.google.atv.mdns_offload.IMdnsOffload;
import device.google.atv.mdns_offload.IMdnsOffloadManager;


public class MdnsOffloadManagerService extends Service {

    private static final String TAG = MdnsOffloadManagerService.class.getSimpleName();
    private static final int VENDOR_SERVICE_COMPONENT_ID =
            R.string.config_mdnsOffloadVendorServiceComponent;
    private static final int AWAIT_DUMP_SECONDS = 5;

    private final ConnectivityManager.NetworkCallback mNetworkCallback =
            new ConnectivityManagerNetworkCallback();
    private final Map<String, InterfaceOffloadManager> mInterfaceOffloadManagers = new HashMap<>();
    private final Injector mInjector;
    private Handler mHandler;
    private PriorityListManager mPriorityListManager;
    private OffloadIntentStore mOffloadIntentStore;
    private OffloadWriter mOffloadWriter;
    private ConnectivityManager mConnectivityManager;
    private PackageManager mPackageManager;
    private WakeLockWrapper mWakeLock;

    public MdnsOffloadManagerService() {
        this(new Injector());
    }

    @VisibleForTesting
    MdnsOffloadManagerService(@NonNull Injector injector) {
        super();
        injector.setContext(this);
        mInjector = injector;
    }

    @VisibleForTesting
    static class Injector {

        private Context mContext = null;
        private Looper mLooper = null;

        void setContext(Context context) {
            mContext = context;
        }

        synchronized Looper getLooper() {
            if (mLooper == null) {
                HandlerThread ht = new HandlerThread("MdnsOffloadManager");
                ht.start();
                mLooper = ht.getLooper();
            }
            return mLooper;
        }

        Resources getResources() {
            return mContext.getResources();
        }

        ConnectivityManager getConnectivityManager() {
            return mContext.getSystemService(ConnectivityManager.class);
        }


        PowerManager.LowPowerStandbyPolicy getLowPowerStandbyPolicy() {
            return mContext.getSystemService(PowerManager.class).getLowPowerStandbyPolicy();
        }

        WakeLockWrapper newWakeLock() {
            return new WakeLockWrapper(
                    mContext.getSystemService(PowerManager.class)
                            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG));
        }

        PackageManager getPackageManager() {
            return mContext.getPackageManager();
        }

        boolean isInteractive() {
            return mContext.getSystemService(PowerManager.class).isInteractive();
        }

        boolean bindService(Intent intent, ServiceConnection connection, int flags) {
            return mContext.bindService(intent, connection, flags);
        }

        void registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) {
            mContext.registerReceiver(receiver, filter, flags);
        }

        int getCallingUid() {
            return Binder.getCallingUid();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(mInjector.getLooper());
        mPriorityListManager = new PriorityListManager(mInjector.getResources());
        mOffloadIntentStore = new OffloadIntentStore(mPriorityListManager);
        mOffloadWriter = new OffloadWriter();
        mConnectivityManager = mInjector.getConnectivityManager();
        mPackageManager = mInjector.getPackageManager();
        mWakeLock = mInjector.newWakeLock();
        bindVendorService();
        setupScreenBroadcastReceiver();
        setupConnectivityListener();
        setupStandbyPolicyListener();
    }

    private void bindVendorService() {
        String vendorServicePath = mInjector.getResources().getString(VENDOR_SERVICE_COMPONENT_ID);

        if (vendorServicePath.isEmpty()) {
            String msg = "vendorServicePath is empty. Bind cannot proceed.";
            Log.e(TAG, msg);
            throw new IllegalArgumentException(msg);
        }
        ComponentName componentName = ComponentName.unflattenFromString(vendorServicePath);
        if (componentName == null) {
            String msg = "componentName cannot be extracted from vendorServicePath."
                    + " Bind cannot proceed.";
            Log.e(TAG, msg);
            throw new IllegalArgumentException(msg);
        }

        Log.d(TAG, "IMdnsOffloadManager is binding to: " + componentName);

        Intent explicitIntent = new Intent();
        explicitIntent.setComponent(componentName);
        boolean bindingSuccessful = mInjector.bindService(
                explicitIntent, mVendorServiceConnection, Context.BIND_AUTO_CREATE);
        if (!bindingSuccessful) {
            String msg = "Failed to bind to vendor service at {" + vendorServicePath + "}.";
            Log.e(TAG, msg);
            throw new IllegalStateException(msg);
        }
    }

    private void setupScreenBroadcastReceiver() {
        BroadcastReceiver receiver = new ScreenBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mInjector.registerReceiver(receiver, filter, 0);
        mHandler.post(() -> mOffloadWriter.setOffloadState(!mInjector.isInteractive()));
    }

    private void setupConnectivityListener() {
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                .build();
        mConnectivityManager.registerNetworkCallback(networkRequest, mNetworkCallback);
    }

    private void setupStandbyPolicyListener() {
        BroadcastReceiver receiver = new LowPowerStandbyPolicyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(PowerManager.ACTION_LOW_POWER_STANDBY_POLICY_CHANGED);
        mInjector.registerReceiver(receiver, filter, 0);
        refreshAppIdAllowlist();
    }

    private void refreshAppIdAllowlist() {
        PowerManager.LowPowerStandbyPolicy standbyPolicy = mInjector.getLowPowerStandbyPolicy();
        Set<Integer> allowedAppIds = standbyPolicy.getExemptPackages()
                .stream()
                .map(pkg -> {
                    try {
                        return mPackageManager.getPackageUid(pkg, 0);
                    } catch (PackageManager.NameNotFoundException e) {
                        Log.w(TAG, "Unable to get UID of package {" + pkg + "}.");
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .map(UserHandle::getAppId)
                .collect(Collectors.toSet());
        mHandler.post(() -> {
            mOffloadIntentStore.setAppIdAllowlist(allowedAppIds);
            mInterfaceOffloadManagers.values()
                    .forEach(InterfaceOffloadManager::onAppIdAllowlistUpdated);
        });
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mOffloadManagerBinder;
    }

    @Override
    protected void dump(FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strings) {
        CountDownLatch doneSignal = new CountDownLatch(1);
        mHandler.post(() -> {
            dump(printWriter);
            doneSignal.countDown();
        });
        boolean success = false;
        try {
            success = doneSignal.await(AWAIT_DUMP_SECONDS, TimeUnit.SECONDS);
        } catch (InterruptedException ignored) {
        }
        if (!success) {
            Log.e(TAG, "Failed to dump state on handler thread");
        }
    }

    @WorkerThread
    private void dump(PrintWriter writer) {
        mOffloadIntentStore.dump(writer);
        mInterfaceOffloadManagers.values().forEach(manager -> manager.dump(writer));
        mOffloadWriter.dump(writer);
        mOffloadIntentStore.dumpProtocolData(writer);
    }

    private final IMdnsOffloadManager.Stub mOffloadManagerBinder = new IMdnsOffloadManager.Stub() {
        @Override
        public int addProtocolResponses(@NonNull String networkInterface,
                @NonNull OffloadServiceInfo serviceOffloadData,
                @NonNull IBinder clientToken) {
            Objects.requireNonNull(networkInterface);
            Objects.requireNonNull(serviceOffloadData);
            Objects.requireNonNull(clientToken);
            int callerUid = mInjector.getCallingUid();
            OffloadIntentStore.OffloadIntent offloadIntent =
                    mOffloadIntentStore.registerOffloadIntent(
                            networkInterface, serviceOffloadData, clientToken, callerUid);
            try {
                offloadIntent.mClientToken.linkToDeath(
                        () -> removeProtocolResponses(offloadIntent.mRecordKey, clientToken), 0);
            } catch (RemoteException e) {
                String msg = "Error while setting a callback for linkToDeath binder" +
                        " {" + offloadIntent.mClientToken + "} in addProtocolResponses.";
                Log.e(TAG, msg, e);
                return offloadIntent.mRecordKey;
            }
            mHandler.post(() -> {
                getInterfaceOffloadManager(networkInterface).refreshProtocolResponses();
            });
            return offloadIntent.mRecordKey;
        }

        @Override
        public void removeProtocolResponses(int recordKey, @NonNull IBinder clientToken) {
            if (recordKey <= 0) {
                throw new IllegalArgumentException("recordKey must be positive");
            }
            Objects.requireNonNull(clientToken);
            mHandler.post(() -> {
                OffloadIntentStore.OffloadIntent offloadIntent =
                        mOffloadIntentStore.getAndRemoveOffloadIntent(recordKey, clientToken);
                if (offloadIntent == null) {
                    return;
                }
                getInterfaceOffloadManager(offloadIntent.mNetworkInterface)
                        .refreshProtocolResponses();
            });
        }

        @Override
        public void addToPassthroughList(
                @NonNull String networkInterface,
                @NonNull String qname,
                @NonNull IBinder clientToken) {
            Objects.requireNonNull(networkInterface);
            Objects.requireNonNull(qname);
            Objects.requireNonNull(clientToken);
            int callerUid = mInjector.getCallingUid();
            mHandler.post(() -> {
                OffloadIntentStore.PassthroughIntent ptIntent =
                        mOffloadIntentStore.registerPassthroughIntent(
                                networkInterface, qname, clientToken, callerUid);
                IBinder token = ptIntent.mClientToken;
                try {
                    token.linkToDeath(
                            () -> removeFromPassthroughList(
                                    networkInterface, ptIntent.mCanonicalQName, token), 0);
                } catch (RemoteException e) {
                    String msg = "Error while setting a callback for linkToDeath binder {"
                            + token + "} in addToPassthroughList.";
                    Log.e(TAG, msg, e);
                    return;
                }
                getInterfaceOffloadManager(networkInterface).refreshPassthroughList();
            });
        }

        @Override
        public void removeFromPassthroughList(
                @NonNull String networkInterface,
                @NonNull String qname,
                @NonNull IBinder clientToken) {
            Objects.requireNonNull(networkInterface);
            Objects.requireNonNull(qname);
            Objects.requireNonNull(clientToken);
            mHandler.post(() -> {
                boolean removed = mOffloadIntentStore.removePassthroughIntent(qname, clientToken);
                if (removed) {
                    getInterfaceOffloadManager(networkInterface).refreshPassthroughList();
                }
            });
        }

        @Override
        public int getInterfaceVersion() {
            return super.VERSION;
        }

        @Override
        public String getInterfaceHash() {
            return super.HASH;
        }
    };

    private InterfaceOffloadManager getInterfaceOffloadManager(String networkInterface) {
        return mInterfaceOffloadManagers.computeIfAbsent(
                networkInterface,
                iface -> new InterfaceOffloadManager(iface, mOffloadIntentStore, mOffloadWriter));
    }

    private final ServiceConnection mVendorServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.i(TAG, "IMdnsOffload service bound successfully.");
            IMdnsOffload vendorService = IMdnsOffload.Stub.asInterface(service);
            mHandler.post(() -> {
                mOffloadWriter.setVendorService(vendorService);
                mOffloadWriter.resetAll();
                mInterfaceOffloadManagers.values()
                        .forEach(InterfaceOffloadManager::onVendorServiceConnected);
                mOffloadWriter.applyOffloadState();
            });
        }

        public void onServiceDisconnected(ComponentName className) {
            Log.e(TAG, "IMdnsOffload service has unexpectedly disconnected.");
            mHandler.post(() -> {
                mOffloadWriter.setVendorService(null);
                mInterfaceOffloadManagers.values()
                        .forEach(InterfaceOffloadManager::onVendorServiceDisconnected);
            });
        }
    };

    private class ScreenBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Note: Screen on/off here is actually historical naming for the overall interactive
            // state of the device:
            // https://developer.android.com/reference/android/os/PowerManager#isInteractive()
            String action = intent.getAction();
            mHandler.post(() -> {
                if (Intent.ACTION_SCREEN_ON.equals(action)) {
                    mOffloadWriter.setOffloadState(false);
                    mOffloadWriter.retrieveAndClearMetrics(mOffloadIntentStore.getRecordKeys());
                } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    try {
                        mWakeLock.acquire(5000);
                        mOffloadWriter.setOffloadState(true);
                    } finally {
                        mWakeLock.release();
                    }
                }
            });
        }
    }

    private class LowPowerStandbyPolicyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!PowerManager.ACTION_LOW_POWER_STANDBY_POLICY_CHANGED.equals(intent.getAction())) {
                return;
            }
            refreshAppIdAllowlist();
        }
    }

    private class ConnectivityManagerNetworkCallback extends ConnectivityManager.NetworkCallback {
        private final Map<Network, LinkProperties> mLinkProperties = new HashMap<>();

        @Override
        public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
            // We only want to know the interface name of a network. This method is
            // called right after onAvailable() or any other important change during the lifecycle
            // of the network.
            mHandler.post(() -> {
                LinkProperties previousProperties = mLinkProperties.put(network, linkProperties);
                if (previousProperties != null &&
                        !previousProperties.getInterfaceName().equals(
                                linkProperties.getInterfaceName())) {
                    // This means that the interface changed names, which may happen
                    // but very rarely.
                    InterfaceOffloadManager offloadManager =
                            getInterfaceOffloadManager(previousProperties.getInterfaceName());
                    offloadManager.onNetworkLost();
                }

                // We trigger an onNetworkAvailable even if the existing is the same in case
                // anything needs to be refreshed due to the LinkProperties change.
                InterfaceOffloadManager offloadManager =
                        getInterfaceOffloadManager(linkProperties.getInterfaceName());
                offloadManager.onNetworkAvailable();
            });
        }

        @Override
        public void onLost(@NonNull Network network) {
            mHandler.post(() -> {
                // Network object is guaranteed to match a network object from a previous
                // onLinkPropertiesChanged() so the LinkProperties must be available to retrieve
                // the associated iface.
                LinkProperties previousProperties = mLinkProperties.remove(network);
                if (previousProperties == null){
                    Log.w(TAG,"Network "+ network + " lost before being available.");
                    return;
                }
                InterfaceOffloadManager offloadManager =
                        getInterfaceOffloadManager(previousProperties.getInterfaceName());
                offloadManager.onNetworkLost();
            });
        }
    }
}