blob: b975a1befd20705d3cc2198f8c8323d75797422f [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
Paul Hua6bc4632023-06-26 01:18:29 +0000268 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
269 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800270
271 @Override
272 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
273
274 @Override
275 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
276
277 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000278 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
279 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800280
281 @Override
282 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
283
284 @Override
285 public void onSearchStoppedWithError(int error) { }
286
287 @Override
288 public void onSearchFailedToStart() { }
289
290 @Override
291 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
292
293 @Override
294 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
295 }
296
297 private class DiscoveryListener extends MdnsListener {
298
Paul Hud44e1b72023-06-16 02:07:42 +0000299 DiscoveryListener(int clientRequestId, int transactionId,
300 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
301 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800302 }
303
304 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000305 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
306 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800307 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
308 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000309 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800310 }
311
312 @Override
313 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800314 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
315 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000316 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800317 }
318 }
319
Paul Hu75069ed2023-01-14 00:31:09 +0800320 private class ResolutionListener extends MdnsListener {
321
Paul Hud44e1b72023-06-16 02:07:42 +0000322 ResolutionListener(int clientRequestId, int transactionId,
323 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
324 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800325 }
326
327 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000328 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800329 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
330 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000331 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800332 }
333 }
334
Paul Hu30bd70d2023-02-07 13:20:56 +0000335 private class ServiceInfoListener extends MdnsListener {
336
Paul Hud44e1b72023-06-16 02:07:42 +0000337 ServiceInfoListener(int clientRequestId, int transactionId,
338 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
339 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000340 }
341
342 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000343 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
344 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000345 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
346 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000347 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000348 }
349
350 @Override
351 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
352 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
353 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000354 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000355 }
356
357 @Override
358 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
359 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
360 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000361 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000362 }
363 }
364
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900365 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
366 @Override
367 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
368 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
369 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
370 // filtering on such interfaces, so taking the multicast lock is not necessary to
371 // disable APF filtering of multicast.
372 if (socketNetwork == null
373 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
374 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
375 return;
376 }
377
378 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
379 updateMulticastLock();
380 }
381 }
382
383 @Override
384 public void onSocketDestroyed(@Nullable Network socketNetwork,
385 @NonNull MdnsInterfaceSocket socket) {
386 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
387 updateMulticastLock();
388 }
389 }
390 }
391
392 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
393 private final Handler mHandler;
394
395 private UidImportanceListener(Handler handler) {
396 mHandler = handler;
397 }
398
399 @Override
400 public void onUidImportance(int uid, int importance) {
401 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
402 }
403 }
404
405 private void handleUidImportanceChanged(int uid, int importance) {
406 // Lower importance values are more "important"
407 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
408 ? mRunningAppActiveUids.add(uid)
409 : mRunningAppActiveUids.remove(uid);
410 if (modified) {
411 updateMulticastLock();
412 }
413 }
414
415 /**
416 * Take or release the lock based on updated internal state.
417 *
418 * This determines whether the lock needs to be held based on
419 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
420 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
421 * updated.
422 */
423 private void updateMulticastLock() {
424 final int needsLockUid = getMulticastLockNeededUid();
425 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
426 final WifiManager wm = mContext.getSystemService(WifiManager.class);
427 if (wm == null) {
428 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
429 return;
430 }
431 mHeldMulticastLock = wm.createMulticastLock(TAG);
432 mHeldMulticastLock.acquire();
433 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
434 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
435 mHeldMulticastLock.release();
436 mHeldMulticastLock = null;
437 mServiceLogs.log("Released multicast lock");
438 }
439 }
440
441 /**
442 * @return The UID of an app requiring the multicast lock, or -1 if none.
443 */
444 private int getMulticastLockNeededUid() {
445 if (mWifiLockRequiredNetworks.size() == 0) {
446 // Return early if NSD is not active, or not on any relevant network
447 return -1;
448 }
Paul Hud44e1b72023-06-16 02:07:42 +0000449 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
450 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900451 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
452 // Ignore non-active UIDs
453 continue;
454 }
455
456 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
457 return clientInfo.mUid;
458 }
459 }
460 return -1;
461 }
462
Paul Hu019621e2023-01-13 23:26:49 +0800463 /**
464 * Data class of mdns service callback information.
465 */
466 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000467 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800468 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800469 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000470 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800471
Paul Hud44e1b72023-06-16 02:07:42 +0000472 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000473 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
474 }
475
476 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo,
477 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000478 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800479 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000480 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800481 }
482 }
483
Irfan Sheriff75006652012-04-17 23:15:29 -0700484 private class NsdStateMachine extends StateMachine {
485
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700486 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700487 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700488
489 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700490 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900491 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700492 }
493
Luke Huang92860f92021-06-23 06:29:30 +0000494 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800495 if (mIsDaemonStarted) {
496 if (DBG) Log.d(TAG, "Daemon is already started.");
497 return;
498 }
499 mMDnsManager.registerEventListener(mMDnsEventCallback);
500 mMDnsManager.startDaemon();
501 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000502 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000503 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000504 }
505
paulhu2b9ed952022-02-10 21:58:32 +0800506 private void maybeStopDaemon() {
507 if (!mIsDaemonStarted) {
508 if (DBG) Log.d(TAG, "Daemon has not been started.");
509 return;
510 }
511 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
512 mMDnsManager.stopDaemon();
513 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000514 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800515 }
516
Luke Huang92860f92021-06-23 06:29:30 +0000517 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000518 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000519 }
520
521 private void scheduleStop() {
522 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
523 }
524 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800525 // The native daemon should stay alive and can't be cleanup
526 // if any legacy client connected.
527 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000528 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000529 }
530 }
531
Luke Huang92860f92021-06-23 06:29:30 +0000532 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000533 this.removeMessages(NsdManager.DAEMON_CLEANUP);
534 }
535
Paul Hu23fa2022023-01-13 22:57:24 +0800536 private void maybeStartMonitoringSockets() {
537 if (mIsMonitoringSocketsStarted) {
538 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
539 return;
540 }
541
542 mMdnsSocketProvider.startMonitoringSockets();
543 mIsMonitoringSocketsStarted = true;
544 }
545
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900546 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
547 if (!mIsMonitoringSocketsStarted) return;
548 if (isAnyRequestActive()) return;
549
Paul Hu58f20602023-02-18 11:41:07 +0800550 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800551 mIsMonitoringSocketsStarted = false;
552 }
553
Hugo Benichi803a2f02017-04-24 11:35:06 +0900554 NsdStateMachine(String name, Handler handler) {
555 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700556 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700557 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800558 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900559 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700560 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700561 }
562
563 class DefaultState extends State {
564 @Override
565 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900566 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000567 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700568 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900569 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800570 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
571 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900572 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800573 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000574 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000575 final NetworkNsdReportedMetrics metrics =
576 mDeps.makeNetworkNsdReportedMetrics(
577 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900578 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000579 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800580 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900581 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000582 Log.w(TAG, "Client request id " + clientRequestId
583 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700584 }
585 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900586 case NsdManager.UNREGISTER_CLIENT:
587 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
588 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800589 if (cInfo != null) {
590 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900591 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800592 mLegacyClientCount -= 1;
593 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800594 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900595 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800596 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700597 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900599 cInfo = getClientInfoForReply(msg);
600 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000601 cInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000602 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700604 break;
605 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 cInfo = getClientInfoForReply(msg);
607 if (cInfo != null) {
608 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000609 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900610 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700611 break;
612 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900613 cInfo = getClientInfoForReply(msg);
614 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000615 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000616 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900617 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 break;
619 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 cInfo = getClientInfoForReply(msg);
621 if (cInfo != null) {
622 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000623 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900624 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700625 break;
626 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900627 cInfo = getClientInfoForReply(msg);
628 if (cInfo != null) {
Paul Hua6bc4632023-06-26 01:18:29 +0000629 cInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000630 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900631 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700632 break;
Paul Hub58deb72022-12-26 09:24:42 +0000633 case NsdManager.STOP_RESOLUTION:
634 cInfo = getClientInfoForReply(msg);
635 if (cInfo != null) {
636 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000637 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000638 }
639 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000640 case NsdManager.REGISTER_SERVICE_CALLBACK:
641 cInfo = getClientInfoForReply(msg);
642 if (cInfo != null) {
643 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000644 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000645 }
646 break;
Luke Huang05298582021-06-13 16:52:05 +0000647 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800648 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000649 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800650 // This event should be only sent by the legacy (target SDK < S) clients.
651 // Mark the sending client as legacy.
652 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900653 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800654 if (cInfo != null) {
655 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900656 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800657 mLegacyClientCount += 1;
658 maybeStartDaemon();
659 }
660 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700661 default:
paulhub2225702021-11-17 09:35:33 +0800662 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700663 return NOT_HANDLED;
664 }
665 return HANDLED;
666 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900667
668 private ClientInfo getClientInfoForReply(Message msg) {
669 final ListenerArgs args = (ListenerArgs) msg.obj;
670 return mClients.get(args.connector);
671 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700672 }
673
Irfan Sheriff75006652012-04-17 23:15:29 -0700674 class EnabledState extends State {
675 @Override
676 public void enter() {
677 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700678 }
679
680 @Override
681 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000682 // TODO: it is incorrect to stop the daemon without expunging all requests
683 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000684 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700685 }
686
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700687 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900688 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800689 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700690 return true;
691 }
692 return false;
693 }
694
Paul Hud44e1b72023-06-16 02:07:42 +0000695 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000696 ClientInfo clientInfo, int what, long startTimeMs) {
697 clientInfo.mClientRequests.put(clientRequestId,
698 new LegacyClientRequest(transactionId, what, startTimeMs));
Paul Hud44e1b72023-06-16 02:07:42 +0000699 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000700 // Remove the cleanup event because here comes a new request.
701 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700702 }
703
Paul Hud44e1b72023-06-16 02:07:42 +0000704 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900705 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000706 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000707 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000708 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900709 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800710 }
711
Paul Hud44e1b72023-06-16 02:07:42 +0000712 private void removeRequestMap(
713 int clientRequestId, int transactionId, ClientInfo clientInfo) {
714 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900715 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000716 clientInfo.mClientRequests.remove(clientRequestId);
717 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900718
719 if (existing instanceof LegacyClientRequest) {
720 maybeScheduleStop();
721 } else {
722 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900723 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900724 }
725 }
726
Paul Hud44e1b72023-06-16 02:07:42 +0000727 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900728 MdnsListener listener, ClientInfo clientInfo,
729 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000730 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000731 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000732 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900733 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800734 }
735
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900736 /**
737 * Truncate a service name to up to 63 UTF-8 bytes.
738 *
739 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
740 * names used in registerService follows historical behavior (see mdnsresponder
741 * handle_regservice_request).
742 */
743 @NonNull
744 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900745 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800746 }
747
Paul Hud44e1b72023-06-16 02:07:42 +0000748 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
749 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800750 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000751 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800752 }
753
Irfan Sheriff75006652012-04-17 23:15:29 -0700754 @Override
755 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900756 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000757 final int transactionId;
758 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900759 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900760 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700761 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800762 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800763 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900764 args = (ListenerArgs) msg.obj;
765 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000766 // If the binder death notification for a INsdManagerCallback was received
767 // before any calls are received by NsdService, the clientInfo would be
768 // cleared and cause NPE. Add a null check here to prevent this corner case.
769 if (clientInfo == null) {
770 Log.e(TAG, "Unknown connector in discovery");
771 break;
772 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700773
774 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000775 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000776 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700777 break;
778 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700779
Paul Hu23fa2022023-01-13 22:57:24 +0800780 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000781 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900782 final Pair<String, String> typeAndSubtype =
783 parseTypeAndSubtype(info.getServiceType());
784 final String serviceType = typeAndSubtype == null
785 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800786 if (clientInfo.mUseJavaBackend
787 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900788 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800789 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000790 clientInfo.onDiscoverServicesFailedImmediately(
791 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800792 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700793 }
Paul Hu23fa2022023-01-13 22:57:24 +0800794
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900795 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800796 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000797 final MdnsListener listener = new DiscoveryListener(clientRequestId,
798 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900799 final MdnsSearchOptions.Builder optionsBuilder =
800 MdnsSearchOptions.newBuilder()
801 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900802 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900803 .setIsPassiveMode(true);
804 if (typeAndSubtype.second != null) {
805 // The parsing ensures subtype starts with an underscore.
806 // MdnsSearchOptions expects the underscore to not be present.
807 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
808 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900809 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900810 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000811 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
812 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000813 clientInfo.onDiscoverServicesStarted(
814 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000815 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000816 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700817 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800818 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000819 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800820 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000821 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800822 + info.getServiceType());
823 }
Paul Hua6bc4632023-06-26 01:18:29 +0000824 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
825 msg.what, mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000826 clientInfo.onDiscoverServicesStarted(
827 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800828 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000829 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000830 clientInfo.onDiscoverServicesFailedImmediately(
831 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800832 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700833 }
834 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800835 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900836 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800837 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900838 args = (ListenerArgs) msg.obj;
839 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000840 // If the binder death notification for a INsdManagerCallback was received
841 // before any calls are received by NsdService, the clientInfo would be
842 // cleared and cause NPE. Add a null check here to prevent this corner case.
843 if (clientInfo == null) {
844 Log.e(TAG, "Unknown connector in stop discovery");
845 break;
846 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700847
Paul Hud44e1b72023-06-16 02:07:42 +0000848 final ClientRequest request =
849 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900850 if (request == null) {
851 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700852 break;
853 }
Paul Hud44e1b72023-06-16 02:07:42 +0000854 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900855 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
856 // point, so this needs to check the type of the original request to
857 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900858 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000859 stopDiscoveryManagerRequest(
860 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000861 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000862 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700863 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000864 removeRequestMap(clientRequestId, transactionId, clientInfo);
865 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000866 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800867 } else {
868 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000869 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800870 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700871 }
872 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900873 }
874 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800875 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900876 args = (ListenerArgs) msg.obj;
877 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000878 // If the binder death notification for a INsdManagerCallback was received
879 // before any calls are received by NsdService, the clientInfo would be
880 // cleared and cause NPE. Add a null check here to prevent this corner case.
881 if (clientInfo == null) {
882 Log.e(TAG, "Unknown connector in registration");
883 break;
884 }
885
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700886 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000887 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000888 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700889 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700890 }
891
Paul Hud44e1b72023-06-16 02:07:42 +0000892 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900893 final NsdServiceInfo serviceInfo = args.serviceInfo;
894 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900895 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
896 final String registerServiceType = typeSubtype == null
897 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800898 if (clientInfo.mUseJavaBackend
899 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900900 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900901 if (registerServiceType == null) {
902 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000903 clientInfo.onRegisterServiceFailedImmediately(
904 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900905 break;
906 }
907 serviceInfo.setServiceType(registerServiceType);
908 serviceInfo.setServiceName(truncateServiceName(
909 serviceInfo.getServiceName()));
910
911 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900912 // TODO: pass in the subtype as well. Including the subtype in the
913 // service type would generate service instance names like
914 // Name._subtype._sub._type._tcp, which is incorrect
915 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000916 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
917 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900918 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700919 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900920 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000921 if (registerService(transactionId, serviceInfo)) {
922 if (DBG) {
923 Log.d(TAG, "Register " + clientRequestId
924 + " " + transactionId);
925 }
Paul Hua6bc4632023-06-26 01:18:29 +0000926 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
927 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900928 // Return success after mDns reports success
929 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000930 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000931 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000932 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900933 }
934
Irfan Sheriff75006652012-04-17 23:15:29 -0700935 }
936 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900937 }
938 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800939 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900940 args = (ListenerArgs) msg.obj;
941 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000942 // If the binder death notification for a INsdManagerCallback was received
943 // before any calls are received by NsdService, the clientInfo would be
944 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900945 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800946 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700947 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700948 }
Paul Hud44e1b72023-06-16 02:07:42 +0000949 final ClientRequest request =
950 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900951 if (request == null) {
952 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
953 break;
954 }
Paul Hud44e1b72023-06-16 02:07:42 +0000955 transactionId = request.mTransactionId;
956 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900957
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900958 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
959 // so this needs to check the type of the original request to unregister
960 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000961 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900962 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000963 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000964 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +0000965 request.calculateRequestDurationMs(stopTimeMs));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700966 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000967 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000968 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +0000969 transactionId,
970 request.calculateRequestDurationMs(stopTimeMs));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900971 } else {
972 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000973 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900974 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700975 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700976 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900977 }
Paul Hu75069ed2023-01-14 00:31:09 +0800978 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800979 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900980 args = (ListenerArgs) msg.obj;
981 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000982 // If the binder death notification for a INsdManagerCallback was received
983 // before any calls are received by NsdService, the clientInfo would be
984 // cleared and cause NPE. Add a null check here to prevent this corner case.
985 if (clientInfo == null) {
986 Log.e(TAG, "Unknown connector in resolution");
987 break;
988 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700989
Paul Hu75069ed2023-01-14 00:31:09 +0800990 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000991 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900992 final Pair<String, String> typeSubtype =
993 parseTypeAndSubtype(info.getServiceType());
994 final String serviceType = typeSubtype == null
995 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800996 if (clientInfo.mUseJavaBackend
997 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900998 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800999 if (serviceType == null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001000 clientInfo.onResolveServiceFailedImmediately(
1001 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001002 break;
1003 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001004 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001005
1006 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001007 final MdnsListener listener = new ResolutionListener(clientRequestId,
1008 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001009 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1010 .setNetwork(info.getNetwork())
1011 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001012 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001013 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001014 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001015 mMdnsDiscoveryManager.registerListener(
1016 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001017 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1018 listener, clientInfo, info.getNetwork());
1019 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001020 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001021 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001022 if (clientInfo.mResolvedService != null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001023 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001024 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001025 break;
1026 }
1027
1028 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001029 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001030 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001031 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1032 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001033 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001034 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001035 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001036 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001037 }
1038 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001039 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001040 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001041 if (DBG) Log.d(TAG, "Stop service resolution");
1042 args = (ListenerArgs) msg.obj;
1043 clientInfo = mClients.get(args.connector);
1044 // If the binder death notification for a INsdManagerCallback was received
1045 // before any calls are received by NsdService, the clientInfo would be
1046 // cleared and cause NPE. Add a null check here to prevent this corner case.
1047 if (clientInfo == null) {
1048 Log.e(TAG, "Unknown connector in stop resolution");
1049 break;
1050 }
1051
Paul Hud44e1b72023-06-16 02:07:42 +00001052 final ClientRequest request =
1053 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001054 if (request == null) {
1055 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1056 break;
1057 }
Paul Hud44e1b72023-06-16 02:07:42 +00001058 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001059 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1060 // point, so this needs to check the type of the original request to
1061 // unregister instead of looking at the flag value.
1062 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001063 stopDiscoveryManagerRequest(
1064 request, clientRequestId, transactionId, clientInfo);
1065 clientInfo.onStopResolutionSucceeded(clientRequestId);
1066 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001067 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001068 removeRequestMap(clientRequestId, transactionId, clientInfo);
1069 if (stopResolveService(transactionId)) {
1070 clientInfo.onStopResolutionSucceeded(clientRequestId);
Paul Hue4f5f252023-02-16 21:13:47 +08001071 } else {
1072 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001073 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001074 }
1075 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001076 }
Paul Hub58deb72022-12-26 09:24:42 +00001077 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001078 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001079 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001080 if (DBG) Log.d(TAG, "Register a service callback");
1081 args = (ListenerArgs) msg.obj;
1082 clientInfo = mClients.get(args.connector);
1083 // If the binder death notification for a INsdManagerCallback was received
1084 // before any calls are received by NsdService, the clientInfo would be
1085 // cleared and cause NPE. Add a null check here to prevent this corner case.
1086 if (clientInfo == null) {
1087 Log.e(TAG, "Unknown connector in callback registration");
1088 break;
1089 }
1090
Paul Hu30bd70d2023-02-07 13:20:56 +00001091 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001092 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001093 final Pair<String, String> typeAndSubtype =
1094 parseTypeAndSubtype(info.getServiceType());
1095 final String serviceType = typeAndSubtype == null
1096 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001097 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001098 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001099 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001100 break;
1101 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001102 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001103
Paul Hu30bd70d2023-02-07 13:20:56 +00001104 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001105 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1106 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001107 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1108 .setNetwork(info.getNetwork())
1109 .setIsPassiveMode(true)
1110 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001111 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001112 .build();
1113 mMdnsDiscoveryManager.registerListener(
1114 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001115 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1116 clientInfo, info.getNetwork());
1117 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001118 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001119 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001120 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001121 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001122 if (DBG) Log.d(TAG, "Unregister a service callback");
1123 args = (ListenerArgs) msg.obj;
1124 clientInfo = mClients.get(args.connector);
1125 // If the binder death notification for a INsdManagerCallback was received
1126 // before any calls are received by NsdService, the clientInfo would be
1127 // cleared and cause NPE. Add a null check here to prevent this corner case.
1128 if (clientInfo == null) {
1129 Log.e(TAG, "Unknown connector in callback unregistration");
1130 break;
1131 }
1132
Paul Hud44e1b72023-06-16 02:07:42 +00001133 final ClientRequest request =
1134 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001135 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001136 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001137 break;
1138 }
Paul Hud44e1b72023-06-16 02:07:42 +00001139 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001140 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001141 stopDiscoveryManagerRequest(
1142 request, clientRequestId, transactionId, clientInfo);
1143 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1144 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001145 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001146 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001147 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001148 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001149 }
paulhu2b9ed952022-02-10 21:58:32 +08001150 case MDNS_SERVICE_EVENT:
1151 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001152 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001153 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001154 break;
Paul Hu019621e2023-01-13 23:26:49 +08001155 case MDNS_DISCOVERY_MANAGER_EVENT:
1156 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1157 return NOT_HANDLED;
1158 }
1159 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001160 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1161 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1162 // TODO: Limits the number of registrations created by a given class.
1163 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1164 offloadEngineInfo);
1165 // TODO: Sends all the existing OffloadServiceInfos back.
1166 break;
1167 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1168 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1169 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001170 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001171 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001172 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001173 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001174 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001175
Paul Hud44e1b72023-06-16 02:07:42 +00001176 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001177 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001178 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001179 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001180 Log.e(TAG, String.format(
1181 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001182 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001183 }
1184
1185 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001186 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1187 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001188 // This can happen because of race conditions. For example,
1189 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1190 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001191 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1192 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001193 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001194 }
Paul Hu812e9212023-06-20 06:24:53 +00001195 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1196 if (request == null) {
1197 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1198 return false;
1199 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001200 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001201 Log.d(TAG, String.format(
1202 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001203 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001204 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001205 case IMDnsEventListener.SERVICE_FOUND: {
1206 final DiscoveryInfo info = (DiscoveryInfo) obj;
1207 final String name = info.serviceName;
1208 final String type = info.registrationType;
1209 servInfo = new NsdServiceInfo(name, type);
1210 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001211 if (foundNetId == 0L) {
1212 // Ignore services that do not have a Network: they are not usable
1213 // by apps, as they would need privileged permissions to use
1214 // interfaces that do not have an associated Network.
1215 break;
1216 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001217 if (foundNetId == INetd.DUMMY_NET_ID) {
1218 // Ignore services on the dummy0 interface: they are only seen when
1219 // discovering locally advertised services, and are not reachable
1220 // through that interface.
1221 break;
1222 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001223 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001224
1225 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001226 break;
paulhu2b9ed952022-02-10 21:58:32 +08001227 }
1228 case IMDnsEventListener.SERVICE_LOST: {
1229 final DiscoveryInfo info = (DiscoveryInfo) obj;
1230 final String name = info.serviceName;
1231 final String type = info.registrationType;
1232 final int lostNetId = info.netId;
1233 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001234 // The network could be set to null (netId 0) if it was torn down when the
1235 // service is lost
1236 // TODO: avoid returning null in that case, possibly by remembering
1237 // found services on the same interface index and their network at the time
1238 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001239 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001240 break;
paulhu2b9ed952022-02-10 21:58:32 +08001241 }
1242 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001243 clientInfo.onDiscoverServicesFailed(clientRequestId,
1244 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1245 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001246 break;
paulhu2b9ed952022-02-10 21:58:32 +08001247 case IMDnsEventListener.SERVICE_REGISTERED: {
1248 final RegistrationInfo info = (RegistrationInfo) obj;
1249 final String name = info.serviceName;
1250 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001251 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001252 transactionId,
1253 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001254 break;
paulhu2b9ed952022-02-10 21:58:32 +08001255 }
1256 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001257 clientInfo.onRegisterServiceFailed(clientRequestId,
1258 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001259 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001260 break;
paulhu2b9ed952022-02-10 21:58:32 +08001261 case IMDnsEventListener.SERVICE_RESOLVED: {
1262 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001263 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001264 final String fullName = info.serviceFullName;
1265 while (index < fullName.length() && fullName.charAt(index) != '.') {
1266 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001267 ++index;
1268 }
1269 ++index;
1270 }
paulhu2b9ed952022-02-10 21:58:32 +08001271 if (index >= fullName.length()) {
1272 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001273 break;
1274 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001275
paulhube186602022-04-12 07:18:23 +00001276 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001277 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001278 String type = rest.replace(".local.", "");
1279
Paul Hu30bd70d2023-02-07 13:20:56 +00001280 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001281 serviceInfo.setServiceName(name);
1282 serviceInfo.setServiceType(type);
1283 serviceInfo.setPort(info.port);
1284 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001285 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001286
Paul Hud44e1b72023-06-16 02:07:42 +00001287 stopResolveService(transactionId);
1288 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001289
Paul Hud44e1b72023-06-16 02:07:42 +00001290 final int transactionId2 = getUniqueId();
1291 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1292 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001293 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001294 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001295 clientInfo.onResolveServiceFailed(clientRequestId,
1296 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1297 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001298 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001299 }
1300 break;
paulhu2b9ed952022-02-10 21:58:32 +08001301 }
1302 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001303 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001304 stopResolveService(transactionId);
1305 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001306 clientInfo.onResolveServiceFailed(clientRequestId,
1307 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1308 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001309 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001310 break;
paulhu2b9ed952022-02-10 21:58:32 +08001311 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001312 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001313 stopGetAddrInfo(transactionId);
1314 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001315 clientInfo.onResolveServiceFailed(clientRequestId,
1316 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1317 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001318 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001319 break;
paulhu2b9ed952022-02-10 21:58:32 +08001320 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001321 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001322 final GetAddressInfo info = (GetAddressInfo) obj;
1323 final String address = info.address;
1324 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001325 InetAddress serviceHost = null;
1326 try {
paulhu2b9ed952022-02-10 21:58:32 +08001327 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001328 } catch (UnknownHostException e) {
1329 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1330 }
1331
1332 // If the resolved service is on an interface without a network, consider it
1333 // as a failure: it would not be usable by apps as they would need
1334 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001335 if (netId != NETID_UNSET && serviceHost != null) {
1336 clientInfo.mResolvedService.setHost(serviceHost);
1337 setServiceNetworkForCallback(clientInfo.mResolvedService,
1338 netId, info.interfaceIdx);
1339 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001340 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001341 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001342 clientInfo.onResolveServiceFailed(clientRequestId,
1343 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1344 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001345 }
Paul Hud44e1b72023-06-16 02:07:42 +00001346 stopGetAddrInfo(transactionId);
1347 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001348 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001349 break;
paulhu2b9ed952022-02-10 21:58:32 +08001350 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001351 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001352 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001353 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001354 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001355 }
Paul Hu019621e2023-01-13 23:26:49 +08001356
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001357 @Nullable
1358 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1359 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001360 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001361 final String[] typeArray = serviceInfo.getServiceType();
1362 final String joinedType;
1363 if (typeArray.length == 0
1364 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1365 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1366 + Arrays.toString(typeArray));
1367 return null;
1368 } else {
1369 joinedType = TextUtils.join(".",
1370 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1371 }
1372 final String serviceType;
1373 switch (code) {
1374 case NsdManager.SERVICE_FOUND:
1375 case NsdManager.SERVICE_LOST:
1376 // For consistency with historical behavior, discovered service types have
1377 // a dot at the end.
1378 serviceType = joinedType + ".";
1379 break;
1380 case RESOLVE_SERVICE_SUCCEEDED:
1381 // For consistency with historical behavior, resolved service types have
1382 // a dot at the beginning.
1383 serviceType = "." + joinedType;
1384 break;
1385 default:
1386 serviceType = joinedType;
1387 break;
1388 }
Paul Hu019621e2023-01-13 23:26:49 +08001389 final String serviceName = serviceInfo.getServiceInstanceName();
1390 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1391 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001392 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1393 // network for Tethering interface. In other words, the network == null means the
1394 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001395 setServiceNetworkForCallback(
1396 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001397 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001398 serviceInfo.getInterfaceIndex());
1399 return servInfo;
1400 }
1401
1402 private boolean handleMdnsDiscoveryManagerEvent(
1403 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001404 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001405 if (clientInfo == null) {
1406 Log.e(TAG, String.format(
1407 "id %d for %d has no client mapping", transactionId, code));
1408 return false;
1409 }
1410
1411 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001412 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001413 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1414 // Errors are already logged if null
1415 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001416 mServiceLogs.log(String.format(
1417 "MdnsDiscoveryManager event code=%s transactionId=%d",
1418 NsdManager.nameOf(code), transactionId));
Paul Hu812e9212023-06-20 06:24:53 +00001419 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1420 if (request == null) {
1421 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1422 return false;
1423 }
Paul Hu019621e2023-01-13 23:26:49 +08001424 switch (code) {
1425 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001426 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001427 break;
1428 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001429 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001430 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001431 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1432 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001433 info.setPort(serviceInfo.getPort());
1434
1435 Map<String, String> attrs = serviceInfo.getAttributes();
1436 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1437 final String key = kv.getKey();
1438 try {
1439 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1440 } catch (IllegalArgumentException e) {
1441 Log.e(TAG, "Invalid attribute", e);
1442 }
1443 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001444 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001445 if (addresses.size() != 0) {
1446 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001447 request.setServiceFromCache(event.mIsServiceFromCache);
1448 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001449 } else {
1450 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001451 clientInfo.onResolveServiceFailed(clientRequestId,
1452 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1453 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001454 }
1455
1456 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001457 if (!(request instanceof DiscoveryManagerRequest)) {
1458 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1459 break;
1460 }
Paul Hud44e1b72023-06-16 02:07:42 +00001461 stopDiscoveryManagerRequest(
1462 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001463 break;
1464 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001465 case NsdManager.SERVICE_UPDATED: {
1466 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1467 info.setPort(serviceInfo.getPort());
1468
1469 Map<String, String> attrs = serviceInfo.getAttributes();
1470 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1471 final String key = kv.getKey();
1472 try {
1473 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1474 } catch (IllegalArgumentException e) {
1475 Log.e(TAG, "Invalid attribute", e);
1476 }
1477 }
1478
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001479 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001480 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001481 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001482 break;
1483 }
1484 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001485 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001486 break;
Paul Hu019621e2023-01-13 23:26:49 +08001487 default:
1488 return false;
1489 }
1490 return true;
1491 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001492 }
1493 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001494
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001495 @NonNull
1496 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1497 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1498 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1499 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1500 for (String ipv4Address : v4Addrs) {
1501 try {
1502 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1503 } catch (IllegalArgumentException e) {
1504 Log.wtf(TAG, "Invalid ipv4 address", e);
1505 }
1506 }
1507 for (String ipv6Address : v6Addrs) {
1508 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001509 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1510 ipv6Address);
1511 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1512 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001513 Log.wtf(TAG, "Invalid ipv6 address", e);
1514 }
1515 }
1516 return addresses;
1517 }
1518
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001519 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1520 switch (netId) {
1521 case NETID_UNSET:
1522 info.setNetwork(null);
1523 break;
1524 case INetd.LOCAL_NET_ID:
1525 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1526 // visible / usable for apps, so do not return it. Store the interface
1527 // index instead, so at least if the client tries to resolve the service
1528 // with that NsdServiceInfo, it will be done on the same interface.
1529 // If they recreate the NsdServiceInfo themselves, resolution would be
1530 // done on all interfaces as before T, which should also work.
1531 info.setNetwork(null);
1532 info.setInterfaceIndex(ifaceIdx);
1533 break;
1534 default:
1535 info.setNetwork(new Network(netId));
1536 }
1537 }
1538
paulhube186602022-04-12 07:18:23 +00001539 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1540 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1541 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1542 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1543 private String unescape(String s) {
1544 StringBuilder sb = new StringBuilder(s.length());
1545 for (int i = 0; i < s.length(); ++i) {
1546 char c = s.charAt(i);
1547 if (c == '\\') {
1548 if (++i >= s.length()) {
1549 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1550 break;
1551 }
1552 c = s.charAt(i);
1553 if (c != '.' && c != '\\') {
1554 if (i + 2 >= s.length()) {
1555 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1556 break;
1557 }
1558 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1559 + (s.charAt(i + 2) - '0'));
1560 i += 2;
1561 }
1562 }
1563 sb.append(c);
1564 }
1565 return sb.toString();
1566 }
1567
Paul Hu7445e3d2023-03-03 15:14:00 +08001568 /**
1569 * Check the given service type is valid and construct it to a service type
1570 * which can use for discovery / resolution service.
1571 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001572 * <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 +08001573 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1574 * underscore; they are alphanumerical characters or dashes or underscore, except the
1575 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1576 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001577 * <p>The subtype may also be specified with a comma after the service type, for example
1578 * _type._tcp,_subtype.
1579 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001580 * @param serviceType the request service type for discovery / resolution service
1581 * @return constructed service type or null if the given service type is invalid.
1582 */
1583 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001584 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001585 if (TextUtils.isEmpty(serviceType)) return null;
1586
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001587 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001588 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001589 // Optional leading subtype (_subtype._type._tcp)
1590 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1591 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1592 // Actual type (_type._tcp.local)
1593 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001594 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001595 // e.g. allow "_type._tcp.local."
1596 + "\\.?"
1597 // Optional subtype after comma, for "_type._tcp,_subtype" format
1598 + "(?:,(" + typeOrSubtypePattern + "))?"
1599 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001600 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1601 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001602 // Use the subtype either at the beginning or after the comma
1603 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1604 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001605 }
1606
Hugo Benichi803a2f02017-04-24 11:35:06 +09001607 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001608 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001609 this(ctx, handler, cleanupDelayMs, new Dependencies());
1610 }
1611
1612 @VisibleForTesting
1613 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001614 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001615 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001616 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001617 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001618 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1619 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001620 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001621
Paul Hu14667de2023-04-17 22:42:47 +08001622 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001623 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001624 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1625 // address events are received.
1626 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001627
1628 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1629 // startBootstrapServices).
1630 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1631 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1632 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1633 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1634 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1635 mRunningAppActiveImportanceCutoff);
1636
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001637 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001638 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1639 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001640 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001641 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001642 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1643 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001644 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001645 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001646 }
1647
1648 /**
1649 * Dependencies of NsdService, for injection in tests.
1650 */
1651 @VisibleForTesting
1652 public static class Dependencies {
1653 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001654 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001655 *
1656 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001657 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001658 */
1659 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001660 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1661 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001662 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001663 }
1664
1665 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001666 * Check whether the MdnsAdvertiser feature is enabled.
1667 *
1668 * @param context The global context information about an app environment.
1669 * @return true if the MdnsAdvertiser feature is enabled.
1670 */
1671 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001672 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1673 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1674 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001675 }
1676
1677 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001678 * Get the type allowlist flag value.
1679 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1680 */
1681 @Nullable
1682 public String getTypeAllowlistFlags() {
1683 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1684 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1685 }
1686
1687 /**
1688 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1689 */
1690 public boolean isFeatureEnabled(Context context, String feature) {
1691 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1692 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1693 }
1694
1695 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001696 * @see MdnsDiscoveryManager
1697 */
1698 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001699 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001700 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1701 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001702 }
1703
1704 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001705 * @see MdnsAdvertiser
1706 */
1707 public MdnsAdvertiser makeMdnsAdvertiser(
1708 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001709 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1710 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001711 }
1712
1713 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001714 * @see MdnsSocketProvider
1715 */
Paul Hu14667de2023-04-17 22:42:47 +08001716 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001717 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1718 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1719 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1720 }
1721
1722 /**
1723 * @see DeviceConfig#getInt(String, String, int)
1724 */
1725 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1726 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1727 }
1728
1729 /**
1730 * @see Binder#getCallingUid()
1731 */
1732 public int getCallingUid() {
1733 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001734 }
Paul Hu777ed052023-06-19 13:35:15 +00001735
1736 /**
1737 * @see NetworkNsdReportedMetrics
1738 */
1739 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1740 boolean isLegacy, int clientId) {
1741 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1742 }
1743
1744 /**
1745 * @see MdnsUtils.Clock
1746 */
1747 public Clock makeClock() {
1748 return new Clock();
1749 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001750 }
1751
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001752 /**
1753 * Return whether a type is allowlisted to use the Java backend.
1754 * @param type The service type
1755 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1756 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1757 */
1758 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1759 @NonNull String flagPrefix) {
1760 if (type == null) return false;
1761 final String typesConfig = mDeps.getTypeAllowlistFlags();
1762 if (TextUtils.isEmpty(typesConfig)) return false;
1763
1764 final String mappingPrefix = type + ":";
1765 String mappedFlag = null;
1766 for (String mapping : TextUtils.split(typesConfig, ",")) {
1767 if (mapping.startsWith(mappingPrefix)) {
1768 mappedFlag = mapping.substring(mappingPrefix.length());
1769 break;
1770 }
1771 }
1772
1773 if (mappedFlag == null) return false;
1774
1775 return mDeps.isFeatureEnabled(mContext,
1776 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1777 }
1778
1779 private boolean useDiscoveryManagerForType(@Nullable String type) {
1780 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1781 }
1782
1783 private boolean useAdvertiserForType(@Nullable String type) {
1784 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1785 }
1786
paulhu1b35e822022-04-08 14:48:41 +08001787 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001788 HandlerThread thread = new HandlerThread(TAG);
1789 thread.start();
1790 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001791 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001792 return service;
1793 }
1794
paulhu2b9ed952022-02-10 21:58:32 +08001795 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1796 private final StateMachine mStateMachine;
1797
1798 MDnsEventCallback(StateMachine sm) {
1799 mStateMachine = sm;
1800 }
1801
1802 @Override
1803 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1804 mStateMachine.sendMessage(
1805 MDNS_SERVICE_EVENT, status.result, status.id, status);
1806 }
1807
1808 @Override
1809 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1810 mStateMachine.sendMessage(
1811 MDNS_SERVICE_EVENT, status.result, status.id, status);
1812 }
1813
1814 @Override
1815 public void onServiceResolutionStatus(final ResolutionInfo status) {
1816 mStateMachine.sendMessage(
1817 MDNS_SERVICE_EVENT, status.result, status.id, status);
1818 }
1819
1820 @Override
1821 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1822 mStateMachine.sendMessage(
1823 MDNS_SERVICE_EVENT, status.result, status.id, status);
1824 }
1825
1826 @Override
1827 public int getInterfaceVersion() throws RemoteException {
1828 return this.VERSION;
1829 }
1830
1831 @Override
1832 public String getInterfaceHash() throws RemoteException {
1833 return this.HASH;
1834 }
1835 }
1836
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001837 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1838 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1839 final int count = mOffloadEngines.beginBroadcast();
1840 try {
1841 for (int i = 0; i < count; i++) {
1842 final OffloadEngineInfo offloadEngineInfo =
1843 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1844 final String interfaceName = offloadEngineInfo.mInterfaceName;
1845 if (!targetInterfaceName.equals(interfaceName)
1846 || ((offloadEngineInfo.mOffloadType
1847 & offloadServiceInfo.getOffloadType()) == 0)) {
1848 continue;
1849 }
1850 try {
1851 if (isRemove) {
1852 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1853 offloadServiceInfo);
1854 } else {
1855 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1856 offloadServiceInfo);
1857 }
1858 } catch (RemoteException e) {
1859 // Can happen in regular cases, do not log a stacktrace
1860 Log.i(TAG, "Failed to send offload callback, remote died", e);
1861 }
1862 }
1863 } finally {
1864 mOffloadEngines.finishBroadcast();
1865 }
1866 }
1867
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001868 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001869 // TODO: add a callback to notify when a service is being added on each interface (as soon
1870 // as probing starts), and call mOffloadCallbacks. This callback is for
1871 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1872
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001873 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001874 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1875 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1876 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001877 if (clientInfo == null) return;
1878
Paul Hud44e1b72023-06-16 02:07:42 +00001879 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1880 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001881
1882 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1883 // historical behavior.
1884 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001885 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001886 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1887 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001888 }
1889
1890 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001891 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1892 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001893 if (clientInfo == null) return;
1894
Paul Hud44e1b72023-06-16 02:07:42 +00001895 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1896 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001897 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1898 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001899 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001900 }
1901
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001902 @Override
1903 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1904 @NonNull OffloadServiceInfo offloadServiceInfo) {
1905 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1906 }
1907
1908 @Override
1909 public void onOffloadStop(@NonNull String interfaceName,
1910 @NonNull OffloadServiceInfo offloadServiceInfo) {
1911 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1912 }
1913
Paul Hud44e1b72023-06-16 02:07:42 +00001914 private ClientInfo getClientInfoOrLog(int transactionId) {
1915 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001916 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001917 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001918 }
1919 return clientInfo;
1920 }
1921
Paul Hud44e1b72023-06-16 02:07:42 +00001922 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1923 final int clientRequestId = info.getClientRequestId(transactionId);
1924 if (clientRequestId < 0) {
1925 Log.e(TAG, String.format(
1926 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001927 }
Paul Hud44e1b72023-06-16 02:07:42 +00001928 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001929 }
1930 }
1931
Paul Hu2e0a88c2023-03-09 16:05:01 +08001932 private static class ConnectorArgs {
1933 @NonNull public final NsdServiceConnector connector;
1934 @NonNull public final INsdManagerCallback callback;
1935 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001936 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001937
1938 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001939 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001940 this.connector = connector;
1941 this.callback = callback;
1942 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001943 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001944 }
1945 }
1946
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001947 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001948 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001949 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001950 final int uid = mDeps.getCallingUid();
1951 if (cb == null) {
1952 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1953 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001954 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001955 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001956 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001957 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001958 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001959 }
1960
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001961 private static class ListenerArgs {
1962 public final NsdServiceConnector connector;
1963 public final NsdServiceInfo serviceInfo;
1964 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1965 this.connector = connector;
1966 this.serviceInfo = serviceInfo;
1967 }
1968 }
1969
1970 private class NsdServiceConnector extends INsdServiceConnector.Stub
1971 implements IBinder.DeathRecipient {
1972 @Override
1973 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1974 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1975 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1976 new ListenerArgs(this, serviceInfo)));
1977 }
1978
1979 @Override
1980 public void unregisterService(int listenerKey) {
1981 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1982 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1983 new ListenerArgs(this, null)));
1984 }
1985
1986 @Override
1987 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1988 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1989 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1990 new ListenerArgs(this, serviceInfo)));
1991 }
1992
1993 @Override
1994 public void stopDiscovery(int listenerKey) {
1995 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1996 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1997 }
1998
1999 @Override
2000 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2001 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2002 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2003 new ListenerArgs(this, serviceInfo)));
2004 }
2005
2006 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002007 public void stopResolution(int listenerKey) {
2008 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2009 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2010 }
2011
2012 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002013 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2014 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2015 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2016 new ListenerArgs(this, serviceInfo)));
2017 }
2018
2019 @Override
2020 public void unregisterServiceInfoCallback(int listenerKey) {
2021 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2022 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2023 new ListenerArgs(this, null)));
2024 }
2025
2026 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002027 public void startDaemon() {
2028 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2029 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2030 }
2031
2032 @Override
2033 public void binderDied() {
2034 mNsdStateMachine.sendMessage(
2035 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002036
2037 }
2038
2039 @Override
2040 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2041 @OffloadEngine.OffloadCapability long offloadCapabilities,
2042 @OffloadEngine.OffloadType long offloadTypes) {
2043 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2044 // it may not be possible for all the callers of this API to have it.
2045 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2046 Objects.requireNonNull(ifaceName);
2047 Objects.requireNonNull(cb);
2048 mNsdStateMachine.sendMessage(
2049 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2050 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2051 offloadTypes)));
2052 }
2053
2054 @Override
2055 public void unregisterOffloadEngine(IOffloadEngine cb) {
2056 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2057 // it may not be possible for all the callers of this API to have it.
2058 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2059 Objects.requireNonNull(cb);
2060 mNsdStateMachine.sendMessage(
2061 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002062 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002063 }
2064
Hugo Benichi912db992017-04-24 16:41:03 +09002065 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002066 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002067 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002068 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2069 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002070 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002071 }
2072
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002073 private int getUniqueId() {
2074 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2075 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002076 }
2077
Paul Hud44e1b72023-06-16 02:07:42 +00002078 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002079 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002080 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002081 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002082 String name = service.getServiceName();
2083 String type = service.getServiceType();
2084 int port = service.getPort();
2085 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002086 final int registerInterface = getNetworkInterfaceIndex(service);
2087 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002088 Log.e(TAG, "Interface to register service on not found");
2089 return false;
2090 }
Paul Hud44e1b72023-06-16 02:07:42 +00002091 return mMDnsManager.registerService(
2092 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002093 }
2094
Paul Hud44e1b72023-06-16 02:07:42 +00002095 private boolean unregisterService(int transactionId) {
2096 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002097 }
2098
Paul Hud44e1b72023-06-16 02:07:42 +00002099 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002100 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002101 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2102 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002103 Log.e(TAG, "Interface to discover service on not found");
2104 return false;
2105 }
Paul Hud44e1b72023-06-16 02:07:42 +00002106 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002107 }
2108
Paul Hud44e1b72023-06-16 02:07:42 +00002109 private boolean stopServiceDiscovery(int transactionId) {
2110 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002111 }
2112
Paul Hud44e1b72023-06-16 02:07:42 +00002113 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002114 final String name = service.getServiceName();
2115 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002116 final int resolveInterface = getNetworkInterfaceIndex(service);
2117 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002118 Log.e(TAG, "Interface to resolve service on not found");
2119 return false;
2120 }
Paul Hud44e1b72023-06-16 02:07:42 +00002121 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002122 }
2123
2124 /**
2125 * Guess the interface to use to resolve or discover a service on a specific network.
2126 *
2127 * This is an imperfect guess, as for example the network may be gone or not yet fully
2128 * registered. This is fine as failing is correct if the network is gone, and a client
2129 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2130 * this is to support the legacy mdnsresponder implementation, which historically resolved
2131 * services on an unspecified network.
2132 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002133 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2134 final Network network = serviceInfo.getNetwork();
2135 if (network == null) {
2136 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2137 // provided by NsdService from discovery results, and the service was found on an
2138 // interface that has no app-usable Network).
2139 if (serviceInfo.getInterfaceIndex() != 0) {
2140 return serviceInfo.getInterfaceIndex();
2141 }
2142 return IFACE_IDX_ANY;
2143 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002144
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002145 String interfaceName = getNetworkInterfaceName(network);
2146 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002147 return IFACE_IDX_ANY;
2148 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002149 return getNetworkInterfaceIndexByName(interfaceName);
2150 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002151
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002152 private String getNetworkInterfaceName(@Nullable Network network) {
2153 if (network == null) {
2154 return null;
2155 }
2156 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2157 if (cm == null) {
2158 Log.wtf(TAG, "No ConnectivityManager");
2159 return null;
2160 }
2161 final LinkProperties lp = cm.getLinkProperties(network);
2162 if (lp == null) {
2163 return null;
2164 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002165 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002166 return lp.getInterfaceName();
2167 }
2168
2169 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002170 final NetworkInterface iface;
2171 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002172 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002173 } catch (SocketException e) {
2174 Log.e(TAG, "Error querying interface", e);
2175 return IFACE_IDX_ANY;
2176 }
2177
2178 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002179 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002180 return IFACE_IDX_ANY;
2181 }
2182
2183 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002184 }
2185
Paul Hud44e1b72023-06-16 02:07:42 +00002186 private boolean stopResolveService(int transactionId) {
2187 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002188 }
2189
Paul Hud44e1b72023-06-16 02:07:42 +00002190 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2191 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002192 }
2193
Paul Hud44e1b72023-06-16 02:07:42 +00002194 private boolean stopGetAddrInfo(int transactionId) {
2195 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002196 }
2197
2198 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002199 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2200 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002201
Paul Hub2e67d32023-04-18 05:50:14 +00002202 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2203 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002204 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002205
2206 // Dump service and clients logs
2207 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002208 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002209 pw.increaseIndent();
2210 mServiceLogs.reverseDump(pw);
2211 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002212 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002213
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002214 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002215 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002216 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002217 private int mFoundServiceCount = 0;
2218 private int mLostServiceCount = 0;
2219 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002220 private boolean mIsServiceFromCache = false;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002221
Paul Hu812e9212023-06-20 06:24:53 +00002222 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002223 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002224 mStartTimeMs = startTimeMs;
2225 }
2226
Paul Hu812e9212023-06-20 06:24:53 +00002227 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002228 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002229 }
Paul Hu812e9212023-06-20 06:24:53 +00002230
2231 public void onServiceFound(String serviceName) {
2232 mFoundServiceCount++;
2233 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2234 mServices.add(serviceName);
2235 }
2236 }
2237
2238 public void onServiceLost() {
2239 mLostServiceCount++;
2240 }
2241
2242 public int getFoundServiceCount() {
2243 return mFoundServiceCount;
2244 }
2245
2246 public int getLostServiceCount() {
2247 return mLostServiceCount;
2248 }
2249
2250 public int getServicesCount() {
2251 return mServices.size();
2252 }
Paul Hua6bc4632023-06-26 01:18:29 +00002253
2254 public void setServiceFromCache(boolean isServiceFromCache) {
2255 mIsServiceFromCache = isServiceFromCache;
2256 }
2257
2258 public boolean isServiceFromCache() {
2259 return mIsServiceFromCache;
2260 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002261 }
2262
2263 private static class LegacyClientRequest extends ClientRequest {
2264 private final int mRequestCode;
2265
Paul Hu812e9212023-06-20 06:24:53 +00002266 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2267 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002268 mRequestCode = requestCode;
2269 }
2270 }
2271
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002272 private abstract static class JavaBackendClientRequest extends ClientRequest {
2273 @Nullable
2274 private final Network mRequestedNetwork;
2275
Paul Hu777ed052023-06-19 13:35:15 +00002276 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002277 long startTimeMs) {
2278 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002279 mRequestedNetwork = requestedNetwork;
2280 }
2281
2282 @Nullable
2283 public Network getRequestedNetwork() {
2284 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002285 }
2286 }
2287
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002288 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002289 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002290 long startTimeMs) {
2291 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002292 }
2293 }
2294
2295 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002296 @NonNull
2297 private final MdnsListener mListener;
2298
Paul Hud44e1b72023-06-16 02:07:42 +00002299 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002300 @Nullable Network requestedNetwork, long startTimeMs) {
2301 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002302 mListener = listener;
2303 }
2304 }
2305
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002306 /* Information tracked per client */
2307 private class ClientInfo {
2308
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002309 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002310 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002311 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002312 private NsdServiceInfo mResolvedService;
2313
Paul Hud44e1b72023-06-16 02:07:42 +00002314 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002315 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002316
Luke Huangf7277ed2021-07-12 21:15:10 +08002317 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002318 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002319 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002320 // The flag of using java backend if the client's target SDK >= U
2321 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002322 // Store client logs
2323 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002324 // Report the nsd metrics data
2325 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002326
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002327 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002328 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002329 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002330 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002331 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002332 mClientLogs = sharedLog;
2333 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002334 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002335 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002336
2337 @Override
2338 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002339 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002340 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002341 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002342 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2343 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002344 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002345 int clientRequestId = mClientRequests.keyAt(i);
2346 sb.append("clientRequestId ")
2347 .append(clientRequestId)
2348 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002349 .append(" type ").append(
2350 mClientRequests.valueAt(i).getClass().getSimpleName())
2351 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002352 }
2353 return sb.toString();
2354 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002355
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002356 private boolean isPreSClient() {
2357 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002358 }
2359
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002360 private void setPreSClient() {
2361 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002362 }
2363
Paul Hu812e9212023-06-20 06:24:53 +00002364 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002365 final MdnsListener listener =
2366 ((DiscoveryManagerRequest) request).mListener;
2367 mMdnsDiscoveryManager.unregisterListener(
2368 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002369 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002370 }
2371
Dave Plattfeff2af2014-03-07 14:48:22 -08002372 // Remove any pending requests from the global map when we get rid of a client,
2373 // and send cancellations to the daemon.
2374 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002375 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002376 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002377 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002378 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002379 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002380 final int transactionId = request.mTransactionId;
2381 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002382 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002383 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2384 + " transactionId " + transactionId
2385 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002386 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002387
2388 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002389 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2390 if (listener instanceof DiscoveryListener) {
2391 mMetrics.reportServiceDiscoveryStop(transactionId,
2392 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2393 request.getFoundServiceCount(),
2394 request.getLostServiceCount(),
2395 request.getServicesCount());
2396 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002397 continue;
2398 }
2399
2400 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002401 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002402 mMetrics.reportServiceUnregistration(transactionId,
2403 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002404 continue;
2405 }
2406
2407 if (!(request instanceof LegacyClientRequest)) {
2408 throw new IllegalStateException("Unknown request type: " + request.getClass());
2409 }
2410
2411 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002412 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002413 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002414 mMetrics.reportServiceDiscoveryStop(transactionId,
2415 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2416 request.getFoundServiceCount(),
2417 request.getLostServiceCount(),
2418 request.getServicesCount());
Dave Plattfeff2af2014-03-07 14:48:22 -08002419 break;
2420 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002421 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002422 break;
2423 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002424 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002425 mMetrics.reportServiceUnregistration(transactionId,
2426 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002427 break;
2428 default:
2429 break;
2430 }
2431 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002432 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002433 updateMulticastLock();
2434 }
2435
2436 /**
2437 * Returns true if this client has any Java backend request that requests one of the given
2438 * networks.
2439 */
2440 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2441 for (int i = 0; i < mClientRequests.size(); i++) {
2442 final ClientRequest req = mClientRequests.valueAt(i);
2443 if (!(req instanceof JavaBackendClientRequest)) {
2444 continue;
2445 }
2446 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2447 .getRequestedNetwork();
2448 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2449 return true;
2450 }
2451 }
2452 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002453 }
2454
Paul Hud44e1b72023-06-16 02:07:42 +00002455 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2456 // transaction id, return the corresponding client request id.
2457 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002458 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002459 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002460 return mClientRequests.keyAt(i);
2461 }
Christopher Lane74411222014-04-25 18:39:07 -07002462 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002463 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002464 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002465
Paul Hub2e67d32023-04-18 05:50:14 +00002466 private void log(String message) {
2467 mClientLogs.log(message);
2468 }
2469
Paul Hu812e9212023-06-20 06:24:53 +00002470 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2471 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002472 try {
2473 mCb.onDiscoverServicesStarted(listenerKey, info);
2474 } catch (RemoteException e) {
2475 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2476 }
2477 }
Paul Hu812e9212023-06-20 06:24:53 +00002478 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2479 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2480 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002481
Paul Hu812e9212023-06-20 06:24:53 +00002482 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2483 long durationMs) {
2484 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002485 try {
2486 mCb.onDiscoverServicesFailed(listenerKey, error);
2487 } catch (RemoteException e) {
2488 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2489 }
2490 }
2491
Paul Hu812e9212023-06-20 06:24:53 +00002492 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2493 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002494 try {
2495 mCb.onServiceFound(listenerKey, info);
2496 } catch (RemoteException e) {
2497 Log.e(TAG, "Error calling onServiceFound(", e);
2498 }
2499 }
2500
Paul Hu812e9212023-06-20 06:24:53 +00002501 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2502 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002503 try {
2504 mCb.onServiceLost(listenerKey, info);
2505 } catch (RemoteException e) {
2506 Log.e(TAG, "Error calling onServiceLost(", e);
2507 }
2508 }
2509
2510 void onStopDiscoveryFailed(int listenerKey, int error) {
2511 try {
2512 mCb.onStopDiscoveryFailed(listenerKey, error);
2513 } catch (RemoteException e) {
2514 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2515 }
2516 }
2517
Paul Hu812e9212023-06-20 06:24:53 +00002518 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2519 mMetrics.reportServiceDiscoveryStop(
2520 request.mTransactionId,
2521 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2522 request.getFoundServiceCount(),
2523 request.getLostServiceCount(),
2524 request.getServicesCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002525 try {
2526 mCb.onStopDiscoverySucceeded(listenerKey);
2527 } catch (RemoteException e) {
2528 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2529 }
2530 }
2531
Paul Hu777ed052023-06-19 13:35:15 +00002532 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002533 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002534 }
2535
2536 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2537 long durationMs) {
2538 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002539 try {
2540 mCb.onRegisterServiceFailed(listenerKey, error);
2541 } catch (RemoteException e) {
2542 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2543 }
2544 }
2545
Paul Hu777ed052023-06-19 13:35:15 +00002546 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2547 long durationMs) {
2548 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002549 try {
2550 mCb.onRegisterServiceSucceeded(listenerKey, info);
2551 } catch (RemoteException e) {
2552 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2553 }
2554 }
2555
2556 void onUnregisterServiceFailed(int listenerKey, int error) {
2557 try {
2558 mCb.onUnregisterServiceFailed(listenerKey, error);
2559 } catch (RemoteException e) {
2560 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2561 }
2562 }
2563
Paul Hu777ed052023-06-19 13:35:15 +00002564 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2565 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002566 try {
2567 mCb.onUnregisterServiceSucceeded(listenerKey);
2568 } catch (RemoteException e) {
2569 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2570 }
2571 }
2572
Paul Hua6bc4632023-06-26 01:18:29 +00002573 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2574 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2575 }
2576
2577 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2578 long durationMs) {
2579 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002580 try {
2581 mCb.onResolveServiceFailed(listenerKey, error);
2582 } catch (RemoteException e) {
2583 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2584 }
2585 }
2586
Paul Hua6bc4632023-06-26 01:18:29 +00002587 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2588 ClientRequest request) {
2589 mMetrics.reportServiceResolved(
2590 request.mTransactionId,
2591 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2592 request.isServiceFromCache());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002593 try {
2594 mCb.onResolveServiceSucceeded(listenerKey, info);
2595 } catch (RemoteException e) {
2596 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2597 }
2598 }
Paul Hub58deb72022-12-26 09:24:42 +00002599
2600 void onStopResolutionFailed(int listenerKey, int error) {
2601 try {
2602 mCb.onStopResolutionFailed(listenerKey, error);
2603 } catch (RemoteException e) {
2604 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2605 }
2606 }
2607
2608 void onStopResolutionSucceeded(int listenerKey) {
2609 try {
2610 mCb.onStopResolutionSucceeded(listenerKey);
2611 } catch (RemoteException e) {
2612 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2613 }
2614 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002615
2616 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2617 try {
2618 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2619 } catch (RemoteException e) {
2620 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2621 }
2622 }
2623
2624 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2625 try {
2626 mCb.onServiceUpdated(listenerKey, info);
2627 } catch (RemoteException e) {
2628 Log.e(TAG, "Error calling onServiceUpdated", e);
2629 }
2630 }
2631
2632 void onServiceUpdatedLost(int listenerKey) {
2633 try {
2634 mCb.onServiceUpdatedLost(listenerKey);
2635 } catch (RemoteException e) {
2636 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2637 }
2638 }
2639
2640 void onServiceInfoCallbackUnregistered(int listenerKey) {
2641 try {
2642 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2643 } catch (RemoteException e) {
2644 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2645 }
2646 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002647 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002648}