blob: e189d69aca68c0bb05c60ac8812bd636aa1e3d7c [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);
Paul Hu60149052023-07-31 14:26:08 +08001065 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001066 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)) {
Paul Hu60149052023-07-31 14:26:08 +08001070 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
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());
Paul Huddce5912023-08-01 10:26:49 +08001117 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001118 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001119 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001120 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001121 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001122 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001123 if (DBG) Log.d(TAG, "Unregister a service callback");
1124 args = (ListenerArgs) msg.obj;
1125 clientInfo = mClients.get(args.connector);
1126 // If the binder death notification for a INsdManagerCallback was received
1127 // before any calls are received by NsdService, the clientInfo would be
1128 // cleared and cause NPE. Add a null check here to prevent this corner case.
1129 if (clientInfo == null) {
1130 Log.e(TAG, "Unknown connector in callback unregistration");
1131 break;
1132 }
1133
Paul Hud44e1b72023-06-16 02:07:42 +00001134 final ClientRequest request =
1135 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001136 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001137 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001138 break;
1139 }
Paul Hud44e1b72023-06-16 02:07:42 +00001140 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001141 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001142 stopDiscoveryManagerRequest(
1143 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001144 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001145 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001146 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001147 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001148 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001149 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001150 }
paulhu2b9ed952022-02-10 21:58:32 +08001151 case MDNS_SERVICE_EVENT:
1152 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001153 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001154 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001155 break;
Paul Hu019621e2023-01-13 23:26:49 +08001156 case MDNS_DISCOVERY_MANAGER_EVENT:
1157 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1158 return NOT_HANDLED;
1159 }
1160 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001161 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1162 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1163 // TODO: Limits the number of registrations created by a given class.
1164 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1165 offloadEngineInfo);
1166 // TODO: Sends all the existing OffloadServiceInfos back.
1167 break;
1168 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1169 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1170 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001171 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001172 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001173 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001174 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001175 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001176
Paul Hud44e1b72023-06-16 02:07:42 +00001177 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001178 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001179 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001180 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001181 Log.e(TAG, String.format(
1182 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001183 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001184 }
1185
1186 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001187 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1188 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001189 // This can happen because of race conditions. For example,
1190 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1191 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001192 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1193 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001194 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001195 }
Paul Hu812e9212023-06-20 06:24:53 +00001196 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1197 if (request == null) {
1198 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1199 return false;
1200 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001201 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001202 Log.d(TAG, String.format(
1203 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001204 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001205 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001206 case IMDnsEventListener.SERVICE_FOUND: {
1207 final DiscoveryInfo info = (DiscoveryInfo) obj;
1208 final String name = info.serviceName;
1209 final String type = info.registrationType;
1210 servInfo = new NsdServiceInfo(name, type);
1211 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001212 if (foundNetId == 0L) {
1213 // Ignore services that do not have a Network: they are not usable
1214 // by apps, as they would need privileged permissions to use
1215 // interfaces that do not have an associated Network.
1216 break;
1217 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001218 if (foundNetId == INetd.DUMMY_NET_ID) {
1219 // Ignore services on the dummy0 interface: they are only seen when
1220 // discovering locally advertised services, and are not reachable
1221 // through that interface.
1222 break;
1223 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001224 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001225
1226 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001227 break;
paulhu2b9ed952022-02-10 21:58:32 +08001228 }
1229 case IMDnsEventListener.SERVICE_LOST: {
1230 final DiscoveryInfo info = (DiscoveryInfo) obj;
1231 final String name = info.serviceName;
1232 final String type = info.registrationType;
1233 final int lostNetId = info.netId;
1234 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001235 // The network could be set to null (netId 0) if it was torn down when the
1236 // service is lost
1237 // TODO: avoid returning null in that case, possibly by remembering
1238 // found services on the same interface index and their network at the time
1239 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001240 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001241 break;
paulhu2b9ed952022-02-10 21:58:32 +08001242 }
1243 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001244 clientInfo.onDiscoverServicesFailed(clientRequestId,
1245 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1246 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001247 break;
paulhu2b9ed952022-02-10 21:58:32 +08001248 case IMDnsEventListener.SERVICE_REGISTERED: {
1249 final RegistrationInfo info = (RegistrationInfo) obj;
1250 final String name = info.serviceName;
1251 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001252 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001253 transactionId,
1254 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001255 break;
paulhu2b9ed952022-02-10 21:58:32 +08001256 }
1257 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001258 clientInfo.onRegisterServiceFailed(clientRequestId,
1259 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001260 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001261 break;
paulhu2b9ed952022-02-10 21:58:32 +08001262 case IMDnsEventListener.SERVICE_RESOLVED: {
1263 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001264 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001265 final String fullName = info.serviceFullName;
1266 while (index < fullName.length() && fullName.charAt(index) != '.') {
1267 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001268 ++index;
1269 }
1270 ++index;
1271 }
paulhu2b9ed952022-02-10 21:58:32 +08001272 if (index >= fullName.length()) {
1273 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001274 break;
1275 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001276
paulhube186602022-04-12 07:18:23 +00001277 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001278 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001279 String type = rest.replace(".local.", "");
1280
Paul Hu30bd70d2023-02-07 13:20:56 +00001281 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001282 serviceInfo.setServiceName(name);
1283 serviceInfo.setServiceType(type);
1284 serviceInfo.setPort(info.port);
1285 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001286 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001287
Paul Hud44e1b72023-06-16 02:07:42 +00001288 stopResolveService(transactionId);
1289 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001290
Paul Hud44e1b72023-06-16 02:07:42 +00001291 final int transactionId2 = getUniqueId();
1292 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1293 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001294 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001295 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001296 clientInfo.onResolveServiceFailed(clientRequestId,
1297 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1298 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001299 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001300 }
1301 break;
paulhu2b9ed952022-02-10 21:58:32 +08001302 }
1303 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001304 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001305 stopResolveService(transactionId);
1306 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001307 clientInfo.onResolveServiceFailed(clientRequestId,
1308 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1309 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001310 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001311 break;
paulhu2b9ed952022-02-10 21:58:32 +08001312 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001313 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001314 stopGetAddrInfo(transactionId);
1315 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001316 clientInfo.onResolveServiceFailed(clientRequestId,
1317 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1318 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001319 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001320 break;
paulhu2b9ed952022-02-10 21:58:32 +08001321 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001322 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001323 final GetAddressInfo info = (GetAddressInfo) obj;
1324 final String address = info.address;
1325 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001326 InetAddress serviceHost = null;
1327 try {
paulhu2b9ed952022-02-10 21:58:32 +08001328 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001329 } catch (UnknownHostException e) {
1330 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1331 }
1332
1333 // If the resolved service is on an interface without a network, consider it
1334 // as a failure: it would not be usable by apps as they would need
1335 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001336 if (netId != NETID_UNSET && serviceHost != null) {
1337 clientInfo.mResolvedService.setHost(serviceHost);
1338 setServiceNetworkForCallback(clientInfo.mResolvedService,
1339 netId, info.interfaceIdx);
1340 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001341 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001342 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001343 clientInfo.onResolveServiceFailed(clientRequestId,
1344 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1345 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001346 }
Paul Hud44e1b72023-06-16 02:07:42 +00001347 stopGetAddrInfo(transactionId);
1348 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001349 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001350 break;
paulhu2b9ed952022-02-10 21:58:32 +08001351 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001352 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001353 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001354 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001355 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001356 }
Paul Hu019621e2023-01-13 23:26:49 +08001357
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001358 @Nullable
1359 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1360 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001361 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001362 final String[] typeArray = serviceInfo.getServiceType();
1363 final String joinedType;
1364 if (typeArray.length == 0
1365 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1366 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1367 + Arrays.toString(typeArray));
1368 return null;
1369 } else {
1370 joinedType = TextUtils.join(".",
1371 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1372 }
1373 final String serviceType;
1374 switch (code) {
1375 case NsdManager.SERVICE_FOUND:
1376 case NsdManager.SERVICE_LOST:
1377 // For consistency with historical behavior, discovered service types have
1378 // a dot at the end.
1379 serviceType = joinedType + ".";
1380 break;
1381 case RESOLVE_SERVICE_SUCCEEDED:
1382 // For consistency with historical behavior, resolved service types have
1383 // a dot at the beginning.
1384 serviceType = "." + joinedType;
1385 break;
1386 default:
1387 serviceType = joinedType;
1388 break;
1389 }
Paul Hu019621e2023-01-13 23:26:49 +08001390 final String serviceName = serviceInfo.getServiceInstanceName();
1391 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1392 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001393 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1394 // network for Tethering interface. In other words, the network == null means the
1395 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001396 setServiceNetworkForCallback(
1397 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001398 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001399 serviceInfo.getInterfaceIndex());
1400 return servInfo;
1401 }
1402
1403 private boolean handleMdnsDiscoveryManagerEvent(
1404 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001405 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001406 if (clientInfo == null) {
1407 Log.e(TAG, String.format(
1408 "id %d for %d has no client mapping", transactionId, code));
1409 return false;
1410 }
1411
1412 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001413 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001414 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1415 // Errors are already logged if null
1416 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001417 mServiceLogs.log(String.format(
1418 "MdnsDiscoveryManager event code=%s transactionId=%d",
1419 NsdManager.nameOf(code), transactionId));
Paul Hu812e9212023-06-20 06:24:53 +00001420 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1421 if (request == null) {
1422 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1423 return false;
1424 }
Paul Hu019621e2023-01-13 23:26:49 +08001425 switch (code) {
1426 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001427 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001428 break;
1429 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001430 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001431 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001432 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1433 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001434 info.setPort(serviceInfo.getPort());
1435
1436 Map<String, String> attrs = serviceInfo.getAttributes();
1437 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1438 final String key = kv.getKey();
1439 try {
1440 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1441 } catch (IllegalArgumentException e) {
1442 Log.e(TAG, "Invalid attribute", e);
1443 }
1444 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001445 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001446 if (addresses.size() != 0) {
1447 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001448 request.setServiceFromCache(event.mIsServiceFromCache);
1449 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001450 } else {
1451 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001452 clientInfo.onResolveServiceFailed(clientRequestId,
1453 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1454 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001455 }
1456
1457 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001458 if (!(request instanceof DiscoveryManagerRequest)) {
1459 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1460 break;
1461 }
Paul Hud44e1b72023-06-16 02:07:42 +00001462 stopDiscoveryManagerRequest(
1463 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001464 break;
1465 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001466 case NsdManager.SERVICE_UPDATED: {
1467 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1468 info.setPort(serviceInfo.getPort());
1469
1470 Map<String, String> attrs = serviceInfo.getAttributes();
1471 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1472 final String key = kv.getKey();
1473 try {
1474 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1475 } catch (IllegalArgumentException e) {
1476 Log.e(TAG, "Invalid attribute", e);
1477 }
1478 }
1479
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001480 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001481 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001482 clientInfo.onServiceUpdated(clientRequestId, info, request);
1483 // Set the ServiceFromCache flag only if the service is actually being
1484 // retrieved from the cache. This flag should not be overridden by later
1485 // service updates, which may not be cached.
1486 if (event.mIsServiceFromCache) {
1487 request.setServiceFromCache(true);
1488 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001489 break;
1490 }
1491 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001492 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001493 break;
Paul Hu019621e2023-01-13 23:26:49 +08001494 default:
1495 return false;
1496 }
1497 return true;
1498 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001499 }
1500 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001501
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001502 @NonNull
1503 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1504 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1505 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1506 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1507 for (String ipv4Address : v4Addrs) {
1508 try {
1509 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1510 } catch (IllegalArgumentException e) {
1511 Log.wtf(TAG, "Invalid ipv4 address", e);
1512 }
1513 }
1514 for (String ipv6Address : v6Addrs) {
1515 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001516 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1517 ipv6Address);
1518 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1519 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001520 Log.wtf(TAG, "Invalid ipv6 address", e);
1521 }
1522 }
1523 return addresses;
1524 }
1525
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001526 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1527 switch (netId) {
1528 case NETID_UNSET:
1529 info.setNetwork(null);
1530 break;
1531 case INetd.LOCAL_NET_ID:
1532 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1533 // visible / usable for apps, so do not return it. Store the interface
1534 // index instead, so at least if the client tries to resolve the service
1535 // with that NsdServiceInfo, it will be done on the same interface.
1536 // If they recreate the NsdServiceInfo themselves, resolution would be
1537 // done on all interfaces as before T, which should also work.
1538 info.setNetwork(null);
1539 info.setInterfaceIndex(ifaceIdx);
1540 break;
1541 default:
1542 info.setNetwork(new Network(netId));
1543 }
1544 }
1545
paulhube186602022-04-12 07:18:23 +00001546 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1547 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1548 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1549 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1550 private String unescape(String s) {
1551 StringBuilder sb = new StringBuilder(s.length());
1552 for (int i = 0; i < s.length(); ++i) {
1553 char c = s.charAt(i);
1554 if (c == '\\') {
1555 if (++i >= s.length()) {
1556 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1557 break;
1558 }
1559 c = s.charAt(i);
1560 if (c != '.' && c != '\\') {
1561 if (i + 2 >= s.length()) {
1562 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1563 break;
1564 }
1565 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1566 + (s.charAt(i + 2) - '0'));
1567 i += 2;
1568 }
1569 }
1570 sb.append(c);
1571 }
1572 return sb.toString();
1573 }
1574
Paul Hu7445e3d2023-03-03 15:14:00 +08001575 /**
1576 * Check the given service type is valid and construct it to a service type
1577 * which can use for discovery / resolution service.
1578 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001579 * <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 +08001580 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1581 * underscore; they are alphanumerical characters or dashes or underscore, except the
1582 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1583 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001584 * <p>The subtype may also be specified with a comma after the service type, for example
1585 * _type._tcp,_subtype.
1586 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001587 * @param serviceType the request service type for discovery / resolution service
1588 * @return constructed service type or null if the given service type is invalid.
1589 */
1590 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001591 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001592 if (TextUtils.isEmpty(serviceType)) return null;
1593
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001594 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001595 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001596 // Optional leading subtype (_subtype._type._tcp)
1597 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1598 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1599 // Actual type (_type._tcp.local)
1600 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001601 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001602 // e.g. allow "_type._tcp.local."
1603 + "\\.?"
1604 // Optional subtype after comma, for "_type._tcp,_subtype" format
1605 + "(?:,(" + typeOrSubtypePattern + "))?"
1606 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001607 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1608 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001609 // Use the subtype either at the beginning or after the comma
1610 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1611 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001612 }
1613
Hugo Benichi803a2f02017-04-24 11:35:06 +09001614 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001615 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001616 this(ctx, handler, cleanupDelayMs, new Dependencies());
1617 }
1618
1619 @VisibleForTesting
1620 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001621 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001622 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001623 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001624 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001625 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1626 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001627 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001628
Paul Hu14667de2023-04-17 22:42:47 +08001629 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001630 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001631 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1632 // address events are received.
1633 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001634
1635 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1636 // startBootstrapServices).
1637 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1638 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1639 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1640 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1641 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1642 mRunningAppActiveImportanceCutoff);
1643
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001644 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001645 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1646 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001647 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001648 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001649 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1650 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001651 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001652 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001653 }
1654
1655 /**
1656 * Dependencies of NsdService, for injection in tests.
1657 */
1658 @VisibleForTesting
1659 public static class Dependencies {
1660 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001661 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001662 *
1663 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001664 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001665 */
1666 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001667 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1668 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001669 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001670 }
1671
1672 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001673 * Check whether the MdnsAdvertiser feature is enabled.
1674 *
1675 * @param context The global context information about an app environment.
1676 * @return true if the MdnsAdvertiser feature is enabled.
1677 */
1678 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001679 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1680 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1681 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001682 }
1683
1684 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001685 * Get the type allowlist flag value.
1686 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1687 */
1688 @Nullable
1689 public String getTypeAllowlistFlags() {
1690 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1691 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1692 }
1693
1694 /**
1695 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1696 */
1697 public boolean isFeatureEnabled(Context context, String feature) {
1698 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1699 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1700 }
1701
1702 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001703 * @see MdnsDiscoveryManager
1704 */
1705 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001706 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001707 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1708 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001709 }
1710
1711 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001712 * @see MdnsAdvertiser
1713 */
1714 public MdnsAdvertiser makeMdnsAdvertiser(
1715 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001716 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1717 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001718 }
1719
1720 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001721 * @see MdnsSocketProvider
1722 */
Paul Hu14667de2023-04-17 22:42:47 +08001723 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001724 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1725 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1726 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1727 }
1728
1729 /**
1730 * @see DeviceConfig#getInt(String, String, int)
1731 */
1732 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1733 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1734 }
1735
1736 /**
1737 * @see Binder#getCallingUid()
1738 */
1739 public int getCallingUid() {
1740 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001741 }
Paul Hu777ed052023-06-19 13:35:15 +00001742
1743 /**
1744 * @see NetworkNsdReportedMetrics
1745 */
1746 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1747 boolean isLegacy, int clientId) {
1748 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1749 }
1750
1751 /**
1752 * @see MdnsUtils.Clock
1753 */
1754 public Clock makeClock() {
1755 return new Clock();
1756 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001757 }
1758
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001759 /**
1760 * Return whether a type is allowlisted to use the Java backend.
1761 * @param type The service type
1762 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1763 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1764 */
1765 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1766 @NonNull String flagPrefix) {
1767 if (type == null) return false;
1768 final String typesConfig = mDeps.getTypeAllowlistFlags();
1769 if (TextUtils.isEmpty(typesConfig)) return false;
1770
1771 final String mappingPrefix = type + ":";
1772 String mappedFlag = null;
1773 for (String mapping : TextUtils.split(typesConfig, ",")) {
1774 if (mapping.startsWith(mappingPrefix)) {
1775 mappedFlag = mapping.substring(mappingPrefix.length());
1776 break;
1777 }
1778 }
1779
1780 if (mappedFlag == null) return false;
1781
1782 return mDeps.isFeatureEnabled(mContext,
1783 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1784 }
1785
1786 private boolean useDiscoveryManagerForType(@Nullable String type) {
1787 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1788 }
1789
1790 private boolean useAdvertiserForType(@Nullable String type) {
1791 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1792 }
1793
paulhu1b35e822022-04-08 14:48:41 +08001794 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001795 HandlerThread thread = new HandlerThread(TAG);
1796 thread.start();
1797 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001798 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001799 return service;
1800 }
1801
paulhu2b9ed952022-02-10 21:58:32 +08001802 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1803 private final StateMachine mStateMachine;
1804
1805 MDnsEventCallback(StateMachine sm) {
1806 mStateMachine = sm;
1807 }
1808
1809 @Override
1810 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1811 mStateMachine.sendMessage(
1812 MDNS_SERVICE_EVENT, status.result, status.id, status);
1813 }
1814
1815 @Override
1816 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1817 mStateMachine.sendMessage(
1818 MDNS_SERVICE_EVENT, status.result, status.id, status);
1819 }
1820
1821 @Override
1822 public void onServiceResolutionStatus(final ResolutionInfo status) {
1823 mStateMachine.sendMessage(
1824 MDNS_SERVICE_EVENT, status.result, status.id, status);
1825 }
1826
1827 @Override
1828 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1829 mStateMachine.sendMessage(
1830 MDNS_SERVICE_EVENT, status.result, status.id, status);
1831 }
1832
1833 @Override
1834 public int getInterfaceVersion() throws RemoteException {
1835 return this.VERSION;
1836 }
1837
1838 @Override
1839 public String getInterfaceHash() throws RemoteException {
1840 return this.HASH;
1841 }
1842 }
1843
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001844 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1845 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1846 final int count = mOffloadEngines.beginBroadcast();
1847 try {
1848 for (int i = 0; i < count; i++) {
1849 final OffloadEngineInfo offloadEngineInfo =
1850 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1851 final String interfaceName = offloadEngineInfo.mInterfaceName;
1852 if (!targetInterfaceName.equals(interfaceName)
1853 || ((offloadEngineInfo.mOffloadType
1854 & offloadServiceInfo.getOffloadType()) == 0)) {
1855 continue;
1856 }
1857 try {
1858 if (isRemove) {
1859 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1860 offloadServiceInfo);
1861 } else {
1862 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1863 offloadServiceInfo);
1864 }
1865 } catch (RemoteException e) {
1866 // Can happen in regular cases, do not log a stacktrace
1867 Log.i(TAG, "Failed to send offload callback, remote died", e);
1868 }
1869 }
1870 } finally {
1871 mOffloadEngines.finishBroadcast();
1872 }
1873 }
1874
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001875 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001876 // TODO: add a callback to notify when a service is being added on each interface (as soon
1877 // as probing starts), and call mOffloadCallbacks. This callback is for
1878 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1879
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001880 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001881 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1882 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1883 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001884 if (clientInfo == null) return;
1885
Paul Hud44e1b72023-06-16 02:07:42 +00001886 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1887 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001888
1889 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1890 // historical behavior.
1891 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001892 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001893 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1894 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001895 }
1896
1897 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001898 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1899 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001900 if (clientInfo == null) return;
1901
Paul Hud44e1b72023-06-16 02:07:42 +00001902 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1903 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001904 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1905 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001906 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001907 }
1908
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001909 @Override
1910 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1911 @NonNull OffloadServiceInfo offloadServiceInfo) {
1912 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1913 }
1914
1915 @Override
1916 public void onOffloadStop(@NonNull String interfaceName,
1917 @NonNull OffloadServiceInfo offloadServiceInfo) {
1918 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1919 }
1920
Paul Hud44e1b72023-06-16 02:07:42 +00001921 private ClientInfo getClientInfoOrLog(int transactionId) {
1922 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001923 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001924 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001925 }
1926 return clientInfo;
1927 }
1928
Paul Hud44e1b72023-06-16 02:07:42 +00001929 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1930 final int clientRequestId = info.getClientRequestId(transactionId);
1931 if (clientRequestId < 0) {
1932 Log.e(TAG, String.format(
1933 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001934 }
Paul Hud44e1b72023-06-16 02:07:42 +00001935 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001936 }
1937 }
1938
Paul Hu2e0a88c2023-03-09 16:05:01 +08001939 private static class ConnectorArgs {
1940 @NonNull public final NsdServiceConnector connector;
1941 @NonNull public final INsdManagerCallback callback;
1942 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001943 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001944
1945 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001946 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001947 this.connector = connector;
1948 this.callback = callback;
1949 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001950 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001951 }
1952 }
1953
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001954 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001955 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001957 final int uid = mDeps.getCallingUid();
1958 if (cb == null) {
1959 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1960 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001961 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001962 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001963 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001964 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001965 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001966 }
1967
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001968 private static class ListenerArgs {
1969 public final NsdServiceConnector connector;
1970 public final NsdServiceInfo serviceInfo;
1971 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1972 this.connector = connector;
1973 this.serviceInfo = serviceInfo;
1974 }
1975 }
1976
1977 private class NsdServiceConnector extends INsdServiceConnector.Stub
1978 implements IBinder.DeathRecipient {
1979 @Override
1980 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1981 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1982 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1983 new ListenerArgs(this, serviceInfo)));
1984 }
1985
1986 @Override
1987 public void unregisterService(int listenerKey) {
1988 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1989 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1990 new ListenerArgs(this, null)));
1991 }
1992
1993 @Override
1994 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1995 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1996 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1997 new ListenerArgs(this, serviceInfo)));
1998 }
1999
2000 @Override
2001 public void stopDiscovery(int listenerKey) {
2002 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2003 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2004 }
2005
2006 @Override
2007 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2008 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2009 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2010 new ListenerArgs(this, serviceInfo)));
2011 }
2012
2013 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002014 public void stopResolution(int listenerKey) {
2015 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2016 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2017 }
2018
2019 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002020 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2021 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2022 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2023 new ListenerArgs(this, serviceInfo)));
2024 }
2025
2026 @Override
2027 public void unregisterServiceInfoCallback(int listenerKey) {
2028 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2029 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2030 new ListenerArgs(this, null)));
2031 }
2032
2033 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002034 public void startDaemon() {
2035 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2036 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2037 }
2038
2039 @Override
2040 public void binderDied() {
2041 mNsdStateMachine.sendMessage(
2042 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002043
2044 }
2045
2046 @Override
2047 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2048 @OffloadEngine.OffloadCapability long offloadCapabilities,
2049 @OffloadEngine.OffloadType long offloadTypes) {
2050 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2051 // it may not be possible for all the callers of this API to have it.
2052 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2053 Objects.requireNonNull(ifaceName);
2054 Objects.requireNonNull(cb);
2055 mNsdStateMachine.sendMessage(
2056 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2057 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2058 offloadTypes)));
2059 }
2060
2061 @Override
2062 public void unregisterOffloadEngine(IOffloadEngine cb) {
2063 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2064 // it may not be possible for all the callers of this API to have it.
2065 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2066 Objects.requireNonNull(cb);
2067 mNsdStateMachine.sendMessage(
2068 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002069 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002070 }
2071
Hugo Benichi912db992017-04-24 16:41:03 +09002072 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002073 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002074 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002075 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2076 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002077 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002078 }
2079
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002080 private int getUniqueId() {
2081 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2082 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002083 }
2084
Paul Hud44e1b72023-06-16 02:07:42 +00002085 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002086 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002087 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002088 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002089 String name = service.getServiceName();
2090 String type = service.getServiceType();
2091 int port = service.getPort();
2092 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002093 final int registerInterface = getNetworkInterfaceIndex(service);
2094 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002095 Log.e(TAG, "Interface to register service on not found");
2096 return false;
2097 }
Paul Hud44e1b72023-06-16 02:07:42 +00002098 return mMDnsManager.registerService(
2099 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002100 }
2101
Paul Hud44e1b72023-06-16 02:07:42 +00002102 private boolean unregisterService(int transactionId) {
2103 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002104 }
2105
Paul Hud44e1b72023-06-16 02:07:42 +00002106 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002107 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002108 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2109 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002110 Log.e(TAG, "Interface to discover service on not found");
2111 return false;
2112 }
Paul Hud44e1b72023-06-16 02:07:42 +00002113 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002114 }
2115
Paul Hud44e1b72023-06-16 02:07:42 +00002116 private boolean stopServiceDiscovery(int transactionId) {
2117 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002118 }
2119
Paul Hud44e1b72023-06-16 02:07:42 +00002120 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002121 final String name = service.getServiceName();
2122 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002123 final int resolveInterface = getNetworkInterfaceIndex(service);
2124 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002125 Log.e(TAG, "Interface to resolve service on not found");
2126 return false;
2127 }
Paul Hud44e1b72023-06-16 02:07:42 +00002128 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002129 }
2130
2131 /**
2132 * Guess the interface to use to resolve or discover a service on a specific network.
2133 *
2134 * This is an imperfect guess, as for example the network may be gone or not yet fully
2135 * registered. This is fine as failing is correct if the network is gone, and a client
2136 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2137 * this is to support the legacy mdnsresponder implementation, which historically resolved
2138 * services on an unspecified network.
2139 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002140 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2141 final Network network = serviceInfo.getNetwork();
2142 if (network == null) {
2143 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2144 // provided by NsdService from discovery results, and the service was found on an
2145 // interface that has no app-usable Network).
2146 if (serviceInfo.getInterfaceIndex() != 0) {
2147 return serviceInfo.getInterfaceIndex();
2148 }
2149 return IFACE_IDX_ANY;
2150 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002151
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002152 String interfaceName = getNetworkInterfaceName(network);
2153 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002154 return IFACE_IDX_ANY;
2155 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002156 return getNetworkInterfaceIndexByName(interfaceName);
2157 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002158
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002159 private String getNetworkInterfaceName(@Nullable Network network) {
2160 if (network == null) {
2161 return null;
2162 }
2163 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2164 if (cm == null) {
2165 Log.wtf(TAG, "No ConnectivityManager");
2166 return null;
2167 }
2168 final LinkProperties lp = cm.getLinkProperties(network);
2169 if (lp == null) {
2170 return null;
2171 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002172 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002173 return lp.getInterfaceName();
2174 }
2175
2176 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002177 final NetworkInterface iface;
2178 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002179 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002180 } catch (SocketException e) {
2181 Log.e(TAG, "Error querying interface", e);
2182 return IFACE_IDX_ANY;
2183 }
2184
2185 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002186 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002187 return IFACE_IDX_ANY;
2188 }
2189
2190 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002191 }
2192
Paul Hud44e1b72023-06-16 02:07:42 +00002193 private boolean stopResolveService(int transactionId) {
2194 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002195 }
2196
Paul Hud44e1b72023-06-16 02:07:42 +00002197 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2198 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002199 }
2200
Paul Hud44e1b72023-06-16 02:07:42 +00002201 private boolean stopGetAddrInfo(int transactionId) {
2202 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002203 }
2204
2205 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002206 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2207 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002208
Paul Hub2e67d32023-04-18 05:50:14 +00002209 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2210 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002211 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002212
2213 // Dump service and clients logs
2214 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002215 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002216 pw.increaseIndent();
2217 mServiceLogs.reverseDump(pw);
2218 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002219 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002220
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002221 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002222 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002223 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002224 private int mFoundServiceCount = 0;
2225 private int mLostServiceCount = 0;
2226 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002227 private boolean mIsServiceFromCache = false;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002228
Paul Hu812e9212023-06-20 06:24:53 +00002229 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002230 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002231 mStartTimeMs = startTimeMs;
2232 }
2233
Paul Hu812e9212023-06-20 06:24:53 +00002234 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002235 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002236 }
Paul Hu812e9212023-06-20 06:24:53 +00002237
2238 public void onServiceFound(String serviceName) {
2239 mFoundServiceCount++;
2240 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2241 mServices.add(serviceName);
2242 }
2243 }
2244
2245 public void onServiceLost() {
2246 mLostServiceCount++;
2247 }
2248
2249 public int getFoundServiceCount() {
2250 return mFoundServiceCount;
2251 }
2252
2253 public int getLostServiceCount() {
2254 return mLostServiceCount;
2255 }
2256
2257 public int getServicesCount() {
2258 return mServices.size();
2259 }
Paul Hua6bc4632023-06-26 01:18:29 +00002260
2261 public void setServiceFromCache(boolean isServiceFromCache) {
2262 mIsServiceFromCache = isServiceFromCache;
2263 }
2264
2265 public boolean isServiceFromCache() {
2266 return mIsServiceFromCache;
2267 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002268 }
2269
2270 private static class LegacyClientRequest extends ClientRequest {
2271 private final int mRequestCode;
2272
Paul Hu812e9212023-06-20 06:24:53 +00002273 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2274 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002275 mRequestCode = requestCode;
2276 }
2277 }
2278
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002279 private abstract static class JavaBackendClientRequest extends ClientRequest {
2280 @Nullable
2281 private final Network mRequestedNetwork;
2282
Paul Hu777ed052023-06-19 13:35:15 +00002283 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002284 long startTimeMs) {
2285 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002286 mRequestedNetwork = requestedNetwork;
2287 }
2288
2289 @Nullable
2290 public Network getRequestedNetwork() {
2291 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002292 }
2293 }
2294
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002295 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002296 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002297 long startTimeMs) {
2298 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002299 }
2300 }
2301
2302 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002303 @NonNull
2304 private final MdnsListener mListener;
2305
Paul Hud44e1b72023-06-16 02:07:42 +00002306 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002307 @Nullable Network requestedNetwork, long startTimeMs) {
2308 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002309 mListener = listener;
2310 }
2311 }
2312
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002313 /* Information tracked per client */
2314 private class ClientInfo {
2315
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002316 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002317 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002318 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002319 private NsdServiceInfo mResolvedService;
2320
Paul Hud44e1b72023-06-16 02:07:42 +00002321 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002322 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002323
Luke Huangf7277ed2021-07-12 21:15:10 +08002324 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002325 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002326 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002327 // The flag of using java backend if the client's target SDK >= U
2328 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002329 // Store client logs
2330 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002331 // Report the nsd metrics data
2332 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002333
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002334 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002335 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002336 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002337 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002338 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002339 mClientLogs = sharedLog;
2340 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002341 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002342 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002343
2344 @Override
2345 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002346 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002347 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002348 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002349 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2350 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002351 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002352 int clientRequestId = mClientRequests.keyAt(i);
2353 sb.append("clientRequestId ")
2354 .append(clientRequestId)
2355 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002356 .append(" type ").append(
2357 mClientRequests.valueAt(i).getClass().getSimpleName())
2358 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002359 }
2360 return sb.toString();
2361 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002362
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002363 private boolean isPreSClient() {
2364 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002365 }
2366
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002367 private void setPreSClient() {
2368 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002369 }
2370
Paul Hu812e9212023-06-20 06:24:53 +00002371 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002372 final MdnsListener listener =
2373 ((DiscoveryManagerRequest) request).mListener;
2374 mMdnsDiscoveryManager.unregisterListener(
2375 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002376 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002377 }
2378
Dave Plattfeff2af2014-03-07 14:48:22 -08002379 // Remove any pending requests from the global map when we get rid of a client,
2380 // and send cancellations to the daemon.
2381 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002382 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002383 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002384 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002385 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002386 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002387 final int transactionId = request.mTransactionId;
2388 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002389 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002390 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2391 + " transactionId " + transactionId
2392 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002393 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002394
2395 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002396 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2397 if (listener instanceof DiscoveryListener) {
2398 mMetrics.reportServiceDiscoveryStop(transactionId,
2399 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2400 request.getFoundServiceCount(),
2401 request.getLostServiceCount(),
2402 request.getServicesCount());
Paul Hu60149052023-07-31 14:26:08 +08002403 } else if (listener instanceof ResolutionListener) {
2404 mMetrics.reportServiceResolutionStop(transactionId,
2405 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002406 } else if (listener instanceof ServiceInfoListener) {
2407 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2408 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2409 request.getFoundServiceCount(),
2410 request.getLostServiceCount(),
2411 request.isServiceFromCache());
Paul Hu812e9212023-06-20 06:24:53 +00002412 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002413 continue;
2414 }
2415
2416 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002417 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002418 mMetrics.reportServiceUnregistration(transactionId,
2419 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002420 continue;
2421 }
2422
2423 if (!(request instanceof LegacyClientRequest)) {
2424 throw new IllegalStateException("Unknown request type: " + request.getClass());
2425 }
2426
2427 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002428 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002429 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002430 mMetrics.reportServiceDiscoveryStop(transactionId,
2431 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2432 request.getFoundServiceCount(),
2433 request.getLostServiceCount(),
2434 request.getServicesCount());
Dave Plattfeff2af2014-03-07 14:48:22 -08002435 break;
2436 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002437 stopResolveService(transactionId);
Paul Hu60149052023-07-31 14:26:08 +08002438 mMetrics.reportServiceResolutionStop(transactionId,
2439 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002440 break;
2441 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002442 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002443 mMetrics.reportServiceUnregistration(transactionId,
2444 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002445 break;
2446 default:
2447 break;
2448 }
2449 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002450 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002451 updateMulticastLock();
2452 }
2453
2454 /**
2455 * Returns true if this client has any Java backend request that requests one of the given
2456 * networks.
2457 */
2458 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2459 for (int i = 0; i < mClientRequests.size(); i++) {
2460 final ClientRequest req = mClientRequests.valueAt(i);
2461 if (!(req instanceof JavaBackendClientRequest)) {
2462 continue;
2463 }
2464 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2465 .getRequestedNetwork();
2466 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2467 return true;
2468 }
2469 }
2470 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002471 }
2472
Paul Hud44e1b72023-06-16 02:07:42 +00002473 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2474 // transaction id, return the corresponding client request id.
2475 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002476 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002477 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002478 return mClientRequests.keyAt(i);
2479 }
Christopher Lane74411222014-04-25 18:39:07 -07002480 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002481 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002482 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002483
Paul Hub2e67d32023-04-18 05:50:14 +00002484 private void log(String message) {
2485 mClientLogs.log(message);
2486 }
2487
Paul Hu812e9212023-06-20 06:24:53 +00002488 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2489 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002490 try {
2491 mCb.onDiscoverServicesStarted(listenerKey, info);
2492 } catch (RemoteException e) {
2493 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2494 }
2495 }
Paul Hu812e9212023-06-20 06:24:53 +00002496 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2497 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2498 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002499
Paul Hu812e9212023-06-20 06:24:53 +00002500 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2501 long durationMs) {
2502 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002503 try {
2504 mCb.onDiscoverServicesFailed(listenerKey, error);
2505 } catch (RemoteException e) {
2506 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2507 }
2508 }
2509
Paul Hu812e9212023-06-20 06:24:53 +00002510 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2511 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002512 try {
2513 mCb.onServiceFound(listenerKey, info);
2514 } catch (RemoteException e) {
2515 Log.e(TAG, "Error calling onServiceFound(", e);
2516 }
2517 }
2518
Paul Hu812e9212023-06-20 06:24:53 +00002519 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2520 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002521 try {
2522 mCb.onServiceLost(listenerKey, info);
2523 } catch (RemoteException e) {
2524 Log.e(TAG, "Error calling onServiceLost(", e);
2525 }
2526 }
2527
2528 void onStopDiscoveryFailed(int listenerKey, int error) {
2529 try {
2530 mCb.onStopDiscoveryFailed(listenerKey, error);
2531 } catch (RemoteException e) {
2532 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2533 }
2534 }
2535
Paul Hu812e9212023-06-20 06:24:53 +00002536 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2537 mMetrics.reportServiceDiscoveryStop(
2538 request.mTransactionId,
2539 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2540 request.getFoundServiceCount(),
2541 request.getLostServiceCount(),
2542 request.getServicesCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002543 try {
2544 mCb.onStopDiscoverySucceeded(listenerKey);
2545 } catch (RemoteException e) {
2546 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2547 }
2548 }
2549
Paul Hu777ed052023-06-19 13:35:15 +00002550 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002551 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002552 }
2553
2554 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2555 long durationMs) {
2556 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002557 try {
2558 mCb.onRegisterServiceFailed(listenerKey, error);
2559 } catch (RemoteException e) {
2560 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2561 }
2562 }
2563
Paul Hu777ed052023-06-19 13:35:15 +00002564 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2565 long durationMs) {
2566 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002567 try {
2568 mCb.onRegisterServiceSucceeded(listenerKey, info);
2569 } catch (RemoteException e) {
2570 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2571 }
2572 }
2573
2574 void onUnregisterServiceFailed(int listenerKey, int error) {
2575 try {
2576 mCb.onUnregisterServiceFailed(listenerKey, error);
2577 } catch (RemoteException e) {
2578 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2579 }
2580 }
2581
Paul Hu777ed052023-06-19 13:35:15 +00002582 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2583 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002584 try {
2585 mCb.onUnregisterServiceSucceeded(listenerKey);
2586 } catch (RemoteException e) {
2587 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2588 }
2589 }
2590
Paul Hua6bc4632023-06-26 01:18:29 +00002591 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2592 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2593 }
2594
2595 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2596 long durationMs) {
2597 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002598 try {
2599 mCb.onResolveServiceFailed(listenerKey, error);
2600 } catch (RemoteException e) {
2601 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2602 }
2603 }
2604
Paul Hua6bc4632023-06-26 01:18:29 +00002605 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2606 ClientRequest request) {
2607 mMetrics.reportServiceResolved(
2608 request.mTransactionId,
2609 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2610 request.isServiceFromCache());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002611 try {
2612 mCb.onResolveServiceSucceeded(listenerKey, info);
2613 } catch (RemoteException e) {
2614 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2615 }
2616 }
Paul Hub58deb72022-12-26 09:24:42 +00002617
2618 void onStopResolutionFailed(int listenerKey, int error) {
2619 try {
2620 mCb.onStopResolutionFailed(listenerKey, error);
2621 } catch (RemoteException e) {
2622 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2623 }
2624 }
2625
Paul Hu60149052023-07-31 14:26:08 +08002626 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2627 mMetrics.reportServiceResolutionStop(
2628 request.mTransactionId,
2629 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002630 try {
2631 mCb.onStopResolutionSucceeded(listenerKey);
2632 } catch (RemoteException e) {
2633 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2634 }
2635 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002636
2637 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002638 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002639 try {
2640 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2641 } catch (RemoteException e) {
2642 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2643 }
2644 }
2645
Paul Huddce5912023-08-01 10:26:49 +08002646 void onServiceInfoCallbackRegistered(int transactionId) {
2647 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2648 }
2649
2650 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2651 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002652 try {
2653 mCb.onServiceUpdated(listenerKey, info);
2654 } catch (RemoteException e) {
2655 Log.e(TAG, "Error calling onServiceUpdated", e);
2656 }
2657 }
2658
Paul Huddce5912023-08-01 10:26:49 +08002659 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2660 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002661 try {
2662 mCb.onServiceUpdatedLost(listenerKey);
2663 } catch (RemoteException e) {
2664 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2665 }
2666 }
2667
Paul Huddce5912023-08-01 10:26:49 +08002668 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2669 mMetrics.reportServiceInfoCallbackUnregistered(
2670 request.mTransactionId,
2671 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2672 request.getFoundServiceCount(),
2673 request.getLostServiceCount(),
2674 request.isServiceFromCache());
Paul Hu18aeccc2022-12-27 08:48:48 +00002675 try {
2676 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2677 } catch (RemoteException e) {
2678 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2679 }
2680 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002681 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002682}