blob: 786a1810bc54827307f935afc3e0d04a87859f58 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
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
17package com.android.server;
18
Yuyang Huang33fa4d22023-02-14 22:59:37 +090019import static android.Manifest.permission.NETWORK_SETTINGS;
paulhu2b9ed952022-02-10 21:58:32 +080020import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090021import static android.net.NetworkCapabilities.TRANSPORT_VPN;
22import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Paul Hu019621e2023-01-13 23:26:49 +080023import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080024import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090025import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090026import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080027
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090028import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090029import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000030import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031
Paul Hu23fa2022023-01-13 22:57:24 +080032import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080033import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090034import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080035import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070036import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090037import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090038import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080039import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090040import android.net.LinkProperties;
41import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080042import android.net.mdns.aidl.DiscoveryInfo;
43import android.net.mdns.aidl.GetAddressInfo;
44import android.net.mdns.aidl.IMDnsEventListener;
45import android.net.mdns.aidl.RegistrationInfo;
46import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070047import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090048import android.net.nsd.INsdManagerCallback;
49import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090050import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080051import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080053import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090054import android.net.nsd.OffloadEngine;
55import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090056import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000057import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090058import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080059import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090060import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070062import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090063import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090064import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070065import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090066import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080067import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090068import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090069import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090070import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070071import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072
paulhua262cc12019-08-12 16:25:11 +080073import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000074import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080075import com.android.internal.util.State;
76import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000077import com.android.metrics.NetworkNsdReportedMetrics;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090078import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080079import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090080import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080081import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080083import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090084import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080085import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090086import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080087import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080088import com.android.server.connectivity.mdns.MdnsSearchOptions;
89import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
90import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090092import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080093
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094import java.io.FileDescriptor;
95import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090096import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070097import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090098import java.net.NetworkInterface;
99import java.net.SocketException;
100import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800101import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900102import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700103import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800104import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800105import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900106import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000107import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800108import java.util.regex.Matcher;
109import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700110
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700111/**
112 * Network Service Discovery Service handles remote service discovery operation requests by
113 * implementing the INsdManager interface.
114 *
115 * @hide
116 */
117public class NsdService extends INsdManager.Stub {
118 private static final String TAG = "NsdService";
119 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900120 /**
121 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
122 * implementation.
123 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800124 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800125 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700126
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900127 /**
128 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
129 * implementation.
130 */
131 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
132
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900133 /**
134 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
135 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
136 *
137 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
138 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
139 *
140 * In which case the flags:
141 * "mdns_discovery_manager_allowlist_mytype_version",
142 * "mdns_advertiser_allowlist_mytype_version",
143 * "mdns_discovery_manager_allowlist_othertype_version",
144 * "mdns_advertiser_allowlist_othertype_version"
145 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
146 * be read with
147 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
148 *
149 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
150 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
151 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
152 */
153 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
154
155 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
156 "mdns_discovery_manager_allowlist_";
157 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
158 "mdns_advertiser_allowlist_";
159 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
160
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900161 @VisibleForTesting
162 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
163 "mdns_config_running_app_active_importance_cutoff";
164 @VisibleForTesting
165 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
166 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
167 private final int mRunningAppActiveImportanceCutoff;
168
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900169 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000170 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900171 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000172 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
173 @VisibleForTesting
174 static final int NO_TRANSACTION = -1;
Paul Hu14667de2023-04-17 22:42:47 +0800175 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700176
Hugo Benichi32be63d2017-04-05 14:06:11 +0900177 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900178 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800179 private final MDnsManager mMDnsManager;
180 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900181 @NonNull
182 private final Dependencies mDeps;
183 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800184 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900185 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800186 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900187 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800188 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900189 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900190 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000191 @NonNull
192 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800193 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800194 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800195 // state machine thread. If change this outside state machine, it will need to introduce
196 // synchronization.
197 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800198 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700199
200 /**
201 * Clients receiving asynchronous messages
202 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900203 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700204
Paul Hud44e1b72023-06-16 02:07:42 +0000205 /* A map from transaction(unique) id to client info */
206 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700207
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900208 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
209 @Nullable
210 private WifiManager.MulticastLock mHeldMulticastLock;
211 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
212 // (non-null), value is the requested Network (nullable)
213 @NonNull
214 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
215 @NonNull
216 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
217
Luke Huang05298582021-06-13 16:52:05 +0000218 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700219
Hugo Benichi32be63d2017-04-05 14:06:11 +0900220 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700221 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800222 // The count of the connected legacy clients.
223 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000224 // The number of client that ever connected.
225 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700226
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900227 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
228 new RemoteCallbackList<>();
229
230 private static class OffloadEngineInfo {
231 @NonNull final String mInterfaceName;
232 final long mOffloadCapabilities;
233 final long mOffloadType;
234 @NonNull final IOffloadEngine mOffloadEngine;
235
236 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
237 @NonNull String interfaceName, long capabilities, long offloadType) {
238 this.mOffloadEngine = offloadEngine;
239 this.mInterfaceName = interfaceName;
240 this.mOffloadCapabilities = capabilities;
241 this.mOffloadType = offloadType;
242 }
243 }
244
Paul Hu812e9212023-06-20 06:24:53 +0000245 @VisibleForTesting
246 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000247 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800248 protected final int mTransactionId;
249 @NonNull
250 protected final NsdServiceInfo mReqServiceInfo;
251 @NonNull
252 protected final String mListenedServiceType;
253
Paul Hud44e1b72023-06-16 02:07:42 +0000254 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800255 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000256 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800257 mTransactionId = transactionId;
258 mReqServiceInfo = reqServiceInfo;
259 mListenedServiceType = listenedServiceType;
260 }
261
262 @NonNull
263 public String getListenedServiceType() {
264 return mListenedServiceType;
265 }
266
267 @Override
268 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
269
270 @Override
271 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
272
273 @Override
274 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
275
276 @Override
277 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
278
279 @Override
280 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
281
282 @Override
283 public void onSearchStoppedWithError(int error) { }
284
285 @Override
286 public void onSearchFailedToStart() { }
287
288 @Override
289 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
290
291 @Override
292 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
293 }
294
295 private class DiscoveryListener extends MdnsListener {
296
Paul Hud44e1b72023-06-16 02:07:42 +0000297 DiscoveryListener(int clientRequestId, int transactionId,
298 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
299 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800300 }
301
302 @Override
303 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800304 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
305 NsdManager.SERVICE_FOUND,
Paul Hud44e1b72023-06-16 02:07:42 +0000306 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800307 }
308
309 @Override
310 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800311 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
312 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000313 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800314 }
315 }
316
Paul Hu75069ed2023-01-14 00:31:09 +0800317 private class ResolutionListener extends MdnsListener {
318
Paul Hud44e1b72023-06-16 02:07:42 +0000319 ResolutionListener(int clientRequestId, int transactionId,
320 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
321 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800322 }
323
324 @Override
325 public void onServiceFound(MdnsServiceInfo serviceInfo) {
326 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
327 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hud44e1b72023-06-16 02:07:42 +0000328 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800329 }
330 }
331
Paul Hu30bd70d2023-02-07 13:20:56 +0000332 private class ServiceInfoListener extends MdnsListener {
333
Paul Hud44e1b72023-06-16 02:07:42 +0000334 ServiceInfoListener(int clientRequestId, int transactionId,
335 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
336 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000337 }
338
339 @Override
340 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
341 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
342 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000343 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000344 }
345
346 @Override
347 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
348 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
349 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000350 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000351 }
352
353 @Override
354 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
355 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
356 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000357 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000358 }
359 }
360
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900361 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
362 @Override
363 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
364 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
365 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
366 // filtering on such interfaces, so taking the multicast lock is not necessary to
367 // disable APF filtering of multicast.
368 if (socketNetwork == null
369 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
370 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
371 return;
372 }
373
374 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
375 updateMulticastLock();
376 }
377 }
378
379 @Override
380 public void onSocketDestroyed(@Nullable Network socketNetwork,
381 @NonNull MdnsInterfaceSocket socket) {
382 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
383 updateMulticastLock();
384 }
385 }
386 }
387
388 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
389 private final Handler mHandler;
390
391 private UidImportanceListener(Handler handler) {
392 mHandler = handler;
393 }
394
395 @Override
396 public void onUidImportance(int uid, int importance) {
397 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
398 }
399 }
400
401 private void handleUidImportanceChanged(int uid, int importance) {
402 // Lower importance values are more "important"
403 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
404 ? mRunningAppActiveUids.add(uid)
405 : mRunningAppActiveUids.remove(uid);
406 if (modified) {
407 updateMulticastLock();
408 }
409 }
410
411 /**
412 * Take or release the lock based on updated internal state.
413 *
414 * This determines whether the lock needs to be held based on
415 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
416 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
417 * updated.
418 */
419 private void updateMulticastLock() {
420 final int needsLockUid = getMulticastLockNeededUid();
421 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
422 final WifiManager wm = mContext.getSystemService(WifiManager.class);
423 if (wm == null) {
424 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
425 return;
426 }
427 mHeldMulticastLock = wm.createMulticastLock(TAG);
428 mHeldMulticastLock.acquire();
429 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
430 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
431 mHeldMulticastLock.release();
432 mHeldMulticastLock = null;
433 mServiceLogs.log("Released multicast lock");
434 }
435 }
436
437 /**
438 * @return The UID of an app requiring the multicast lock, or -1 if none.
439 */
440 private int getMulticastLockNeededUid() {
441 if (mWifiLockRequiredNetworks.size() == 0) {
442 // Return early if NSD is not active, or not on any relevant network
443 return -1;
444 }
Paul Hud44e1b72023-06-16 02:07:42 +0000445 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
446 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900447 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
448 // Ignore non-active UIDs
449 continue;
450 }
451
452 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
453 return clientInfo.mUid;
454 }
455 }
456 return -1;
457 }
458
Paul Hu019621e2023-01-13 23:26:49 +0800459 /**
460 * Data class of mdns service callback information.
461 */
462 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000463 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800464 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800465 final MdnsServiceInfo mMdnsServiceInfo;
466
Paul Hud44e1b72023-06-16 02:07:42 +0000467 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
468 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800469 mMdnsServiceInfo = mdnsServiceInfo;
470 }
471 }
472
Irfan Sheriff75006652012-04-17 23:15:29 -0700473 private class NsdStateMachine extends StateMachine {
474
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700475 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700476 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700477
478 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700479 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900480 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700481 }
482
Luke Huang92860f92021-06-23 06:29:30 +0000483 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800484 if (mIsDaemonStarted) {
485 if (DBG) Log.d(TAG, "Daemon is already started.");
486 return;
487 }
488 mMDnsManager.registerEventListener(mMDnsEventCallback);
489 mMDnsManager.startDaemon();
490 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000491 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000492 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000493 }
494
paulhu2b9ed952022-02-10 21:58:32 +0800495 private void maybeStopDaemon() {
496 if (!mIsDaemonStarted) {
497 if (DBG) Log.d(TAG, "Daemon has not been started.");
498 return;
499 }
500 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
501 mMDnsManager.stopDaemon();
502 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000503 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800504 }
505
Luke Huang92860f92021-06-23 06:29:30 +0000506 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000507 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000508 }
509
510 private void scheduleStop() {
511 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
512 }
513 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800514 // The native daemon should stay alive and can't be cleanup
515 // if any legacy client connected.
516 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000517 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000518 }
519 }
520
Luke Huang92860f92021-06-23 06:29:30 +0000521 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000522 this.removeMessages(NsdManager.DAEMON_CLEANUP);
523 }
524
Paul Hu23fa2022023-01-13 22:57:24 +0800525 private void maybeStartMonitoringSockets() {
526 if (mIsMonitoringSocketsStarted) {
527 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
528 return;
529 }
530
531 mMdnsSocketProvider.startMonitoringSockets();
532 mIsMonitoringSocketsStarted = true;
533 }
534
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900535 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
536 if (!mIsMonitoringSocketsStarted) return;
537 if (isAnyRequestActive()) return;
538
Paul Hu58f20602023-02-18 11:41:07 +0800539 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800540 mIsMonitoringSocketsStarted = false;
541 }
542
Hugo Benichi803a2f02017-04-24 11:35:06 +0900543 NsdStateMachine(String name, Handler handler) {
544 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700545 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700546 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800547 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900548 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700549 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700550 }
551
552 class DefaultState extends State {
553 @Override
554 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900555 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000556 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700557 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900558 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800559 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
560 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900561 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800562 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000563 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000564 final NetworkNsdReportedMetrics metrics =
565 mDeps.makeNetworkNsdReportedMetrics(
566 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900567 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000568 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800569 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900570 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000571 Log.w(TAG, "Client request id " + clientRequestId
572 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700573 }
574 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900575 case NsdManager.UNREGISTER_CLIENT:
576 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
577 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800578 if (cInfo != null) {
579 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900580 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800581 mLegacyClientCount -= 1;
582 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800583 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900584 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800585 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700586 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700587 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900588 cInfo = getClientInfoForReply(msg);
589 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000590 cInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000591 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900592 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 break;
594 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 cInfo = getClientInfoForReply(msg);
596 if (cInfo != null) {
597 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000598 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900599 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700600 break;
601 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 cInfo = getClientInfoForReply(msg);
603 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000604 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000605 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700607 break;
608 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900609 cInfo = getClientInfoForReply(msg);
610 if (cInfo != null) {
611 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000612 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900613 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700614 break;
615 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900616 cInfo = getClientInfoForReply(msg);
617 if (cInfo != null) {
618 cInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000619 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700621 break;
Paul Hub58deb72022-12-26 09:24:42 +0000622 case NsdManager.STOP_RESOLUTION:
623 cInfo = getClientInfoForReply(msg);
624 if (cInfo != null) {
625 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000626 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000627 }
628 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000629 case NsdManager.REGISTER_SERVICE_CALLBACK:
630 cInfo = getClientInfoForReply(msg);
631 if (cInfo != null) {
632 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000633 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000634 }
635 break;
Luke Huang05298582021-06-13 16:52:05 +0000636 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800637 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000638 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800639 // This event should be only sent by the legacy (target SDK < S) clients.
640 // Mark the sending client as legacy.
641 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900642 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800643 if (cInfo != null) {
644 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900645 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800646 mLegacyClientCount += 1;
647 maybeStartDaemon();
648 }
649 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700650 default:
paulhub2225702021-11-17 09:35:33 +0800651 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700652 return NOT_HANDLED;
653 }
654 return HANDLED;
655 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900656
657 private ClientInfo getClientInfoForReply(Message msg) {
658 final ListenerArgs args = (ListenerArgs) msg.obj;
659 return mClients.get(args.connector);
660 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700661 }
662
Irfan Sheriff75006652012-04-17 23:15:29 -0700663 class EnabledState extends State {
664 @Override
665 public void enter() {
666 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 }
668
669 @Override
670 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000671 // TODO: it is incorrect to stop the daemon without expunging all requests
672 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000673 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700674 }
675
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700676 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900677 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800678 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700679 return true;
680 }
681 return false;
682 }
683
Paul Hud44e1b72023-06-16 02:07:42 +0000684 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
685 ClientInfo clientInfo, int what) {
Paul Hu777ed052023-06-19 13:35:15 +0000686 clientInfo.mClientRequests.put(clientRequestId, new LegacyClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000687 transactionId, what, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000688 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000689 // Remove the cleanup event because here comes a new request.
690 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700691 }
692
Paul Hud44e1b72023-06-16 02:07:42 +0000693 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900694 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000695 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000696 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000697 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900698 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800699 }
700
Paul Hud44e1b72023-06-16 02:07:42 +0000701 private void removeRequestMap(
702 int clientRequestId, int transactionId, ClientInfo clientInfo) {
703 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900704 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000705 clientInfo.mClientRequests.remove(clientRequestId);
706 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900707
708 if (existing instanceof LegacyClientRequest) {
709 maybeScheduleStop();
710 } else {
711 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900712 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900713 }
714 }
715
Paul Hud44e1b72023-06-16 02:07:42 +0000716 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900717 MdnsListener listener, ClientInfo clientInfo,
718 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000719 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000720 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000721 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900722 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800723 }
724
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900725 /**
726 * Truncate a service name to up to 63 UTF-8 bytes.
727 *
728 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
729 * names used in registerService follows historical behavior (see mdnsresponder
730 * handle_regservice_request).
731 */
732 @NonNull
733 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900734 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800735 }
736
Paul Hud44e1b72023-06-16 02:07:42 +0000737 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
738 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800739 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000740 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800741 }
742
Irfan Sheriff75006652012-04-17 23:15:29 -0700743 @Override
744 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900745 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000746 final int transactionId;
747 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900748 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900749 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700750 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800751 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800752 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900753 args = (ListenerArgs) msg.obj;
754 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000755 // If the binder death notification for a INsdManagerCallback was received
756 // before any calls are received by NsdService, the clientInfo would be
757 // cleared and cause NPE. Add a null check here to prevent this corner case.
758 if (clientInfo == null) {
759 Log.e(TAG, "Unknown connector in discovery");
760 break;
761 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700762
763 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000764 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000765 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700766 break;
767 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700768
Paul Hu23fa2022023-01-13 22:57:24 +0800769 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000770 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900771 final Pair<String, String> typeAndSubtype =
772 parseTypeAndSubtype(info.getServiceType());
773 final String serviceType = typeAndSubtype == null
774 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800775 if (clientInfo.mUseJavaBackend
776 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900777 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800778 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000779 clientInfo.onDiscoverServicesFailedImmediately(
780 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800781 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700782 }
Paul Hu23fa2022023-01-13 22:57:24 +0800783
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900784 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800785 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000786 final MdnsListener listener = new DiscoveryListener(clientRequestId,
787 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900788 final MdnsSearchOptions.Builder optionsBuilder =
789 MdnsSearchOptions.newBuilder()
790 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900791 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900792 .setIsPassiveMode(true);
793 if (typeAndSubtype.second != null) {
794 // The parsing ensures subtype starts with an underscore.
795 // MdnsSearchOptions expects the underscore to not be present.
796 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
797 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900798 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900799 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000800 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
801 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000802 clientInfo.onDiscoverServicesStarted(
803 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000804 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000805 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700806 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800807 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000808 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800809 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000810 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800811 + info.getServiceType());
812 }
Paul Hud44e1b72023-06-16 02:07:42 +0000813 storeLegacyRequestMap(
814 clientRequestId, transactionId, clientInfo, msg.what);
Paul Hu812e9212023-06-20 06:24:53 +0000815 clientInfo.onDiscoverServicesStarted(
816 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800817 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000818 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000819 clientInfo.onDiscoverServicesFailedImmediately(
820 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800821 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 }
823 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800824 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900825 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800826 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900827 args = (ListenerArgs) msg.obj;
828 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000829 // If the binder death notification for a INsdManagerCallback was received
830 // before any calls are received by NsdService, the clientInfo would be
831 // cleared and cause NPE. Add a null check here to prevent this corner case.
832 if (clientInfo == null) {
833 Log.e(TAG, "Unknown connector in stop discovery");
834 break;
835 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700836
Paul Hud44e1b72023-06-16 02:07:42 +0000837 final ClientRequest request =
838 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900839 if (request == null) {
840 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700841 break;
842 }
Paul Hud44e1b72023-06-16 02:07:42 +0000843 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900844 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
845 // point, so this needs to check the type of the original request to
846 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900847 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000848 stopDiscoveryManagerRequest(
849 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000850 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000851 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700852 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000853 removeRequestMap(clientRequestId, transactionId, clientInfo);
854 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000855 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800856 } else {
857 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000858 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800859 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700860 }
861 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900862 }
863 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800864 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900865 args = (ListenerArgs) msg.obj;
866 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000867 // If the binder death notification for a INsdManagerCallback was received
868 // before any calls are received by NsdService, the clientInfo would be
869 // cleared and cause NPE. Add a null check here to prevent this corner case.
870 if (clientInfo == null) {
871 Log.e(TAG, "Unknown connector in registration");
872 break;
873 }
874
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700875 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000876 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000877 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700878 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700879 }
880
Paul Hud44e1b72023-06-16 02:07:42 +0000881 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900882 final NsdServiceInfo serviceInfo = args.serviceInfo;
883 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900884 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
885 final String registerServiceType = typeSubtype == null
886 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800887 if (clientInfo.mUseJavaBackend
888 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900889 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900890 if (registerServiceType == null) {
891 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000892 clientInfo.onRegisterServiceFailedImmediately(
893 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900894 break;
895 }
896 serviceInfo.setServiceType(registerServiceType);
897 serviceInfo.setServiceName(truncateServiceName(
898 serviceInfo.getServiceName()));
899
900 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900901 // TODO: pass in the subtype as well. Including the subtype in the
902 // service type would generate service instance names like
903 // Name._subtype._sub._type._tcp, which is incorrect
904 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000905 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
906 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900907 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700908 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900909 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000910 if (registerService(transactionId, serviceInfo)) {
911 if (DBG) {
912 Log.d(TAG, "Register " + clientRequestId
913 + " " + transactionId);
914 }
915 storeLegacyRequestMap(
916 clientRequestId, transactionId, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900917 // Return success after mDns reports success
918 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000919 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000920 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000921 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900922 }
923
Irfan Sheriff75006652012-04-17 23:15:29 -0700924 }
925 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900926 }
927 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800928 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900929 args = (ListenerArgs) msg.obj;
930 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000931 // If the binder death notification for a INsdManagerCallback was received
932 // before any calls are received by NsdService, the clientInfo would be
933 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900934 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800935 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700936 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700937 }
Paul Hud44e1b72023-06-16 02:07:42 +0000938 final ClientRequest request =
939 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900940 if (request == null) {
941 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
942 break;
943 }
Paul Hud44e1b72023-06-16 02:07:42 +0000944 transactionId = request.mTransactionId;
945 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900946
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900947 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
948 // so this needs to check the type of the original request to unregister
949 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000950 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900951 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000952 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000953 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +0000954 request.calculateRequestDurationMs(stopTimeMs));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700955 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000956 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000957 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +0000958 transactionId,
959 request.calculateRequestDurationMs(stopTimeMs));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900960 } else {
961 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000962 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900963 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700964 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700965 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900966 }
Paul Hu75069ed2023-01-14 00:31:09 +0800967 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800968 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900969 args = (ListenerArgs) msg.obj;
970 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000971 // If the binder death notification for a INsdManagerCallback was received
972 // before any calls are received by NsdService, the clientInfo would be
973 // cleared and cause NPE. Add a null check here to prevent this corner case.
974 if (clientInfo == null) {
975 Log.e(TAG, "Unknown connector in resolution");
976 break;
977 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700978
Paul Hu75069ed2023-01-14 00:31:09 +0800979 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000980 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900981 final Pair<String, String> typeSubtype =
982 parseTypeAndSubtype(info.getServiceType());
983 final String serviceType = typeSubtype == null
984 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800985 if (clientInfo.mUseJavaBackend
986 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900987 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800988 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000989 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu75069ed2023-01-14 00:31:09 +0800990 NsdManager.FAILURE_INTERNAL_ERROR);
991 break;
992 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900993 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800994
995 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000996 final MdnsListener listener = new ResolutionListener(clientRequestId,
997 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800998 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
999 .setNetwork(info.getNetwork())
1000 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001001 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001002 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001003 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001004 mMdnsDiscoveryManager.registerListener(
1005 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001006 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1007 listener, clientInfo, info.getNetwork());
1008 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001009 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001010 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001011 if (clientInfo.mResolvedService != null) {
1012 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001013 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001014 break;
1015 }
1016
1017 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001018 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001019 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hud44e1b72023-06-16 02:07:42 +00001020 storeLegacyRequestMap(
1021 clientRequestId, transactionId, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +08001022 } else {
1023 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001024 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001025 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001026 }
1027 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001028 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001029 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001030 if (DBG) Log.d(TAG, "Stop service resolution");
1031 args = (ListenerArgs) msg.obj;
1032 clientInfo = mClients.get(args.connector);
1033 // If the binder death notification for a INsdManagerCallback was received
1034 // before any calls are received by NsdService, the clientInfo would be
1035 // cleared and cause NPE. Add a null check here to prevent this corner case.
1036 if (clientInfo == null) {
1037 Log.e(TAG, "Unknown connector in stop resolution");
1038 break;
1039 }
1040
Paul Hud44e1b72023-06-16 02:07:42 +00001041 final ClientRequest request =
1042 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001043 if (request == null) {
1044 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1045 break;
1046 }
Paul Hud44e1b72023-06-16 02:07:42 +00001047 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001048 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1049 // point, so this needs to check the type of the original request to
1050 // unregister instead of looking at the flag value.
1051 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001052 stopDiscoveryManagerRequest(
1053 request, clientRequestId, transactionId, clientInfo);
1054 clientInfo.onStopResolutionSucceeded(clientRequestId);
1055 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001056 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001057 removeRequestMap(clientRequestId, transactionId, clientInfo);
1058 if (stopResolveService(transactionId)) {
1059 clientInfo.onStopResolutionSucceeded(clientRequestId);
Paul Hue4f5f252023-02-16 21:13:47 +08001060 } else {
1061 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001062 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001063 }
1064 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001065 }
Paul Hub58deb72022-12-26 09:24:42 +00001066 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001067 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001068 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001069 if (DBG) Log.d(TAG, "Register a service callback");
1070 args = (ListenerArgs) msg.obj;
1071 clientInfo = mClients.get(args.connector);
1072 // If the binder death notification for a INsdManagerCallback was received
1073 // before any calls are received by NsdService, the clientInfo would be
1074 // cleared and cause NPE. Add a null check here to prevent this corner case.
1075 if (clientInfo == null) {
1076 Log.e(TAG, "Unknown connector in callback registration");
1077 break;
1078 }
1079
Paul Hu30bd70d2023-02-07 13:20:56 +00001080 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001081 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001082 final Pair<String, String> typeAndSubtype =
1083 parseTypeAndSubtype(info.getServiceType());
1084 final String serviceType = typeAndSubtype == null
1085 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001087 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001088 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001089 break;
1090 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001091 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001092
Paul Hu30bd70d2023-02-07 13:20:56 +00001093 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001094 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1095 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001096 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1097 .setNetwork(info.getNetwork())
1098 .setIsPassiveMode(true)
1099 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001100 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001101 .build();
1102 mMdnsDiscoveryManager.registerListener(
1103 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001104 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1105 clientInfo, info.getNetwork());
1106 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001107 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001108 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001109 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001110 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001111 if (DBG) Log.d(TAG, "Unregister a service callback");
1112 args = (ListenerArgs) msg.obj;
1113 clientInfo = mClients.get(args.connector);
1114 // If the binder death notification for a INsdManagerCallback was received
1115 // before any calls are received by NsdService, the clientInfo would be
1116 // cleared and cause NPE. Add a null check here to prevent this corner case.
1117 if (clientInfo == null) {
1118 Log.e(TAG, "Unknown connector in callback unregistration");
1119 break;
1120 }
1121
Paul Hud44e1b72023-06-16 02:07:42 +00001122 final ClientRequest request =
1123 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001124 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001125 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001126 break;
1127 }
Paul Hud44e1b72023-06-16 02:07:42 +00001128 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001129 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001130 stopDiscoveryManagerRequest(
1131 request, clientRequestId, transactionId, clientInfo);
1132 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1133 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001134 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001135 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001136 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001137 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001138 }
paulhu2b9ed952022-02-10 21:58:32 +08001139 case MDNS_SERVICE_EVENT:
1140 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001141 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001142 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001143 break;
Paul Hu019621e2023-01-13 23:26:49 +08001144 case MDNS_DISCOVERY_MANAGER_EVENT:
1145 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1146 return NOT_HANDLED;
1147 }
1148 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001149 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1150 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1151 // TODO: Limits the number of registrations created by a given class.
1152 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1153 offloadEngineInfo);
1154 // TODO: Sends all the existing OffloadServiceInfos back.
1155 break;
1156 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1157 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1158 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001159 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001160 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001161 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001162 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001163 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001164
Paul Hud44e1b72023-06-16 02:07:42 +00001165 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001166 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001167 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001168 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001169 Log.e(TAG, String.format(
1170 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001171 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001172 }
1173
1174 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001175 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1176 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001177 // This can happen because of race conditions. For example,
1178 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1179 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001180 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1181 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001182 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001183 }
Paul Hu812e9212023-06-20 06:24:53 +00001184 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1185 if (request == null) {
1186 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1187 return false;
1188 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001189 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001190 Log.d(TAG, String.format(
1191 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001192 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001193 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001194 case IMDnsEventListener.SERVICE_FOUND: {
1195 final DiscoveryInfo info = (DiscoveryInfo) obj;
1196 final String name = info.serviceName;
1197 final String type = info.registrationType;
1198 servInfo = new NsdServiceInfo(name, type);
1199 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001200 if (foundNetId == 0L) {
1201 // Ignore services that do not have a Network: they are not usable
1202 // by apps, as they would need privileged permissions to use
1203 // interfaces that do not have an associated Network.
1204 break;
1205 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001206 if (foundNetId == INetd.DUMMY_NET_ID) {
1207 // Ignore services on the dummy0 interface: they are only seen when
1208 // discovering locally advertised services, and are not reachable
1209 // through that interface.
1210 break;
1211 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001212 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001213
1214 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001215 break;
paulhu2b9ed952022-02-10 21:58:32 +08001216 }
1217 case IMDnsEventListener.SERVICE_LOST: {
1218 final DiscoveryInfo info = (DiscoveryInfo) obj;
1219 final String name = info.serviceName;
1220 final String type = info.registrationType;
1221 final int lostNetId = info.netId;
1222 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001223 // The network could be set to null (netId 0) if it was torn down when the
1224 // service is lost
1225 // TODO: avoid returning null in that case, possibly by remembering
1226 // found services on the same interface index and their network at the time
1227 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001228 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001229 break;
paulhu2b9ed952022-02-10 21:58:32 +08001230 }
1231 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001232 clientInfo.onDiscoverServicesFailed(clientRequestId,
1233 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1234 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001235 break;
paulhu2b9ed952022-02-10 21:58:32 +08001236 case IMDnsEventListener.SERVICE_REGISTERED: {
1237 final RegistrationInfo info = (RegistrationInfo) obj;
1238 final String name = info.serviceName;
1239 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001240 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001241 transactionId,
1242 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001243 break;
paulhu2b9ed952022-02-10 21:58:32 +08001244 }
1245 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001246 clientInfo.onRegisterServiceFailed(clientRequestId,
1247 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001248 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001249 break;
paulhu2b9ed952022-02-10 21:58:32 +08001250 case IMDnsEventListener.SERVICE_RESOLVED: {
1251 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001252 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001253 final String fullName = info.serviceFullName;
1254 while (index < fullName.length() && fullName.charAt(index) != '.') {
1255 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001256 ++index;
1257 }
1258 ++index;
1259 }
paulhu2b9ed952022-02-10 21:58:32 +08001260 if (index >= fullName.length()) {
1261 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001262 break;
1263 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001264
paulhube186602022-04-12 07:18:23 +00001265 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001266 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001267 String type = rest.replace(".local.", "");
1268
Paul Hu30bd70d2023-02-07 13:20:56 +00001269 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001270 serviceInfo.setServiceName(name);
1271 serviceInfo.setServiceType(type);
1272 serviceInfo.setPort(info.port);
1273 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001274 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275
Paul Hud44e1b72023-06-16 02:07:42 +00001276 stopResolveService(transactionId);
1277 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001278
Paul Hud44e1b72023-06-16 02:07:42 +00001279 final int transactionId2 = getUniqueId();
1280 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1281 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001282 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001283 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001284 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001285 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001286 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001287 }
1288 break;
paulhu2b9ed952022-02-10 21:58:32 +08001289 }
1290 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001291 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001292 stopResolveService(transactionId);
1293 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001294 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001295 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001296 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001297 break;
paulhu2b9ed952022-02-10 21:58:32 +08001298 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001299 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001300 stopGetAddrInfo(transactionId);
1301 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001302 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001303 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001304 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001305 break;
paulhu2b9ed952022-02-10 21:58:32 +08001306 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001307 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001308 final GetAddressInfo info = (GetAddressInfo) obj;
1309 final String address = info.address;
1310 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001311 InetAddress serviceHost = null;
1312 try {
paulhu2b9ed952022-02-10 21:58:32 +08001313 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001314 } catch (UnknownHostException e) {
1315 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1316 }
1317
1318 // If the resolved service is on an interface without a network, consider it
1319 // as a failure: it would not be usable by apps as they would need
1320 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001321 if (netId != NETID_UNSET && serviceHost != null) {
1322 clientInfo.mResolvedService.setHost(serviceHost);
1323 setServiceNetworkForCallback(clientInfo.mResolvedService,
1324 netId, info.interfaceIdx);
1325 clientInfo.onResolveServiceSucceeded(
Paul Hud44e1b72023-06-16 02:07:42 +00001326 clientRequestId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001327 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001328 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001329 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001330 }
Paul Hud44e1b72023-06-16 02:07:42 +00001331 stopGetAddrInfo(transactionId);
1332 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001333 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001334 break;
paulhu2b9ed952022-02-10 21:58:32 +08001335 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001336 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001337 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001338 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001339 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001340 }
Paul Hu019621e2023-01-13 23:26:49 +08001341
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001342 @Nullable
1343 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1344 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001345 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001346 final String[] typeArray = serviceInfo.getServiceType();
1347 final String joinedType;
1348 if (typeArray.length == 0
1349 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1350 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1351 + Arrays.toString(typeArray));
1352 return null;
1353 } else {
1354 joinedType = TextUtils.join(".",
1355 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1356 }
1357 final String serviceType;
1358 switch (code) {
1359 case NsdManager.SERVICE_FOUND:
1360 case NsdManager.SERVICE_LOST:
1361 // For consistency with historical behavior, discovered service types have
1362 // a dot at the end.
1363 serviceType = joinedType + ".";
1364 break;
1365 case RESOLVE_SERVICE_SUCCEEDED:
1366 // For consistency with historical behavior, resolved service types have
1367 // a dot at the beginning.
1368 serviceType = "." + joinedType;
1369 break;
1370 default:
1371 serviceType = joinedType;
1372 break;
1373 }
Paul Hu019621e2023-01-13 23:26:49 +08001374 final String serviceName = serviceInfo.getServiceInstanceName();
1375 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1376 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001377 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1378 // network for Tethering interface. In other words, the network == null means the
1379 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001380 setServiceNetworkForCallback(
1381 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001382 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001383 serviceInfo.getInterfaceIndex());
1384 return servInfo;
1385 }
1386
1387 private boolean handleMdnsDiscoveryManagerEvent(
1388 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001389 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001390 if (clientInfo == null) {
1391 Log.e(TAG, String.format(
1392 "id %d for %d has no client mapping", transactionId, code));
1393 return false;
1394 }
1395
1396 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001397 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001398 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1399 // Errors are already logged if null
1400 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001401 mServiceLogs.log(String.format(
1402 "MdnsDiscoveryManager event code=%s transactionId=%d",
1403 NsdManager.nameOf(code), transactionId));
Paul Hu812e9212023-06-20 06:24:53 +00001404 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1405 if (request == null) {
1406 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1407 return false;
1408 }
Paul Hu019621e2023-01-13 23:26:49 +08001409 switch (code) {
1410 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001411 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001412 break;
1413 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001414 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001415 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001416 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1417 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001418 info.setPort(serviceInfo.getPort());
1419
1420 Map<String, String> attrs = serviceInfo.getAttributes();
1421 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1422 final String key = kv.getKey();
1423 try {
1424 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1425 } catch (IllegalArgumentException e) {
1426 Log.e(TAG, "Invalid attribute", e);
1427 }
1428 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001429 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001430 if (addresses.size() != 0) {
1431 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001432 clientInfo.onResolveServiceSucceeded(clientRequestId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001433 } else {
1434 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001435 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001436 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001437 }
1438
1439 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001440 if (!(request instanceof DiscoveryManagerRequest)) {
1441 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1442 break;
1443 }
Paul Hud44e1b72023-06-16 02:07:42 +00001444 stopDiscoveryManagerRequest(
1445 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001446 break;
1447 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001448 case NsdManager.SERVICE_UPDATED: {
1449 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1450 info.setPort(serviceInfo.getPort());
1451
1452 Map<String, String> attrs = serviceInfo.getAttributes();
1453 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1454 final String key = kv.getKey();
1455 try {
1456 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1457 } catch (IllegalArgumentException e) {
1458 Log.e(TAG, "Invalid attribute", e);
1459 }
1460 }
1461
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001462 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001463 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001464 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001465 break;
1466 }
1467 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001468 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001469 break;
Paul Hu019621e2023-01-13 23:26:49 +08001470 default:
1471 return false;
1472 }
1473 return true;
1474 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001475 }
1476 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001477
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001478 @NonNull
1479 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1480 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1481 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1482 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1483 for (String ipv4Address : v4Addrs) {
1484 try {
1485 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1486 } catch (IllegalArgumentException e) {
1487 Log.wtf(TAG, "Invalid ipv4 address", e);
1488 }
1489 }
1490 for (String ipv6Address : v6Addrs) {
1491 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001492 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1493 ipv6Address);
1494 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1495 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001496 Log.wtf(TAG, "Invalid ipv6 address", e);
1497 }
1498 }
1499 return addresses;
1500 }
1501
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001502 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1503 switch (netId) {
1504 case NETID_UNSET:
1505 info.setNetwork(null);
1506 break;
1507 case INetd.LOCAL_NET_ID:
1508 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1509 // visible / usable for apps, so do not return it. Store the interface
1510 // index instead, so at least if the client tries to resolve the service
1511 // with that NsdServiceInfo, it will be done on the same interface.
1512 // If they recreate the NsdServiceInfo themselves, resolution would be
1513 // done on all interfaces as before T, which should also work.
1514 info.setNetwork(null);
1515 info.setInterfaceIndex(ifaceIdx);
1516 break;
1517 default:
1518 info.setNetwork(new Network(netId));
1519 }
1520 }
1521
paulhube186602022-04-12 07:18:23 +00001522 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1523 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1524 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1525 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1526 private String unescape(String s) {
1527 StringBuilder sb = new StringBuilder(s.length());
1528 for (int i = 0; i < s.length(); ++i) {
1529 char c = s.charAt(i);
1530 if (c == '\\') {
1531 if (++i >= s.length()) {
1532 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1533 break;
1534 }
1535 c = s.charAt(i);
1536 if (c != '.' && c != '\\') {
1537 if (i + 2 >= s.length()) {
1538 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1539 break;
1540 }
1541 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1542 + (s.charAt(i + 2) - '0'));
1543 i += 2;
1544 }
1545 }
1546 sb.append(c);
1547 }
1548 return sb.toString();
1549 }
1550
Paul Hu7445e3d2023-03-03 15:14:00 +08001551 /**
1552 * Check the given service type is valid and construct it to a service type
1553 * which can use for discovery / resolution service.
1554 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001555 * <p>The valid service type should be 2 labels, or 3 labels if the query is for a
Paul Hu7445e3d2023-03-03 15:14:00 +08001556 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1557 * underscore; they are alphanumerical characters or dashes or underscore, except the
1558 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1559 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001560 * <p>The subtype may also be specified with a comma after the service type, for example
1561 * _type._tcp,_subtype.
1562 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001563 * @param serviceType the request service type for discovery / resolution service
1564 * @return constructed service type or null if the given service type is invalid.
1565 */
1566 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001567 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001568 if (TextUtils.isEmpty(serviceType)) return null;
1569
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001570 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001571 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001572 // Optional leading subtype (_subtype._type._tcp)
1573 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1574 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1575 // Actual type (_type._tcp.local)
1576 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001577 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001578 // e.g. allow "_type._tcp.local."
1579 + "\\.?"
1580 // Optional subtype after comma, for "_type._tcp,_subtype" format
1581 + "(?:,(" + typeOrSubtypePattern + "))?"
1582 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001583 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1584 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001585 // Use the subtype either at the beginning or after the comma
1586 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1587 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001588 }
1589
Hugo Benichi803a2f02017-04-24 11:35:06 +09001590 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001591 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001592 this(ctx, handler, cleanupDelayMs, new Dependencies());
1593 }
1594
1595 @VisibleForTesting
1596 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001597 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001598 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001599 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001600 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001601 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1602 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001603 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001604
Paul Hu14667de2023-04-17 22:42:47 +08001605 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001606 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001607 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1608 // address events are received.
1609 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001610
1611 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1612 // startBootstrapServices).
1613 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1614 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1615 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1616 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1617 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1618 mRunningAppActiveImportanceCutoff);
1619
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001620 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001621 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1622 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001623 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001624 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001625 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1626 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001627 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001628 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001629 }
1630
1631 /**
1632 * Dependencies of NsdService, for injection in tests.
1633 */
1634 @VisibleForTesting
1635 public static class Dependencies {
1636 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001637 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001638 *
1639 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001640 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001641 */
1642 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001643 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1644 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001645 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001646 }
1647
1648 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001649 * Check whether the MdnsAdvertiser feature is enabled.
1650 *
1651 * @param context The global context information about an app environment.
1652 * @return true if the MdnsAdvertiser feature is enabled.
1653 */
1654 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001655 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1656 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1657 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001658 }
1659
1660 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001661 * Get the type allowlist flag value.
1662 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1663 */
1664 @Nullable
1665 public String getTypeAllowlistFlags() {
1666 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1667 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1668 }
1669
1670 /**
1671 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1672 */
1673 public boolean isFeatureEnabled(Context context, String feature) {
1674 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1675 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1676 }
1677
1678 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001679 * @see MdnsDiscoveryManager
1680 */
1681 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001682 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001683 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1684 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001685 }
1686
1687 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001688 * @see MdnsAdvertiser
1689 */
1690 public MdnsAdvertiser makeMdnsAdvertiser(
1691 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001692 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1693 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001694 }
1695
1696 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001697 * @see MdnsSocketProvider
1698 */
Paul Hu14667de2023-04-17 22:42:47 +08001699 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001700 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1701 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1702 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1703 }
1704
1705 /**
1706 * @see DeviceConfig#getInt(String, String, int)
1707 */
1708 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1709 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1710 }
1711
1712 /**
1713 * @see Binder#getCallingUid()
1714 */
1715 public int getCallingUid() {
1716 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001717 }
Paul Hu777ed052023-06-19 13:35:15 +00001718
1719 /**
1720 * @see NetworkNsdReportedMetrics
1721 */
1722 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1723 boolean isLegacy, int clientId) {
1724 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1725 }
1726
1727 /**
1728 * @see MdnsUtils.Clock
1729 */
1730 public Clock makeClock() {
1731 return new Clock();
1732 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001733 }
1734
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001735 /**
1736 * Return whether a type is allowlisted to use the Java backend.
1737 * @param type The service type
1738 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1739 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1740 */
1741 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1742 @NonNull String flagPrefix) {
1743 if (type == null) return false;
1744 final String typesConfig = mDeps.getTypeAllowlistFlags();
1745 if (TextUtils.isEmpty(typesConfig)) return false;
1746
1747 final String mappingPrefix = type + ":";
1748 String mappedFlag = null;
1749 for (String mapping : TextUtils.split(typesConfig, ",")) {
1750 if (mapping.startsWith(mappingPrefix)) {
1751 mappedFlag = mapping.substring(mappingPrefix.length());
1752 break;
1753 }
1754 }
1755
1756 if (mappedFlag == null) return false;
1757
1758 return mDeps.isFeatureEnabled(mContext,
1759 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1760 }
1761
1762 private boolean useDiscoveryManagerForType(@Nullable String type) {
1763 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1764 }
1765
1766 private boolean useAdvertiserForType(@Nullable String type) {
1767 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1768 }
1769
paulhu1b35e822022-04-08 14:48:41 +08001770 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001771 HandlerThread thread = new HandlerThread(TAG);
1772 thread.start();
1773 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001774 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001775 return service;
1776 }
1777
paulhu2b9ed952022-02-10 21:58:32 +08001778 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1779 private final StateMachine mStateMachine;
1780
1781 MDnsEventCallback(StateMachine sm) {
1782 mStateMachine = sm;
1783 }
1784
1785 @Override
1786 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1787 mStateMachine.sendMessage(
1788 MDNS_SERVICE_EVENT, status.result, status.id, status);
1789 }
1790
1791 @Override
1792 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1793 mStateMachine.sendMessage(
1794 MDNS_SERVICE_EVENT, status.result, status.id, status);
1795 }
1796
1797 @Override
1798 public void onServiceResolutionStatus(final ResolutionInfo status) {
1799 mStateMachine.sendMessage(
1800 MDNS_SERVICE_EVENT, status.result, status.id, status);
1801 }
1802
1803 @Override
1804 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1805 mStateMachine.sendMessage(
1806 MDNS_SERVICE_EVENT, status.result, status.id, status);
1807 }
1808
1809 @Override
1810 public int getInterfaceVersion() throws RemoteException {
1811 return this.VERSION;
1812 }
1813
1814 @Override
1815 public String getInterfaceHash() throws RemoteException {
1816 return this.HASH;
1817 }
1818 }
1819
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001820 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1821 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1822 final int count = mOffloadEngines.beginBroadcast();
1823 try {
1824 for (int i = 0; i < count; i++) {
1825 final OffloadEngineInfo offloadEngineInfo =
1826 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1827 final String interfaceName = offloadEngineInfo.mInterfaceName;
1828 if (!targetInterfaceName.equals(interfaceName)
1829 || ((offloadEngineInfo.mOffloadType
1830 & offloadServiceInfo.getOffloadType()) == 0)) {
1831 continue;
1832 }
1833 try {
1834 if (isRemove) {
1835 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1836 offloadServiceInfo);
1837 } else {
1838 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1839 offloadServiceInfo);
1840 }
1841 } catch (RemoteException e) {
1842 // Can happen in regular cases, do not log a stacktrace
1843 Log.i(TAG, "Failed to send offload callback, remote died", e);
1844 }
1845 }
1846 } finally {
1847 mOffloadEngines.finishBroadcast();
1848 }
1849 }
1850
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001851 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001852 // TODO: add a callback to notify when a service is being added on each interface (as soon
1853 // as probing starts), and call mOffloadCallbacks. This callback is for
1854 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1855
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001856 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001857 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1858 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1859 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001860 if (clientInfo == null) return;
1861
Paul Hud44e1b72023-06-16 02:07:42 +00001862 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1863 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001864
1865 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1866 // historical behavior.
1867 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001868 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001869 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1870 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001871 }
1872
1873 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001874 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1875 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001876 if (clientInfo == null) return;
1877
Paul Hud44e1b72023-06-16 02:07:42 +00001878 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1879 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001880 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1881 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001882 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001883 }
1884
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001885 @Override
1886 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1887 @NonNull OffloadServiceInfo offloadServiceInfo) {
1888 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1889 }
1890
1891 @Override
1892 public void onOffloadStop(@NonNull String interfaceName,
1893 @NonNull OffloadServiceInfo offloadServiceInfo) {
1894 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1895 }
1896
Paul Hud44e1b72023-06-16 02:07:42 +00001897 private ClientInfo getClientInfoOrLog(int transactionId) {
1898 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001899 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001900 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001901 }
1902 return clientInfo;
1903 }
1904
Paul Hud44e1b72023-06-16 02:07:42 +00001905 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1906 final int clientRequestId = info.getClientRequestId(transactionId);
1907 if (clientRequestId < 0) {
1908 Log.e(TAG, String.format(
1909 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001910 }
Paul Hud44e1b72023-06-16 02:07:42 +00001911 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001912 }
1913 }
1914
Paul Hu2e0a88c2023-03-09 16:05:01 +08001915 private static class ConnectorArgs {
1916 @NonNull public final NsdServiceConnector connector;
1917 @NonNull public final INsdManagerCallback callback;
1918 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001919 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001920
1921 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001922 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001923 this.connector = connector;
1924 this.callback = callback;
1925 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001926 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001927 }
1928 }
1929
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001930 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001931 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001932 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001933 final int uid = mDeps.getCallingUid();
1934 if (cb == null) {
1935 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1936 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001937 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001938 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001939 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001940 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001941 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001942 }
1943
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001944 private static class ListenerArgs {
1945 public final NsdServiceConnector connector;
1946 public final NsdServiceInfo serviceInfo;
1947 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1948 this.connector = connector;
1949 this.serviceInfo = serviceInfo;
1950 }
1951 }
1952
1953 private class NsdServiceConnector extends INsdServiceConnector.Stub
1954 implements IBinder.DeathRecipient {
1955 @Override
1956 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1957 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1958 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1959 new ListenerArgs(this, serviceInfo)));
1960 }
1961
1962 @Override
1963 public void unregisterService(int listenerKey) {
1964 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1965 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1966 new ListenerArgs(this, null)));
1967 }
1968
1969 @Override
1970 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1971 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1972 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1973 new ListenerArgs(this, serviceInfo)));
1974 }
1975
1976 @Override
1977 public void stopDiscovery(int listenerKey) {
1978 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1979 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1980 }
1981
1982 @Override
1983 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1984 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1985 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1986 new ListenerArgs(this, serviceInfo)));
1987 }
1988
1989 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001990 public void stopResolution(int listenerKey) {
1991 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1992 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1993 }
1994
1995 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001996 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1997 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1998 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1999 new ListenerArgs(this, serviceInfo)));
2000 }
2001
2002 @Override
2003 public void unregisterServiceInfoCallback(int listenerKey) {
2004 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2005 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2006 new ListenerArgs(this, null)));
2007 }
2008
2009 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002010 public void startDaemon() {
2011 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2012 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2013 }
2014
2015 @Override
2016 public void binderDied() {
2017 mNsdStateMachine.sendMessage(
2018 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002019
2020 }
2021
2022 @Override
2023 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2024 @OffloadEngine.OffloadCapability long offloadCapabilities,
2025 @OffloadEngine.OffloadType long offloadTypes) {
2026 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2027 // it may not be possible for all the callers of this API to have it.
2028 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2029 Objects.requireNonNull(ifaceName);
2030 Objects.requireNonNull(cb);
2031 mNsdStateMachine.sendMessage(
2032 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2033 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2034 offloadTypes)));
2035 }
2036
2037 @Override
2038 public void unregisterOffloadEngine(IOffloadEngine cb) {
2039 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2040 // it may not be possible for all the callers of this API to have it.
2041 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2042 Objects.requireNonNull(cb);
2043 mNsdStateMachine.sendMessage(
2044 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002045 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002046 }
2047
Hugo Benichi912db992017-04-24 16:41:03 +09002048 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002049 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002050 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002051 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2052 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002053 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002054 }
2055
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002056 private int getUniqueId() {
2057 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2058 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002059 }
2060
Paul Hud44e1b72023-06-16 02:07:42 +00002061 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002062 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002063 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002064 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002065 String name = service.getServiceName();
2066 String type = service.getServiceType();
2067 int port = service.getPort();
2068 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002069 final int registerInterface = getNetworkInterfaceIndex(service);
2070 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002071 Log.e(TAG, "Interface to register service on not found");
2072 return false;
2073 }
Paul Hud44e1b72023-06-16 02:07:42 +00002074 return mMDnsManager.registerService(
2075 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002076 }
2077
Paul Hud44e1b72023-06-16 02:07:42 +00002078 private boolean unregisterService(int transactionId) {
2079 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002080 }
2081
Paul Hud44e1b72023-06-16 02:07:42 +00002082 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002083 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002084 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2085 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002086 Log.e(TAG, "Interface to discover service on not found");
2087 return false;
2088 }
Paul Hud44e1b72023-06-16 02:07:42 +00002089 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002090 }
2091
Paul Hud44e1b72023-06-16 02:07:42 +00002092 private boolean stopServiceDiscovery(int transactionId) {
2093 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002094 }
2095
Paul Hud44e1b72023-06-16 02:07:42 +00002096 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002097 final String name = service.getServiceName();
2098 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002099 final int resolveInterface = getNetworkInterfaceIndex(service);
2100 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002101 Log.e(TAG, "Interface to resolve service on not found");
2102 return false;
2103 }
Paul Hud44e1b72023-06-16 02:07:42 +00002104 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002105 }
2106
2107 /**
2108 * Guess the interface to use to resolve or discover a service on a specific network.
2109 *
2110 * This is an imperfect guess, as for example the network may be gone or not yet fully
2111 * registered. This is fine as failing is correct if the network is gone, and a client
2112 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2113 * this is to support the legacy mdnsresponder implementation, which historically resolved
2114 * services on an unspecified network.
2115 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002116 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2117 final Network network = serviceInfo.getNetwork();
2118 if (network == null) {
2119 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2120 // provided by NsdService from discovery results, and the service was found on an
2121 // interface that has no app-usable Network).
2122 if (serviceInfo.getInterfaceIndex() != 0) {
2123 return serviceInfo.getInterfaceIndex();
2124 }
2125 return IFACE_IDX_ANY;
2126 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002127
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002128 String interfaceName = getNetworkInterfaceName(network);
2129 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002130 return IFACE_IDX_ANY;
2131 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002132 return getNetworkInterfaceIndexByName(interfaceName);
2133 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002134
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002135 private String getNetworkInterfaceName(@Nullable Network network) {
2136 if (network == null) {
2137 return null;
2138 }
2139 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2140 if (cm == null) {
2141 Log.wtf(TAG, "No ConnectivityManager");
2142 return null;
2143 }
2144 final LinkProperties lp = cm.getLinkProperties(network);
2145 if (lp == null) {
2146 return null;
2147 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002148 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002149 return lp.getInterfaceName();
2150 }
2151
2152 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002153 final NetworkInterface iface;
2154 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002155 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002156 } catch (SocketException e) {
2157 Log.e(TAG, "Error querying interface", e);
2158 return IFACE_IDX_ANY;
2159 }
2160
2161 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002162 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002163 return IFACE_IDX_ANY;
2164 }
2165
2166 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002167 }
2168
Paul Hud44e1b72023-06-16 02:07:42 +00002169 private boolean stopResolveService(int transactionId) {
2170 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002171 }
2172
Paul Hud44e1b72023-06-16 02:07:42 +00002173 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2174 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002175 }
2176
Paul Hud44e1b72023-06-16 02:07:42 +00002177 private boolean stopGetAddrInfo(int transactionId) {
2178 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002179 }
2180
2181 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002182 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2183 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002184
Paul Hub2e67d32023-04-18 05:50:14 +00002185 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2186 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002187 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002188
2189 // Dump service and clients logs
2190 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002191 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002192 pw.increaseIndent();
2193 mServiceLogs.reverseDump(pw);
2194 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002195 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002196
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002197 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002198 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002199 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002200 private int mFoundServiceCount = 0;
2201 private int mLostServiceCount = 0;
2202 private final Set<String> mServices = new ArraySet<>();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002203
Paul Hu812e9212023-06-20 06:24:53 +00002204 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002205 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002206 mStartTimeMs = startTimeMs;
2207 }
2208
Paul Hu812e9212023-06-20 06:24:53 +00002209 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002210 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002211 }
Paul Hu812e9212023-06-20 06:24:53 +00002212
2213 public void onServiceFound(String serviceName) {
2214 mFoundServiceCount++;
2215 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2216 mServices.add(serviceName);
2217 }
2218 }
2219
2220 public void onServiceLost() {
2221 mLostServiceCount++;
2222 }
2223
2224 public int getFoundServiceCount() {
2225 return mFoundServiceCount;
2226 }
2227
2228 public int getLostServiceCount() {
2229 return mLostServiceCount;
2230 }
2231
2232 public int getServicesCount() {
2233 return mServices.size();
2234 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002235 }
2236
2237 private static class LegacyClientRequest extends ClientRequest {
2238 private final int mRequestCode;
2239
Paul Hu812e9212023-06-20 06:24:53 +00002240 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2241 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002242 mRequestCode = requestCode;
2243 }
2244 }
2245
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002246 private abstract static class JavaBackendClientRequest extends ClientRequest {
2247 @Nullable
2248 private final Network mRequestedNetwork;
2249
Paul Hu777ed052023-06-19 13:35:15 +00002250 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002251 long startTimeMs) {
2252 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002253 mRequestedNetwork = requestedNetwork;
2254 }
2255
2256 @Nullable
2257 public Network getRequestedNetwork() {
2258 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002259 }
2260 }
2261
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002262 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002263 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002264 long startTimeMs) {
2265 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002266 }
2267 }
2268
2269 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002270 @NonNull
2271 private final MdnsListener mListener;
2272
Paul Hud44e1b72023-06-16 02:07:42 +00002273 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002274 @Nullable Network requestedNetwork, long startTimeMs) {
2275 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002276 mListener = listener;
2277 }
2278 }
2279
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002280 /* Information tracked per client */
2281 private class ClientInfo {
2282
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002283 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002284 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002285 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002286 private NsdServiceInfo mResolvedService;
2287
Paul Hud44e1b72023-06-16 02:07:42 +00002288 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002289 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002290
Luke Huangf7277ed2021-07-12 21:15:10 +08002291 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002292 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002293 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002294 // The flag of using java backend if the client's target SDK >= U
2295 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002296 // Store client logs
2297 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002298 // Report the nsd metrics data
2299 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002300
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002301 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002302 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002303 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002304 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002305 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002306 mClientLogs = sharedLog;
2307 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002308 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002309 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002310
2311 @Override
2312 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002313 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002314 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002315 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002316 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2317 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002318 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002319 int clientRequestId = mClientRequests.keyAt(i);
2320 sb.append("clientRequestId ")
2321 .append(clientRequestId)
2322 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002323 .append(" type ").append(
2324 mClientRequests.valueAt(i).getClass().getSimpleName())
2325 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002326 }
2327 return sb.toString();
2328 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002329
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002330 private boolean isPreSClient() {
2331 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002332 }
2333
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002334 private void setPreSClient() {
2335 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002336 }
2337
Paul Hu812e9212023-06-20 06:24:53 +00002338 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002339 final MdnsListener listener =
2340 ((DiscoveryManagerRequest) request).mListener;
2341 mMdnsDiscoveryManager.unregisterListener(
2342 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002343 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002344 }
2345
Dave Plattfeff2af2014-03-07 14:48:22 -08002346 // Remove any pending requests from the global map when we get rid of a client,
2347 // and send cancellations to the daemon.
2348 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002349 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002350 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002351 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002352 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002353 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002354 final int transactionId = request.mTransactionId;
2355 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002356 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002357 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2358 + " transactionId " + transactionId
2359 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002360 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002361
2362 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002363 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2364 if (listener instanceof DiscoveryListener) {
2365 mMetrics.reportServiceDiscoveryStop(transactionId,
2366 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2367 request.getFoundServiceCount(),
2368 request.getLostServiceCount(),
2369 request.getServicesCount());
2370 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002371 continue;
2372 }
2373
2374 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002375 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002376 mMetrics.reportServiceUnregistration(transactionId,
2377 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002378 continue;
2379 }
2380
2381 if (!(request instanceof LegacyClientRequest)) {
2382 throw new IllegalStateException("Unknown request type: " + request.getClass());
2383 }
2384
2385 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002386 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002387 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002388 mMetrics.reportServiceDiscoveryStop(transactionId,
2389 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2390 request.getFoundServiceCount(),
2391 request.getLostServiceCount(),
2392 request.getServicesCount());
Dave Plattfeff2af2014-03-07 14:48:22 -08002393 break;
2394 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002395 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002396 break;
2397 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002398 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002399 mMetrics.reportServiceUnregistration(transactionId,
2400 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002401 break;
2402 default:
2403 break;
2404 }
2405 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002406 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002407 updateMulticastLock();
2408 }
2409
2410 /**
2411 * Returns true if this client has any Java backend request that requests one of the given
2412 * networks.
2413 */
2414 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2415 for (int i = 0; i < mClientRequests.size(); i++) {
2416 final ClientRequest req = mClientRequests.valueAt(i);
2417 if (!(req instanceof JavaBackendClientRequest)) {
2418 continue;
2419 }
2420 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2421 .getRequestedNetwork();
2422 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2423 return true;
2424 }
2425 }
2426 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002427 }
2428
Paul Hud44e1b72023-06-16 02:07:42 +00002429 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2430 // transaction id, return the corresponding client request id.
2431 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002432 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002433 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002434 return mClientRequests.keyAt(i);
2435 }
Christopher Lane74411222014-04-25 18:39:07 -07002436 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002437 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002438 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002439
Paul Hub2e67d32023-04-18 05:50:14 +00002440 private void log(String message) {
2441 mClientLogs.log(message);
2442 }
2443
Paul Hu812e9212023-06-20 06:24:53 +00002444 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2445 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002446 try {
2447 mCb.onDiscoverServicesStarted(listenerKey, info);
2448 } catch (RemoteException e) {
2449 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2450 }
2451 }
Paul Hu812e9212023-06-20 06:24:53 +00002452 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2453 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2454 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002455
Paul Hu812e9212023-06-20 06:24:53 +00002456 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2457 long durationMs) {
2458 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002459 try {
2460 mCb.onDiscoverServicesFailed(listenerKey, error);
2461 } catch (RemoteException e) {
2462 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2463 }
2464 }
2465
Paul Hu812e9212023-06-20 06:24:53 +00002466 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2467 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002468 try {
2469 mCb.onServiceFound(listenerKey, info);
2470 } catch (RemoteException e) {
2471 Log.e(TAG, "Error calling onServiceFound(", e);
2472 }
2473 }
2474
Paul Hu812e9212023-06-20 06:24:53 +00002475 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2476 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002477 try {
2478 mCb.onServiceLost(listenerKey, info);
2479 } catch (RemoteException e) {
2480 Log.e(TAG, "Error calling onServiceLost(", e);
2481 }
2482 }
2483
2484 void onStopDiscoveryFailed(int listenerKey, int error) {
2485 try {
2486 mCb.onStopDiscoveryFailed(listenerKey, error);
2487 } catch (RemoteException e) {
2488 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2489 }
2490 }
2491
Paul Hu812e9212023-06-20 06:24:53 +00002492 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2493 mMetrics.reportServiceDiscoveryStop(
2494 request.mTransactionId,
2495 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2496 request.getFoundServiceCount(),
2497 request.getLostServiceCount(),
2498 request.getServicesCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002499 try {
2500 mCb.onStopDiscoverySucceeded(listenerKey);
2501 } catch (RemoteException e) {
2502 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2503 }
2504 }
2505
Paul Hu777ed052023-06-19 13:35:15 +00002506 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002507 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002508 }
2509
2510 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2511 long durationMs) {
2512 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002513 try {
2514 mCb.onRegisterServiceFailed(listenerKey, error);
2515 } catch (RemoteException e) {
2516 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2517 }
2518 }
2519
Paul Hu777ed052023-06-19 13:35:15 +00002520 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2521 long durationMs) {
2522 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002523 try {
2524 mCb.onRegisterServiceSucceeded(listenerKey, info);
2525 } catch (RemoteException e) {
2526 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2527 }
2528 }
2529
2530 void onUnregisterServiceFailed(int listenerKey, int error) {
2531 try {
2532 mCb.onUnregisterServiceFailed(listenerKey, error);
2533 } catch (RemoteException e) {
2534 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2535 }
2536 }
2537
Paul Hu777ed052023-06-19 13:35:15 +00002538 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2539 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002540 try {
2541 mCb.onUnregisterServiceSucceeded(listenerKey);
2542 } catch (RemoteException e) {
2543 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2544 }
2545 }
2546
2547 void onResolveServiceFailed(int listenerKey, int error) {
2548 try {
2549 mCb.onResolveServiceFailed(listenerKey, error);
2550 } catch (RemoteException e) {
2551 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2552 }
2553 }
2554
2555 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2556 try {
2557 mCb.onResolveServiceSucceeded(listenerKey, info);
2558 } catch (RemoteException e) {
2559 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2560 }
2561 }
Paul Hub58deb72022-12-26 09:24:42 +00002562
2563 void onStopResolutionFailed(int listenerKey, int error) {
2564 try {
2565 mCb.onStopResolutionFailed(listenerKey, error);
2566 } catch (RemoteException e) {
2567 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2568 }
2569 }
2570
2571 void onStopResolutionSucceeded(int listenerKey) {
2572 try {
2573 mCb.onStopResolutionSucceeded(listenerKey);
2574 } catch (RemoteException e) {
2575 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2576 }
2577 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002578
2579 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2580 try {
2581 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2582 } catch (RemoteException e) {
2583 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2584 }
2585 }
2586
2587 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2588 try {
2589 mCb.onServiceUpdated(listenerKey, info);
2590 } catch (RemoteException e) {
2591 Log.e(TAG, "Error calling onServiceUpdated", e);
2592 }
2593 }
2594
2595 void onServiceUpdatedLost(int listenerKey) {
2596 try {
2597 mCb.onServiceUpdatedLost(listenerKey);
2598 } catch (RemoteException e) {
2599 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2600 }
2601 }
2602
2603 void onServiceInfoCallbackUnregistered(int listenerKey) {
2604 try {
2605 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2606 } catch (RemoteException e) {
2607 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2608 }
2609 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002610 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002611}