blob: ff1f02dff6705e16f99b7a044a4bc62ed6ea2205 [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 Hubad6fe92023-07-24 21:25:22 +0800175 private static final int NO_SENT_QUERY_COUNT = 0;
176 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800177 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700178
Hugo Benichi32be63d2017-04-05 14:06:11 +0900179 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900180 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800181 private final MDnsManager mMDnsManager;
182 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900183 @NonNull
184 private final Dependencies mDeps;
185 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800186 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900187 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800188 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900189 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800190 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900191 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900192 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000193 @NonNull
194 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800195 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800196 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800197 // state machine thread. If change this outside state machine, it will need to introduce
198 // synchronization.
199 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800200 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700201
202 /**
203 * Clients receiving asynchronous messages
204 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900205 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700206
Paul Hud44e1b72023-06-16 02:07:42 +0000207 /* A map from transaction(unique) id to client info */
208 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700209
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900210 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
211 @Nullable
212 private WifiManager.MulticastLock mHeldMulticastLock;
213 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
214 // (non-null), value is the requested Network (nullable)
215 @NonNull
216 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
217 @NonNull
218 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
219
Luke Huang05298582021-06-13 16:52:05 +0000220 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700221
Hugo Benichi32be63d2017-04-05 14:06:11 +0900222 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700223 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800224 // The count of the connected legacy clients.
225 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000226 // The number of client that ever connected.
227 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700228
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900229 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
230 new RemoteCallbackList<>();
231
232 private static class OffloadEngineInfo {
233 @NonNull final String mInterfaceName;
234 final long mOffloadCapabilities;
235 final long mOffloadType;
236 @NonNull final IOffloadEngine mOffloadEngine;
237
238 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
239 @NonNull String interfaceName, long capabilities, long offloadType) {
240 this.mOffloadEngine = offloadEngine;
241 this.mInterfaceName = interfaceName;
242 this.mOffloadCapabilities = capabilities;
243 this.mOffloadType = offloadType;
244 }
245 }
246
Paul Hu812e9212023-06-20 06:24:53 +0000247 @VisibleForTesting
248 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000249 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800250 protected final int mTransactionId;
251 @NonNull
252 protected final NsdServiceInfo mReqServiceInfo;
253 @NonNull
254 protected final String mListenedServiceType;
255
Paul Hud44e1b72023-06-16 02:07:42 +0000256 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800257 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000258 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800259 mTransactionId = transactionId;
260 mReqServiceInfo = reqServiceInfo;
261 mListenedServiceType = listenedServiceType;
262 }
263
264 @NonNull
265 public String getListenedServiceType() {
266 return mListenedServiceType;
267 }
268
269 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000270 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
271 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800272
273 @Override
274 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
275
276 @Override
277 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
278
279 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000280 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
281 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800282
283 @Override
284 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
285
286 @Override
287 public void onSearchStoppedWithError(int error) { }
288
289 @Override
290 public void onSearchFailedToStart() { }
291
292 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800293 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
294 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800295
296 @Override
297 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
298 }
299
300 private class DiscoveryListener extends MdnsListener {
301
Paul Hud44e1b72023-06-16 02:07:42 +0000302 DiscoveryListener(int clientRequestId, int transactionId,
303 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
304 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800305 }
306
307 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000308 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
309 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800310 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
311 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000312 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800313 }
314
315 @Override
316 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800317 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
318 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000319 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800320 }
Paul Hubad6fe92023-07-24 21:25:22 +0800321
322 @Override
323 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
324 int sentQueryTransactionId) {
325 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
326 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
327 }
Paul Hu23fa2022023-01-13 22:57:24 +0800328 }
329
Paul Hu75069ed2023-01-14 00:31:09 +0800330 private class ResolutionListener extends MdnsListener {
331
Paul Hud44e1b72023-06-16 02:07:42 +0000332 ResolutionListener(int clientRequestId, int transactionId,
333 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
334 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800335 }
336
337 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000338 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800339 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
340 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000341 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800342 }
Paul Hubad6fe92023-07-24 21:25:22 +0800343
344 @Override
345 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
346 int sentQueryTransactionId) {
347 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
348 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
349 }
Paul Hu75069ed2023-01-14 00:31:09 +0800350 }
351
Paul Hu30bd70d2023-02-07 13:20:56 +0000352 private class ServiceInfoListener extends MdnsListener {
353
Paul Hud44e1b72023-06-16 02:07:42 +0000354 ServiceInfoListener(int clientRequestId, int transactionId,
355 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
356 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000357 }
358
359 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000360 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
361 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000362 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
363 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000364 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000365 }
366
367 @Override
368 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
369 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
370 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000371 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000372 }
373
374 @Override
375 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
376 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
377 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000378 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000379 }
Paul Hubad6fe92023-07-24 21:25:22 +0800380
381 @Override
382 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
383 int sentQueryTransactionId) {
384 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
385 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
386 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000387 }
388
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900389 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
390 @Override
391 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
392 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
393 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
394 // filtering on such interfaces, so taking the multicast lock is not necessary to
395 // disable APF filtering of multicast.
396 if (socketNetwork == null
397 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
398 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
399 return;
400 }
401
402 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
403 updateMulticastLock();
404 }
405 }
406
407 @Override
408 public void onSocketDestroyed(@Nullable Network socketNetwork,
409 @NonNull MdnsInterfaceSocket socket) {
410 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
411 updateMulticastLock();
412 }
413 }
414 }
415
416 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
417 private final Handler mHandler;
418
419 private UidImportanceListener(Handler handler) {
420 mHandler = handler;
421 }
422
423 @Override
424 public void onUidImportance(int uid, int importance) {
425 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
426 }
427 }
428
429 private void handleUidImportanceChanged(int uid, int importance) {
430 // Lower importance values are more "important"
431 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
432 ? mRunningAppActiveUids.add(uid)
433 : mRunningAppActiveUids.remove(uid);
434 if (modified) {
435 updateMulticastLock();
436 }
437 }
438
439 /**
440 * Take or release the lock based on updated internal state.
441 *
442 * This determines whether the lock needs to be held based on
443 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
444 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
445 * updated.
446 */
447 private void updateMulticastLock() {
448 final int needsLockUid = getMulticastLockNeededUid();
449 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
450 final WifiManager wm = mContext.getSystemService(WifiManager.class);
451 if (wm == null) {
452 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
453 return;
454 }
455 mHeldMulticastLock = wm.createMulticastLock(TAG);
456 mHeldMulticastLock.acquire();
457 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
458 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
459 mHeldMulticastLock.release();
460 mHeldMulticastLock = null;
461 mServiceLogs.log("Released multicast lock");
462 }
463 }
464
465 /**
466 * @return The UID of an app requiring the multicast lock, or -1 if none.
467 */
468 private int getMulticastLockNeededUid() {
469 if (mWifiLockRequiredNetworks.size() == 0) {
470 // Return early if NSD is not active, or not on any relevant network
471 return -1;
472 }
Paul Hud44e1b72023-06-16 02:07:42 +0000473 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
474 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900475 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
476 // Ignore non-active UIDs
477 continue;
478 }
479
480 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
481 return clientInfo.mUid;
482 }
483 }
484 return -1;
485 }
486
Paul Hu019621e2023-01-13 23:26:49 +0800487 /**
488 * Data class of mdns service callback information.
489 */
490 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000491 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800492 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800493 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000494 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800495
Paul Hubad6fe92023-07-24 21:25:22 +0800496 MdnsEvent(int clientRequestId) {
497 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
498 }
499
500 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000501 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
502 }
503
Paul Hubad6fe92023-07-24 21:25:22 +0800504 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000505 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000506 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800507 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000508 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800509 }
510 }
511
Irfan Sheriff75006652012-04-17 23:15:29 -0700512 private class NsdStateMachine extends StateMachine {
513
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700514 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700515 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700516
517 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700518 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900519 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700520 }
521
Luke Huang92860f92021-06-23 06:29:30 +0000522 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800523 if (mIsDaemonStarted) {
524 if (DBG) Log.d(TAG, "Daemon is already started.");
525 return;
526 }
527 mMDnsManager.registerEventListener(mMDnsEventCallback);
528 mMDnsManager.startDaemon();
529 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000530 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000531 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000532 }
533
paulhu2b9ed952022-02-10 21:58:32 +0800534 private void maybeStopDaemon() {
535 if (!mIsDaemonStarted) {
536 if (DBG) Log.d(TAG, "Daemon has not been started.");
537 return;
538 }
539 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
540 mMDnsManager.stopDaemon();
541 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000542 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800543 }
544
Luke Huang92860f92021-06-23 06:29:30 +0000545 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000546 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000547 }
548
549 private void scheduleStop() {
550 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
551 }
552 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800553 // The native daemon should stay alive and can't be cleanup
554 // if any legacy client connected.
555 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000556 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000557 }
558 }
559
Luke Huang92860f92021-06-23 06:29:30 +0000560 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000561 this.removeMessages(NsdManager.DAEMON_CLEANUP);
562 }
563
Paul Hu23fa2022023-01-13 22:57:24 +0800564 private void maybeStartMonitoringSockets() {
565 if (mIsMonitoringSocketsStarted) {
566 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
567 return;
568 }
569
570 mMdnsSocketProvider.startMonitoringSockets();
571 mIsMonitoringSocketsStarted = true;
572 }
573
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900574 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
575 if (!mIsMonitoringSocketsStarted) return;
576 if (isAnyRequestActive()) return;
577
Paul Hu58f20602023-02-18 11:41:07 +0800578 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800579 mIsMonitoringSocketsStarted = false;
580 }
581
Hugo Benichi803a2f02017-04-24 11:35:06 +0900582 NsdStateMachine(String name, Handler handler) {
583 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700584 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700585 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800586 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900587 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700588 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700589 }
590
591 class DefaultState extends State {
592 @Override
593 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900594 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000595 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700596 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900597 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800598 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
599 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900600 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800601 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000602 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000603 final NetworkNsdReportedMetrics metrics =
604 mDeps.makeNetworkNsdReportedMetrics(
605 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900606 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000607 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800608 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900609 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000610 Log.w(TAG, "Client request id " + clientRequestId
611 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700612 }
613 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900614 case NsdManager.UNREGISTER_CLIENT:
615 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
616 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800617 if (cInfo != null) {
618 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900619 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800620 mLegacyClientCount -= 1;
621 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800622 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900623 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800624 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700625 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700626 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900627 cInfo = getClientInfoForReply(msg);
628 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000629 cInfo.onDiscoverServicesFailedImmediately(
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;
633 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900634 cInfo = getClientInfoForReply(msg);
635 if (cInfo != null) {
636 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000637 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900638 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700639 break;
640 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900641 cInfo = getClientInfoForReply(msg);
642 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000643 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000644 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900645 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700646 break;
647 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900648 cInfo = getClientInfoForReply(msg);
649 if (cInfo != null) {
650 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000651 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900652 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700653 break;
654 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900655 cInfo = getClientInfoForReply(msg);
656 if (cInfo != null) {
Paul Hua6bc4632023-06-26 01:18:29 +0000657 cInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000658 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900659 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700660 break;
Paul Hub58deb72022-12-26 09:24:42 +0000661 case NsdManager.STOP_RESOLUTION:
662 cInfo = getClientInfoForReply(msg);
663 if (cInfo != null) {
664 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000665 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000666 }
667 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000668 case NsdManager.REGISTER_SERVICE_CALLBACK:
669 cInfo = getClientInfoForReply(msg);
670 if (cInfo != null) {
671 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000672 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000673 }
674 break;
Luke Huang05298582021-06-13 16:52:05 +0000675 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800676 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000677 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800678 // This event should be only sent by the legacy (target SDK < S) clients.
679 // Mark the sending client as legacy.
680 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900681 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800682 if (cInfo != null) {
683 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900684 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800685 mLegacyClientCount += 1;
686 maybeStartDaemon();
687 }
688 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 default:
paulhub2225702021-11-17 09:35:33 +0800690 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700691 return NOT_HANDLED;
692 }
693 return HANDLED;
694 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900695
696 private ClientInfo getClientInfoForReply(Message msg) {
697 final ListenerArgs args = (ListenerArgs) msg.obj;
698 return mClients.get(args.connector);
699 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700700 }
701
Irfan Sheriff75006652012-04-17 23:15:29 -0700702 class EnabledState extends State {
703 @Override
704 public void enter() {
705 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700706 }
707
708 @Override
709 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000710 // TODO: it is incorrect to stop the daemon without expunging all requests
711 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000712 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700713 }
714
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700715 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900716 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800717 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700718 return true;
719 }
720 return false;
721 }
722
Paul Hud44e1b72023-06-16 02:07:42 +0000723 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000724 ClientInfo clientInfo, int what, long startTimeMs) {
725 clientInfo.mClientRequests.put(clientRequestId,
726 new LegacyClientRequest(transactionId, what, startTimeMs));
Paul Hud44e1b72023-06-16 02:07:42 +0000727 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000728 // Remove the cleanup event because here comes a new request.
729 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700730 }
731
Paul Hud44e1b72023-06-16 02:07:42 +0000732 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900733 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000734 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000735 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000736 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900737 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800738 }
739
Paul Hud44e1b72023-06-16 02:07:42 +0000740 private void removeRequestMap(
741 int clientRequestId, int transactionId, ClientInfo clientInfo) {
742 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900743 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000744 clientInfo.mClientRequests.remove(clientRequestId);
745 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900746
747 if (existing instanceof LegacyClientRequest) {
748 maybeScheduleStop();
749 } else {
750 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900751 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900752 }
753 }
754
Paul Hud44e1b72023-06-16 02:07:42 +0000755 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900756 MdnsListener listener, ClientInfo clientInfo,
757 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000758 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000759 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000760 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900761 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800762 }
763
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900764 /**
765 * Truncate a service name to up to 63 UTF-8 bytes.
766 *
767 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
768 * names used in registerService follows historical behavior (see mdnsresponder
769 * handle_regservice_request).
770 */
771 @NonNull
772 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900773 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800774 }
775
Paul Hud44e1b72023-06-16 02:07:42 +0000776 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
777 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800778 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000779 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800780 }
781
Irfan Sheriff75006652012-04-17 23:15:29 -0700782 @Override
783 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900784 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000785 final int transactionId;
786 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900787 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900788 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700789 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800790 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800791 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900792 args = (ListenerArgs) msg.obj;
793 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000794 // If the binder death notification for a INsdManagerCallback was received
795 // before any calls are received by NsdService, the clientInfo would be
796 // cleared and cause NPE. Add a null check here to prevent this corner case.
797 if (clientInfo == null) {
798 Log.e(TAG, "Unknown connector in discovery");
799 break;
800 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700801
802 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000803 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000804 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700805 break;
806 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700807
Paul Hu23fa2022023-01-13 22:57:24 +0800808 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000809 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900810 final Pair<String, String> typeAndSubtype =
811 parseTypeAndSubtype(info.getServiceType());
812 final String serviceType = typeAndSubtype == null
813 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800814 if (clientInfo.mUseJavaBackend
815 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900816 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800817 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000818 clientInfo.onDiscoverServicesFailedImmediately(
819 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800820 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700821 }
Paul Hu23fa2022023-01-13 22:57:24 +0800822
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900823 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800824 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000825 final MdnsListener listener = new DiscoveryListener(clientRequestId,
826 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900827 final MdnsSearchOptions.Builder optionsBuilder =
828 MdnsSearchOptions.newBuilder()
829 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900830 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900831 .setIsPassiveMode(true);
832 if (typeAndSubtype.second != null) {
833 // The parsing ensures subtype starts with an underscore.
834 // MdnsSearchOptions expects the underscore to not be present.
835 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
836 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900837 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900838 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000839 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
840 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000841 clientInfo.onDiscoverServicesStarted(
842 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000843 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000844 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700845 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800846 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000847 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800848 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000849 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800850 + info.getServiceType());
851 }
Paul Hua6bc4632023-06-26 01:18:29 +0000852 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
853 msg.what, mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000854 clientInfo.onDiscoverServicesStarted(
855 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800856 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000857 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000858 clientInfo.onDiscoverServicesFailedImmediately(
859 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800860 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700861 }
862 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800863 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900864 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800865 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900866 args = (ListenerArgs) msg.obj;
867 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000868 // If the binder death notification for a INsdManagerCallback was received
869 // before any calls are received by NsdService, the clientInfo would be
870 // cleared and cause NPE. Add a null check here to prevent this corner case.
871 if (clientInfo == null) {
872 Log.e(TAG, "Unknown connector in stop discovery");
873 break;
874 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700875
Paul Hud44e1b72023-06-16 02:07:42 +0000876 final ClientRequest request =
877 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900878 if (request == null) {
879 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700880 break;
881 }
Paul Hud44e1b72023-06-16 02:07:42 +0000882 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900883 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
884 // point, so this needs to check the type of the original request to
885 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900886 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000887 stopDiscoveryManagerRequest(
888 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000889 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000890 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700891 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000892 removeRequestMap(clientRequestId, transactionId, clientInfo);
893 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000894 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800895 } else {
896 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000897 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800898 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700899 }
900 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900901 }
902 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800903 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900904 args = (ListenerArgs) msg.obj;
905 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000906 // If the binder death notification for a INsdManagerCallback was received
907 // before any calls are received by NsdService, the clientInfo would be
908 // cleared and cause NPE. Add a null check here to prevent this corner case.
909 if (clientInfo == null) {
910 Log.e(TAG, "Unknown connector in registration");
911 break;
912 }
913
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700914 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000915 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000916 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700917 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700918 }
919
Paul Hud44e1b72023-06-16 02:07:42 +0000920 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900921 final NsdServiceInfo serviceInfo = args.serviceInfo;
922 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900923 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
924 final String registerServiceType = typeSubtype == null
925 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800926 if (clientInfo.mUseJavaBackend
927 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900928 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900929 if (registerServiceType == null) {
930 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000931 clientInfo.onRegisterServiceFailedImmediately(
932 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900933 break;
934 }
935 serviceInfo.setServiceType(registerServiceType);
936 serviceInfo.setServiceName(truncateServiceName(
937 serviceInfo.getServiceName()));
938
939 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900940 // TODO: pass in the subtype as well. Including the subtype in the
941 // service type would generate service instance names like
942 // Name._subtype._sub._type._tcp, which is incorrect
943 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000944 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
945 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900946 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700947 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900948 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000949 if (registerService(transactionId, serviceInfo)) {
950 if (DBG) {
951 Log.d(TAG, "Register " + clientRequestId
952 + " " + transactionId);
953 }
Paul Hua6bc4632023-06-26 01:18:29 +0000954 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
955 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900956 // Return success after mDns reports success
957 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000958 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000959 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000960 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 }
962
Irfan Sheriff75006652012-04-17 23:15:29 -0700963 }
964 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900965 }
966 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800967 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900968 args = (ListenerArgs) msg.obj;
969 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000970 // If the binder death notification for a INsdManagerCallback was received
971 // before any calls are received by NsdService, the clientInfo would be
972 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900973 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800974 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700975 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700976 }
Paul Hud44e1b72023-06-16 02:07:42 +0000977 final ClientRequest request =
978 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900979 if (request == null) {
980 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
981 break;
982 }
Paul Hud44e1b72023-06-16 02:07:42 +0000983 transactionId = request.mTransactionId;
984 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900985
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900986 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
987 // so this needs to check the type of the original request to unregister
988 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000989 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900990 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000991 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000992 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +0000993 request.calculateRequestDurationMs(stopTimeMs));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700994 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000995 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000996 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +0000997 transactionId,
998 request.calculateRequestDurationMs(stopTimeMs));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900999 } else {
1000 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001001 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001002 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001003 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001004 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001005 }
Paul Hu75069ed2023-01-14 00:31:09 +08001006 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001007 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001008 args = (ListenerArgs) msg.obj;
1009 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001010 // If the binder death notification for a INsdManagerCallback was received
1011 // before any calls are received by NsdService, the clientInfo would be
1012 // cleared and cause NPE. Add a null check here to prevent this corner case.
1013 if (clientInfo == null) {
1014 Log.e(TAG, "Unknown connector in resolution");
1015 break;
1016 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001017
Paul Hu75069ed2023-01-14 00:31:09 +08001018 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001019 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001020 final Pair<String, String> typeSubtype =
1021 parseTypeAndSubtype(info.getServiceType());
1022 final String serviceType = typeSubtype == null
1023 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001024 if (clientInfo.mUseJavaBackend
1025 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001026 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001027 if (serviceType == null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001028 clientInfo.onResolveServiceFailedImmediately(
1029 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001030 break;
1031 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001032 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001033
1034 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001035 final MdnsListener listener = new ResolutionListener(clientRequestId,
1036 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001037 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1038 .setNetwork(info.getNetwork())
1039 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001040 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001041 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001042 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001043 mMdnsDiscoveryManager.registerListener(
1044 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001045 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1046 listener, clientInfo, info.getNetwork());
1047 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001048 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001049 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001050 if (clientInfo.mResolvedService != null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001051 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001052 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001053 break;
1054 }
1055
1056 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001057 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001058 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001059 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1060 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001061 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001062 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001063 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001064 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001065 }
1066 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001067 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001068 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001069 if (DBG) Log.d(TAG, "Stop service resolution");
1070 args = (ListenerArgs) msg.obj;
1071 clientInfo = mClients.get(args.connector);
1072 // If the binder death notification for a INsdManagerCallback was received
1073 // before any calls are received by NsdService, the clientInfo would be
1074 // cleared and cause NPE. Add a null check here to prevent this corner case.
1075 if (clientInfo == null) {
1076 Log.e(TAG, "Unknown connector in stop resolution");
1077 break;
1078 }
1079
Paul Hud44e1b72023-06-16 02:07:42 +00001080 final ClientRequest request =
1081 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001082 if (request == null) {
1083 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1084 break;
1085 }
Paul Hud44e1b72023-06-16 02:07:42 +00001086 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001087 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1088 // point, so this needs to check the type of the original request to
1089 // unregister instead of looking at the flag value.
1090 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001091 stopDiscoveryManagerRequest(
1092 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001093 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001094 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001095 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001096 removeRequestMap(clientRequestId, transactionId, clientInfo);
1097 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001098 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001099 } else {
1100 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001101 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001102 }
1103 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001104 }
Paul Hub58deb72022-12-26 09:24:42 +00001105 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001106 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001107 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001108 if (DBG) Log.d(TAG, "Register a service callback");
1109 args = (ListenerArgs) msg.obj;
1110 clientInfo = mClients.get(args.connector);
1111 // If the binder death notification for a INsdManagerCallback was received
1112 // before any calls are received by NsdService, the clientInfo would be
1113 // cleared and cause NPE. Add a null check here to prevent this corner case.
1114 if (clientInfo == null) {
1115 Log.e(TAG, "Unknown connector in callback registration");
1116 break;
1117 }
1118
Paul Hu30bd70d2023-02-07 13:20:56 +00001119 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001120 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001121 final Pair<String, String> typeAndSubtype =
1122 parseTypeAndSubtype(info.getServiceType());
1123 final String serviceType = typeAndSubtype == null
1124 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001125 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001126 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001127 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001128 break;
1129 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001130 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001131
Paul Hu30bd70d2023-02-07 13:20:56 +00001132 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001133 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1134 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001135 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1136 .setNetwork(info.getNetwork())
1137 .setIsPassiveMode(true)
1138 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001139 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001140 .build();
1141 mMdnsDiscoveryManager.registerListener(
1142 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001143 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1144 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001145 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001146 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001147 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001148 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001149 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001150 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001151 if (DBG) Log.d(TAG, "Unregister a service callback");
1152 args = (ListenerArgs) msg.obj;
1153 clientInfo = mClients.get(args.connector);
1154 // If the binder death notification for a INsdManagerCallback was received
1155 // before any calls are received by NsdService, the clientInfo would be
1156 // cleared and cause NPE. Add a null check here to prevent this corner case.
1157 if (clientInfo == null) {
1158 Log.e(TAG, "Unknown connector in callback unregistration");
1159 break;
1160 }
1161
Paul Hud44e1b72023-06-16 02:07:42 +00001162 final ClientRequest request =
1163 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001164 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001165 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001166 break;
1167 }
Paul Hud44e1b72023-06-16 02:07:42 +00001168 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001169 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001170 stopDiscoveryManagerRequest(
1171 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001172 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001173 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001174 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001175 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001176 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001177 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001178 }
paulhu2b9ed952022-02-10 21:58:32 +08001179 case MDNS_SERVICE_EVENT:
1180 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001181 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001182 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001183 break;
Paul Hu019621e2023-01-13 23:26:49 +08001184 case MDNS_DISCOVERY_MANAGER_EVENT:
1185 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1186 return NOT_HANDLED;
1187 }
1188 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001189 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1190 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1191 // TODO: Limits the number of registrations created by a given class.
1192 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1193 offloadEngineInfo);
1194 // TODO: Sends all the existing OffloadServiceInfos back.
1195 break;
1196 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1197 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1198 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001199 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001200 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001201 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001202 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001203 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001204
Paul Hud44e1b72023-06-16 02:07:42 +00001205 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001206 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001207 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001208 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001209 Log.e(TAG, String.format(
1210 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001211 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001212 }
1213
1214 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001215 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1216 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001217 // This can happen because of race conditions. For example,
1218 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1219 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001220 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1221 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001222 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001223 }
Paul Hu812e9212023-06-20 06:24:53 +00001224 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1225 if (request == null) {
1226 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1227 return false;
1228 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001229 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001230 Log.d(TAG, String.format(
1231 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001232 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001233 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001234 case IMDnsEventListener.SERVICE_FOUND: {
1235 final DiscoveryInfo info = (DiscoveryInfo) obj;
1236 final String name = info.serviceName;
1237 final String type = info.registrationType;
1238 servInfo = new NsdServiceInfo(name, type);
1239 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001240 if (foundNetId == 0L) {
1241 // Ignore services that do not have a Network: they are not usable
1242 // by apps, as they would need privileged permissions to use
1243 // interfaces that do not have an associated Network.
1244 break;
1245 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001246 if (foundNetId == INetd.DUMMY_NET_ID) {
1247 // Ignore services on the dummy0 interface: they are only seen when
1248 // discovering locally advertised services, and are not reachable
1249 // through that interface.
1250 break;
1251 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001252 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001253
1254 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001255 break;
paulhu2b9ed952022-02-10 21:58:32 +08001256 }
1257 case IMDnsEventListener.SERVICE_LOST: {
1258 final DiscoveryInfo info = (DiscoveryInfo) obj;
1259 final String name = info.serviceName;
1260 final String type = info.registrationType;
1261 final int lostNetId = info.netId;
1262 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001263 // The network could be set to null (netId 0) if it was torn down when the
1264 // service is lost
1265 // TODO: avoid returning null in that case, possibly by remembering
1266 // found services on the same interface index and their network at the time
1267 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001268 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001269 break;
paulhu2b9ed952022-02-10 21:58:32 +08001270 }
1271 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001272 clientInfo.onDiscoverServicesFailed(clientRequestId,
1273 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1274 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275 break;
paulhu2b9ed952022-02-10 21:58:32 +08001276 case IMDnsEventListener.SERVICE_REGISTERED: {
1277 final RegistrationInfo info = (RegistrationInfo) obj;
1278 final String name = info.serviceName;
1279 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001280 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001281 transactionId,
1282 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001283 break;
paulhu2b9ed952022-02-10 21:58:32 +08001284 }
1285 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001286 clientInfo.onRegisterServiceFailed(clientRequestId,
1287 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001288 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001289 break;
paulhu2b9ed952022-02-10 21:58:32 +08001290 case IMDnsEventListener.SERVICE_RESOLVED: {
1291 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001292 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001293 final String fullName = info.serviceFullName;
1294 while (index < fullName.length() && fullName.charAt(index) != '.') {
1295 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001296 ++index;
1297 }
1298 ++index;
1299 }
paulhu2b9ed952022-02-10 21:58:32 +08001300 if (index >= fullName.length()) {
1301 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001302 break;
1303 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001304
paulhube186602022-04-12 07:18:23 +00001305 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001306 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001307 String type = rest.replace(".local.", "");
1308
Paul Hu30bd70d2023-02-07 13:20:56 +00001309 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001310 serviceInfo.setServiceName(name);
1311 serviceInfo.setServiceType(type);
1312 serviceInfo.setPort(info.port);
1313 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001314 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001315
Paul Hud44e1b72023-06-16 02:07:42 +00001316 stopResolveService(transactionId);
1317 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001318
Paul Hud44e1b72023-06-16 02:07:42 +00001319 final int transactionId2 = getUniqueId();
1320 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1321 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001322 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001323 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001324 clientInfo.onResolveServiceFailed(clientRequestId,
1325 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1326 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001327 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001328 }
1329 break;
paulhu2b9ed952022-02-10 21:58:32 +08001330 }
1331 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001332 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001333 stopResolveService(transactionId);
1334 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001335 clientInfo.onResolveServiceFailed(clientRequestId,
1336 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1337 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001338 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001339 break;
paulhu2b9ed952022-02-10 21:58:32 +08001340 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001342 stopGetAddrInfo(transactionId);
1343 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001344 clientInfo.onResolveServiceFailed(clientRequestId,
1345 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1346 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001347 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001348 break;
paulhu2b9ed952022-02-10 21:58:32 +08001349 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001350 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001351 final GetAddressInfo info = (GetAddressInfo) obj;
1352 final String address = info.address;
1353 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001354 InetAddress serviceHost = null;
1355 try {
paulhu2b9ed952022-02-10 21:58:32 +08001356 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001357 } catch (UnknownHostException e) {
1358 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1359 }
1360
1361 // If the resolved service is on an interface without a network, consider it
1362 // as a failure: it would not be usable by apps as they would need
1363 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001364 if (netId != NETID_UNSET && serviceHost != null) {
1365 clientInfo.mResolvedService.setHost(serviceHost);
1366 setServiceNetworkForCallback(clientInfo.mResolvedService,
1367 netId, info.interfaceIdx);
1368 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001369 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001370 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001371 clientInfo.onResolveServiceFailed(clientRequestId,
1372 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1373 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001374 }
Paul Hud44e1b72023-06-16 02:07:42 +00001375 stopGetAddrInfo(transactionId);
1376 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001377 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001378 break;
paulhu2b9ed952022-02-10 21:58:32 +08001379 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001380 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001381 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001382 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001383 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001384 }
Paul Hu019621e2023-01-13 23:26:49 +08001385
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001386 @Nullable
1387 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1388 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001389 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001390 final String[] typeArray = serviceInfo.getServiceType();
1391 final String joinedType;
1392 if (typeArray.length == 0
1393 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1394 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1395 + Arrays.toString(typeArray));
1396 return null;
1397 } else {
1398 joinedType = TextUtils.join(".",
1399 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1400 }
1401 final String serviceType;
1402 switch (code) {
1403 case NsdManager.SERVICE_FOUND:
1404 case NsdManager.SERVICE_LOST:
1405 // For consistency with historical behavior, discovered service types have
1406 // a dot at the end.
1407 serviceType = joinedType + ".";
1408 break;
1409 case RESOLVE_SERVICE_SUCCEEDED:
1410 // For consistency with historical behavior, resolved service types have
1411 // a dot at the beginning.
1412 serviceType = "." + joinedType;
1413 break;
1414 default:
1415 serviceType = joinedType;
1416 break;
1417 }
Paul Hu019621e2023-01-13 23:26:49 +08001418 final String serviceName = serviceInfo.getServiceInstanceName();
1419 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1420 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001421 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1422 // network for Tethering interface. In other words, the network == null means the
1423 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001424 setServiceNetworkForCallback(
1425 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001426 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001427 serviceInfo.getInterfaceIndex());
1428 return servInfo;
1429 }
1430
1431 private boolean handleMdnsDiscoveryManagerEvent(
1432 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001433 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001434 if (clientInfo == null) {
1435 Log.e(TAG, String.format(
1436 "id %d for %d has no client mapping", transactionId, code));
1437 return false;
1438 }
1439
1440 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001441 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001442 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1443 if (request == null) {
1444 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1445 return false;
1446 }
1447
1448 // Deal with the discovery sent callback
1449 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1450 request.onQuerySent();
1451 return true;
1452 }
1453
1454 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001455 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1456 // Errors are already logged if null
1457 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001458 mServiceLogs.log(String.format(
1459 "MdnsDiscoveryManager event code=%s transactionId=%d",
1460 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001461 switch (code) {
1462 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001463 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001464 break;
1465 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001466 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001467 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001468 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1469 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001470 info.setPort(serviceInfo.getPort());
1471
1472 Map<String, String> attrs = serviceInfo.getAttributes();
1473 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1474 final String key = kv.getKey();
1475 try {
1476 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1477 } catch (IllegalArgumentException e) {
1478 Log.e(TAG, "Invalid attribute", e);
1479 }
1480 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001481 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001482 if (addresses.size() != 0) {
1483 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001484 request.setServiceFromCache(event.mIsServiceFromCache);
1485 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001486 } else {
1487 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001488 clientInfo.onResolveServiceFailed(clientRequestId,
1489 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1490 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001491 }
1492
1493 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001494 if (!(request instanceof DiscoveryManagerRequest)) {
1495 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1496 break;
1497 }
Paul Hud44e1b72023-06-16 02:07:42 +00001498 stopDiscoveryManagerRequest(
1499 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001500 break;
1501 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001502 case NsdManager.SERVICE_UPDATED: {
1503 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1504 info.setPort(serviceInfo.getPort());
1505
1506 Map<String, String> attrs = serviceInfo.getAttributes();
1507 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1508 final String key = kv.getKey();
1509 try {
1510 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1511 } catch (IllegalArgumentException e) {
1512 Log.e(TAG, "Invalid attribute", e);
1513 }
1514 }
1515
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001516 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001517 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001518 clientInfo.onServiceUpdated(clientRequestId, info, request);
1519 // Set the ServiceFromCache flag only if the service is actually being
1520 // retrieved from the cache. This flag should not be overridden by later
1521 // service updates, which may not be cached.
1522 if (event.mIsServiceFromCache) {
1523 request.setServiceFromCache(true);
1524 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001525 break;
1526 }
1527 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001528 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001529 break;
Paul Hu019621e2023-01-13 23:26:49 +08001530 default:
1531 return false;
1532 }
1533 return true;
1534 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001535 }
1536 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001537
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001538 @NonNull
1539 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1540 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1541 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1542 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1543 for (String ipv4Address : v4Addrs) {
1544 try {
1545 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1546 } catch (IllegalArgumentException e) {
1547 Log.wtf(TAG, "Invalid ipv4 address", e);
1548 }
1549 }
1550 for (String ipv6Address : v6Addrs) {
1551 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001552 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1553 ipv6Address);
1554 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1555 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001556 Log.wtf(TAG, "Invalid ipv6 address", e);
1557 }
1558 }
1559 return addresses;
1560 }
1561
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001562 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1563 switch (netId) {
1564 case NETID_UNSET:
1565 info.setNetwork(null);
1566 break;
1567 case INetd.LOCAL_NET_ID:
1568 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1569 // visible / usable for apps, so do not return it. Store the interface
1570 // index instead, so at least if the client tries to resolve the service
1571 // with that NsdServiceInfo, it will be done on the same interface.
1572 // If they recreate the NsdServiceInfo themselves, resolution would be
1573 // done on all interfaces as before T, which should also work.
1574 info.setNetwork(null);
1575 info.setInterfaceIndex(ifaceIdx);
1576 break;
1577 default:
1578 info.setNetwork(new Network(netId));
1579 }
1580 }
1581
paulhube186602022-04-12 07:18:23 +00001582 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1583 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1584 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1585 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1586 private String unescape(String s) {
1587 StringBuilder sb = new StringBuilder(s.length());
1588 for (int i = 0; i < s.length(); ++i) {
1589 char c = s.charAt(i);
1590 if (c == '\\') {
1591 if (++i >= s.length()) {
1592 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1593 break;
1594 }
1595 c = s.charAt(i);
1596 if (c != '.' && c != '\\') {
1597 if (i + 2 >= s.length()) {
1598 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1599 break;
1600 }
1601 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1602 + (s.charAt(i + 2) - '0'));
1603 i += 2;
1604 }
1605 }
1606 sb.append(c);
1607 }
1608 return sb.toString();
1609 }
1610
Paul Hu7445e3d2023-03-03 15:14:00 +08001611 /**
1612 * Check the given service type is valid and construct it to a service type
1613 * which can use for discovery / resolution service.
1614 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001615 * <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 +08001616 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1617 * underscore; they are alphanumerical characters or dashes or underscore, except the
1618 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1619 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001620 * <p>The subtype may also be specified with a comma after the service type, for example
1621 * _type._tcp,_subtype.
1622 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001623 * @param serviceType the request service type for discovery / resolution service
1624 * @return constructed service type or null if the given service type is invalid.
1625 */
1626 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001627 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001628 if (TextUtils.isEmpty(serviceType)) return null;
1629
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001630 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001631 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001632 // Optional leading subtype (_subtype._type._tcp)
1633 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1634 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1635 // Actual type (_type._tcp.local)
1636 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001637 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001638 // e.g. allow "_type._tcp.local."
1639 + "\\.?"
1640 // Optional subtype after comma, for "_type._tcp,_subtype" format
1641 + "(?:,(" + typeOrSubtypePattern + "))?"
1642 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001643 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1644 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001645 // Use the subtype either at the beginning or after the comma
1646 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1647 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001648 }
1649
Hugo Benichi803a2f02017-04-24 11:35:06 +09001650 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001651 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001652 this(ctx, handler, cleanupDelayMs, new Dependencies());
1653 }
1654
1655 @VisibleForTesting
1656 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001657 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001658 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001659 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001660 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001661 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1662 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001663 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001664
Paul Hu14667de2023-04-17 22:42:47 +08001665 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001666 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001667 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1668 // address events are received.
1669 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001670
1671 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1672 // startBootstrapServices).
1673 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1674 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1675 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1676 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1677 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1678 mRunningAppActiveImportanceCutoff);
1679
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001680 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001681 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1682 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001683 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001684 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001685 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1686 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001687 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001688 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001689 }
1690
1691 /**
1692 * Dependencies of NsdService, for injection in tests.
1693 */
1694 @VisibleForTesting
1695 public static class Dependencies {
1696 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001697 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001698 *
1699 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001700 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001701 */
1702 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001703 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1704 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001705 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001706 }
1707
1708 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001709 * Check whether the MdnsAdvertiser feature is enabled.
1710 *
1711 * @param context The global context information about an app environment.
1712 * @return true if the MdnsAdvertiser feature is enabled.
1713 */
1714 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001715 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1716 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1717 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001718 }
1719
1720 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001721 * Get the type allowlist flag value.
1722 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1723 */
1724 @Nullable
1725 public String getTypeAllowlistFlags() {
1726 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1727 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1728 }
1729
1730 /**
1731 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1732 */
1733 public boolean isFeatureEnabled(Context context, String feature) {
1734 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1735 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1736 }
1737
1738 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001739 * @see MdnsDiscoveryManager
1740 */
1741 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001742 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001743 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1744 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001745 }
1746
1747 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001748 * @see MdnsAdvertiser
1749 */
1750 public MdnsAdvertiser makeMdnsAdvertiser(
1751 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001752 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1753 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001754 }
1755
1756 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001757 * @see MdnsSocketProvider
1758 */
Paul Hu14667de2023-04-17 22:42:47 +08001759 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001760 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1761 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1762 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1763 }
1764
1765 /**
1766 * @see DeviceConfig#getInt(String, String, int)
1767 */
1768 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1769 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1770 }
1771
1772 /**
1773 * @see Binder#getCallingUid()
1774 */
1775 public int getCallingUid() {
1776 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001777 }
Paul Hu777ed052023-06-19 13:35:15 +00001778
1779 /**
1780 * @see NetworkNsdReportedMetrics
1781 */
1782 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1783 boolean isLegacy, int clientId) {
1784 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1785 }
1786
1787 /**
1788 * @see MdnsUtils.Clock
1789 */
1790 public Clock makeClock() {
1791 return new Clock();
1792 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001793 }
1794
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001795 /**
1796 * Return whether a type is allowlisted to use the Java backend.
1797 * @param type The service type
1798 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1799 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1800 */
1801 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1802 @NonNull String flagPrefix) {
1803 if (type == null) return false;
1804 final String typesConfig = mDeps.getTypeAllowlistFlags();
1805 if (TextUtils.isEmpty(typesConfig)) return false;
1806
1807 final String mappingPrefix = type + ":";
1808 String mappedFlag = null;
1809 for (String mapping : TextUtils.split(typesConfig, ",")) {
1810 if (mapping.startsWith(mappingPrefix)) {
1811 mappedFlag = mapping.substring(mappingPrefix.length());
1812 break;
1813 }
1814 }
1815
1816 if (mappedFlag == null) return false;
1817
1818 return mDeps.isFeatureEnabled(mContext,
1819 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1820 }
1821
1822 private boolean useDiscoveryManagerForType(@Nullable String type) {
1823 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1824 }
1825
1826 private boolean useAdvertiserForType(@Nullable String type) {
1827 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1828 }
1829
paulhu1b35e822022-04-08 14:48:41 +08001830 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001831 HandlerThread thread = new HandlerThread(TAG);
1832 thread.start();
1833 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001834 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001835 return service;
1836 }
1837
paulhu2b9ed952022-02-10 21:58:32 +08001838 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1839 private final StateMachine mStateMachine;
1840
1841 MDnsEventCallback(StateMachine sm) {
1842 mStateMachine = sm;
1843 }
1844
1845 @Override
1846 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1847 mStateMachine.sendMessage(
1848 MDNS_SERVICE_EVENT, status.result, status.id, status);
1849 }
1850
1851 @Override
1852 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1853 mStateMachine.sendMessage(
1854 MDNS_SERVICE_EVENT, status.result, status.id, status);
1855 }
1856
1857 @Override
1858 public void onServiceResolutionStatus(final ResolutionInfo status) {
1859 mStateMachine.sendMessage(
1860 MDNS_SERVICE_EVENT, status.result, status.id, status);
1861 }
1862
1863 @Override
1864 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1865 mStateMachine.sendMessage(
1866 MDNS_SERVICE_EVENT, status.result, status.id, status);
1867 }
1868
1869 @Override
1870 public int getInterfaceVersion() throws RemoteException {
1871 return this.VERSION;
1872 }
1873
1874 @Override
1875 public String getInterfaceHash() throws RemoteException {
1876 return this.HASH;
1877 }
1878 }
1879
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001880 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1881 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1882 final int count = mOffloadEngines.beginBroadcast();
1883 try {
1884 for (int i = 0; i < count; i++) {
1885 final OffloadEngineInfo offloadEngineInfo =
1886 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1887 final String interfaceName = offloadEngineInfo.mInterfaceName;
1888 if (!targetInterfaceName.equals(interfaceName)
1889 || ((offloadEngineInfo.mOffloadType
1890 & offloadServiceInfo.getOffloadType()) == 0)) {
1891 continue;
1892 }
1893 try {
1894 if (isRemove) {
1895 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1896 offloadServiceInfo);
1897 } else {
1898 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1899 offloadServiceInfo);
1900 }
1901 } catch (RemoteException e) {
1902 // Can happen in regular cases, do not log a stacktrace
1903 Log.i(TAG, "Failed to send offload callback, remote died", e);
1904 }
1905 }
1906 } finally {
1907 mOffloadEngines.finishBroadcast();
1908 }
1909 }
1910
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001911 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001912 // TODO: add a callback to notify when a service is being added on each interface (as soon
1913 // as probing starts), and call mOffloadCallbacks. This callback is for
1914 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1915
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001916 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001917 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1918 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1919 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001920 if (clientInfo == null) return;
1921
Paul Hud44e1b72023-06-16 02:07:42 +00001922 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1923 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001924
1925 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1926 // historical behavior.
1927 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001928 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001929 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1930 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001931 }
1932
1933 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001934 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1935 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001936 if (clientInfo == null) return;
1937
Paul Hud44e1b72023-06-16 02:07:42 +00001938 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1939 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001940 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1941 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001942 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001943 }
1944
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001945 @Override
1946 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1947 @NonNull OffloadServiceInfo offloadServiceInfo) {
1948 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1949 }
1950
1951 @Override
1952 public void onOffloadStop(@NonNull String interfaceName,
1953 @NonNull OffloadServiceInfo offloadServiceInfo) {
1954 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1955 }
1956
Paul Hud44e1b72023-06-16 02:07:42 +00001957 private ClientInfo getClientInfoOrLog(int transactionId) {
1958 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001959 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001960 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001961 }
1962 return clientInfo;
1963 }
1964
Paul Hud44e1b72023-06-16 02:07:42 +00001965 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1966 final int clientRequestId = info.getClientRequestId(transactionId);
1967 if (clientRequestId < 0) {
1968 Log.e(TAG, String.format(
1969 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001970 }
Paul Hud44e1b72023-06-16 02:07:42 +00001971 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001972 }
1973 }
1974
Paul Hu2e0a88c2023-03-09 16:05:01 +08001975 private static class ConnectorArgs {
1976 @NonNull public final NsdServiceConnector connector;
1977 @NonNull public final INsdManagerCallback callback;
1978 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001979 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001980
1981 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001982 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001983 this.connector = connector;
1984 this.callback = callback;
1985 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001986 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001987 }
1988 }
1989
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001990 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001991 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001993 final int uid = mDeps.getCallingUid();
1994 if (cb == null) {
1995 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1996 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001997 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001998 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001999 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002000 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002001 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002002 }
2003
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002004 private static class ListenerArgs {
2005 public final NsdServiceConnector connector;
2006 public final NsdServiceInfo serviceInfo;
2007 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2008 this.connector = connector;
2009 this.serviceInfo = serviceInfo;
2010 }
2011 }
2012
2013 private class NsdServiceConnector extends INsdServiceConnector.Stub
2014 implements IBinder.DeathRecipient {
2015 @Override
2016 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2017 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2018 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2019 new ListenerArgs(this, serviceInfo)));
2020 }
2021
2022 @Override
2023 public void unregisterService(int listenerKey) {
2024 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2025 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2026 new ListenerArgs(this, null)));
2027 }
2028
2029 @Override
2030 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2031 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2032 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2033 new ListenerArgs(this, serviceInfo)));
2034 }
2035
2036 @Override
2037 public void stopDiscovery(int listenerKey) {
2038 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2039 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2040 }
2041
2042 @Override
2043 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2044 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2045 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2046 new ListenerArgs(this, serviceInfo)));
2047 }
2048
2049 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002050 public void stopResolution(int listenerKey) {
2051 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2052 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2053 }
2054
2055 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002056 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2057 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2058 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2059 new ListenerArgs(this, serviceInfo)));
2060 }
2061
2062 @Override
2063 public void unregisterServiceInfoCallback(int listenerKey) {
2064 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2065 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2066 new ListenerArgs(this, null)));
2067 }
2068
2069 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002070 public void startDaemon() {
2071 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2072 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2073 }
2074
2075 @Override
2076 public void binderDied() {
2077 mNsdStateMachine.sendMessage(
2078 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002079
2080 }
2081
2082 @Override
2083 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2084 @OffloadEngine.OffloadCapability long offloadCapabilities,
2085 @OffloadEngine.OffloadType long offloadTypes) {
2086 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2087 // it may not be possible for all the callers of this API to have it.
2088 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2089 Objects.requireNonNull(ifaceName);
2090 Objects.requireNonNull(cb);
2091 mNsdStateMachine.sendMessage(
2092 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2093 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2094 offloadTypes)));
2095 }
2096
2097 @Override
2098 public void unregisterOffloadEngine(IOffloadEngine cb) {
2099 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2100 // it may not be possible for all the callers of this API to have it.
2101 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2102 Objects.requireNonNull(cb);
2103 mNsdStateMachine.sendMessage(
2104 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002105 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002106 }
2107
Hugo Benichi912db992017-04-24 16:41:03 +09002108 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002109 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002110 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002111 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2112 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002113 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002114 }
2115
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002116 private int getUniqueId() {
2117 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2118 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002119 }
2120
Paul Hud44e1b72023-06-16 02:07:42 +00002121 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002122 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002123 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002124 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002125 String name = service.getServiceName();
2126 String type = service.getServiceType();
2127 int port = service.getPort();
2128 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002129 final int registerInterface = getNetworkInterfaceIndex(service);
2130 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002131 Log.e(TAG, "Interface to register service on not found");
2132 return false;
2133 }
Paul Hud44e1b72023-06-16 02:07:42 +00002134 return mMDnsManager.registerService(
2135 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002136 }
2137
Paul Hud44e1b72023-06-16 02:07:42 +00002138 private boolean unregisterService(int transactionId) {
2139 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002140 }
2141
Paul Hud44e1b72023-06-16 02:07:42 +00002142 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002143 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002144 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2145 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002146 Log.e(TAG, "Interface to discover service on not found");
2147 return false;
2148 }
Paul Hud44e1b72023-06-16 02:07:42 +00002149 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002150 }
2151
Paul Hud44e1b72023-06-16 02:07:42 +00002152 private boolean stopServiceDiscovery(int transactionId) {
2153 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002154 }
2155
Paul Hud44e1b72023-06-16 02:07:42 +00002156 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002157 final String name = service.getServiceName();
2158 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002159 final int resolveInterface = getNetworkInterfaceIndex(service);
2160 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002161 Log.e(TAG, "Interface to resolve service on not found");
2162 return false;
2163 }
Paul Hud44e1b72023-06-16 02:07:42 +00002164 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002165 }
2166
2167 /**
2168 * Guess the interface to use to resolve or discover a service on a specific network.
2169 *
2170 * This is an imperfect guess, as for example the network may be gone or not yet fully
2171 * registered. This is fine as failing is correct if the network is gone, and a client
2172 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2173 * this is to support the legacy mdnsresponder implementation, which historically resolved
2174 * services on an unspecified network.
2175 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002176 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2177 final Network network = serviceInfo.getNetwork();
2178 if (network == null) {
2179 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2180 // provided by NsdService from discovery results, and the service was found on an
2181 // interface that has no app-usable Network).
2182 if (serviceInfo.getInterfaceIndex() != 0) {
2183 return serviceInfo.getInterfaceIndex();
2184 }
2185 return IFACE_IDX_ANY;
2186 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002187
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002188 String interfaceName = getNetworkInterfaceName(network);
2189 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002190 return IFACE_IDX_ANY;
2191 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002192 return getNetworkInterfaceIndexByName(interfaceName);
2193 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002194
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002195 private String getNetworkInterfaceName(@Nullable Network network) {
2196 if (network == null) {
2197 return null;
2198 }
2199 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2200 if (cm == null) {
2201 Log.wtf(TAG, "No ConnectivityManager");
2202 return null;
2203 }
2204 final LinkProperties lp = cm.getLinkProperties(network);
2205 if (lp == null) {
2206 return null;
2207 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002208 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002209 return lp.getInterfaceName();
2210 }
2211
2212 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002213 final NetworkInterface iface;
2214 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002215 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002216 } catch (SocketException e) {
2217 Log.e(TAG, "Error querying interface", e);
2218 return IFACE_IDX_ANY;
2219 }
2220
2221 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002222 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002223 return IFACE_IDX_ANY;
2224 }
2225
2226 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002227 }
2228
Paul Hud44e1b72023-06-16 02:07:42 +00002229 private boolean stopResolveService(int transactionId) {
2230 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002231 }
2232
Paul Hud44e1b72023-06-16 02:07:42 +00002233 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2234 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002235 }
2236
Paul Hud44e1b72023-06-16 02:07:42 +00002237 private boolean stopGetAddrInfo(int transactionId) {
2238 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002239 }
2240
2241 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002242 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2243 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002244
Paul Hub2e67d32023-04-18 05:50:14 +00002245 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2246 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002247 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002248
2249 // Dump service and clients logs
2250 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002251 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002252 pw.increaseIndent();
2253 mServiceLogs.reverseDump(pw);
2254 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002255 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002256
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002257 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002258 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002259 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002260 private int mFoundServiceCount = 0;
2261 private int mLostServiceCount = 0;
2262 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002263 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002264 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002265
Paul Hu812e9212023-06-20 06:24:53 +00002266 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002267 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002268 mStartTimeMs = startTimeMs;
2269 }
2270
Paul Hu812e9212023-06-20 06:24:53 +00002271 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002272 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002273 }
Paul Hu812e9212023-06-20 06:24:53 +00002274
2275 public void onServiceFound(String serviceName) {
2276 mFoundServiceCount++;
2277 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2278 mServices.add(serviceName);
2279 }
2280 }
2281
2282 public void onServiceLost() {
2283 mLostServiceCount++;
2284 }
2285
2286 public int getFoundServiceCount() {
2287 return mFoundServiceCount;
2288 }
2289
2290 public int getLostServiceCount() {
2291 return mLostServiceCount;
2292 }
2293
2294 public int getServicesCount() {
2295 return mServices.size();
2296 }
Paul Hua6bc4632023-06-26 01:18:29 +00002297
2298 public void setServiceFromCache(boolean isServiceFromCache) {
2299 mIsServiceFromCache = isServiceFromCache;
2300 }
2301
2302 public boolean isServiceFromCache() {
2303 return mIsServiceFromCache;
2304 }
Paul Hubad6fe92023-07-24 21:25:22 +08002305
2306 public void onQuerySent() {
2307 mSentQueryCount++;
2308 }
2309
2310 public int getSentQueryCount() {
2311 return mSentQueryCount;
2312 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002313 }
2314
2315 private static class LegacyClientRequest extends ClientRequest {
2316 private final int mRequestCode;
2317
Paul Hu812e9212023-06-20 06:24:53 +00002318 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2319 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002320 mRequestCode = requestCode;
2321 }
2322 }
2323
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002324 private abstract static class JavaBackendClientRequest extends ClientRequest {
2325 @Nullable
2326 private final Network mRequestedNetwork;
2327
Paul Hu777ed052023-06-19 13:35:15 +00002328 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002329 long startTimeMs) {
2330 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002331 mRequestedNetwork = requestedNetwork;
2332 }
2333
2334 @Nullable
2335 public Network getRequestedNetwork() {
2336 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002337 }
2338 }
2339
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002340 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002341 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002342 long startTimeMs) {
2343 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002344 }
2345 }
2346
2347 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002348 @NonNull
2349 private final MdnsListener mListener;
2350
Paul Hud44e1b72023-06-16 02:07:42 +00002351 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002352 @Nullable Network requestedNetwork, long startTimeMs) {
2353 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002354 mListener = listener;
2355 }
2356 }
2357
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002358 /* Information tracked per client */
2359 private class ClientInfo {
2360
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002361 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002362 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002363 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002364 private NsdServiceInfo mResolvedService;
2365
Paul Hud44e1b72023-06-16 02:07:42 +00002366 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002367 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002368
Luke Huangf7277ed2021-07-12 21:15:10 +08002369 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002370 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002371 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002372 // The flag of using java backend if the client's target SDK >= U
2373 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002374 // Store client logs
2375 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002376 // Report the nsd metrics data
2377 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002378
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002379 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002380 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002381 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002382 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002383 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002384 mClientLogs = sharedLog;
2385 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002386 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002387 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002388
2389 @Override
2390 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002391 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002392 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002393 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002394 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2395 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002396 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002397 int clientRequestId = mClientRequests.keyAt(i);
2398 sb.append("clientRequestId ")
2399 .append(clientRequestId)
2400 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002401 .append(" type ").append(
2402 mClientRequests.valueAt(i).getClass().getSimpleName())
2403 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002404 }
2405 return sb.toString();
2406 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002407
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002408 private boolean isPreSClient() {
2409 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002410 }
2411
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002412 private void setPreSClient() {
2413 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002414 }
2415
Paul Hu812e9212023-06-20 06:24:53 +00002416 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002417 final MdnsListener listener =
2418 ((DiscoveryManagerRequest) request).mListener;
2419 mMdnsDiscoveryManager.unregisterListener(
2420 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002421 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002422 }
2423
Dave Plattfeff2af2014-03-07 14:48:22 -08002424 // Remove any pending requests from the global map when we get rid of a client,
2425 // and send cancellations to the daemon.
2426 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002427 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002428 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002429 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002430 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002431 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002432 final int transactionId = request.mTransactionId;
2433 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002434 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002435 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2436 + " transactionId " + transactionId
2437 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002438 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002439
2440 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002441 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2442 if (listener instanceof DiscoveryListener) {
2443 mMetrics.reportServiceDiscoveryStop(transactionId,
2444 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2445 request.getFoundServiceCount(),
2446 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002447 request.getServicesCount(),
2448 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002449 } else if (listener instanceof ResolutionListener) {
2450 mMetrics.reportServiceResolutionStop(transactionId,
2451 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002452 } else if (listener instanceof ServiceInfoListener) {
2453 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2454 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2455 request.getFoundServiceCount(),
2456 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002457 request.isServiceFromCache(),
2458 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002459 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002460 continue;
2461 }
2462
2463 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002464 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002465 mMetrics.reportServiceUnregistration(transactionId,
2466 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002467 continue;
2468 }
2469
2470 if (!(request instanceof LegacyClientRequest)) {
2471 throw new IllegalStateException("Unknown request type: " + request.getClass());
2472 }
2473
2474 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002475 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002476 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002477 mMetrics.reportServiceDiscoveryStop(transactionId,
2478 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2479 request.getFoundServiceCount(),
2480 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002481 request.getServicesCount(),
2482 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002483 break;
2484 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002485 stopResolveService(transactionId);
Paul Hu60149052023-07-31 14:26:08 +08002486 mMetrics.reportServiceResolutionStop(transactionId,
2487 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002488 break;
2489 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002490 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002491 mMetrics.reportServiceUnregistration(transactionId,
2492 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002493 break;
2494 default:
2495 break;
2496 }
2497 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002498 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002499 updateMulticastLock();
2500 }
2501
2502 /**
2503 * Returns true if this client has any Java backend request that requests one of the given
2504 * networks.
2505 */
2506 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2507 for (int i = 0; i < mClientRequests.size(); i++) {
2508 final ClientRequest req = mClientRequests.valueAt(i);
2509 if (!(req instanceof JavaBackendClientRequest)) {
2510 continue;
2511 }
2512 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2513 .getRequestedNetwork();
2514 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2515 return true;
2516 }
2517 }
2518 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002519 }
2520
Paul Hud44e1b72023-06-16 02:07:42 +00002521 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2522 // transaction id, return the corresponding client request id.
2523 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002524 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002525 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002526 return mClientRequests.keyAt(i);
2527 }
Christopher Lane74411222014-04-25 18:39:07 -07002528 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002529 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002530 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002531
Paul Hub2e67d32023-04-18 05:50:14 +00002532 private void log(String message) {
2533 mClientLogs.log(message);
2534 }
2535
Paul Hu812e9212023-06-20 06:24:53 +00002536 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2537 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002538 try {
2539 mCb.onDiscoverServicesStarted(listenerKey, info);
2540 } catch (RemoteException e) {
2541 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2542 }
2543 }
Paul Hu812e9212023-06-20 06:24:53 +00002544 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2545 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2546 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002547
Paul Hu812e9212023-06-20 06:24:53 +00002548 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2549 long durationMs) {
2550 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002551 try {
2552 mCb.onDiscoverServicesFailed(listenerKey, error);
2553 } catch (RemoteException e) {
2554 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2555 }
2556 }
2557
Paul Hu812e9212023-06-20 06:24:53 +00002558 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2559 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002560 try {
2561 mCb.onServiceFound(listenerKey, info);
2562 } catch (RemoteException e) {
2563 Log.e(TAG, "Error calling onServiceFound(", e);
2564 }
2565 }
2566
Paul Hu812e9212023-06-20 06:24:53 +00002567 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2568 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002569 try {
2570 mCb.onServiceLost(listenerKey, info);
2571 } catch (RemoteException e) {
2572 Log.e(TAG, "Error calling onServiceLost(", e);
2573 }
2574 }
2575
2576 void onStopDiscoveryFailed(int listenerKey, int error) {
2577 try {
2578 mCb.onStopDiscoveryFailed(listenerKey, error);
2579 } catch (RemoteException e) {
2580 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2581 }
2582 }
2583
Paul Hu812e9212023-06-20 06:24:53 +00002584 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2585 mMetrics.reportServiceDiscoveryStop(
2586 request.mTransactionId,
2587 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2588 request.getFoundServiceCount(),
2589 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002590 request.getServicesCount(),
2591 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002592 try {
2593 mCb.onStopDiscoverySucceeded(listenerKey);
2594 } catch (RemoteException e) {
2595 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2596 }
2597 }
2598
Paul Hu777ed052023-06-19 13:35:15 +00002599 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002600 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002601 }
2602
2603 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2604 long durationMs) {
2605 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002606 try {
2607 mCb.onRegisterServiceFailed(listenerKey, error);
2608 } catch (RemoteException e) {
2609 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2610 }
2611 }
2612
Paul Hu777ed052023-06-19 13:35:15 +00002613 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2614 long durationMs) {
2615 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002616 try {
2617 mCb.onRegisterServiceSucceeded(listenerKey, info);
2618 } catch (RemoteException e) {
2619 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2620 }
2621 }
2622
2623 void onUnregisterServiceFailed(int listenerKey, int error) {
2624 try {
2625 mCb.onUnregisterServiceFailed(listenerKey, error);
2626 } catch (RemoteException e) {
2627 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2628 }
2629 }
2630
Paul Hu777ed052023-06-19 13:35:15 +00002631 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2632 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002633 try {
2634 mCb.onUnregisterServiceSucceeded(listenerKey);
2635 } catch (RemoteException e) {
2636 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2637 }
2638 }
2639
Paul Hua6bc4632023-06-26 01:18:29 +00002640 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2641 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2642 }
2643
2644 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2645 long durationMs) {
2646 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002647 try {
2648 mCb.onResolveServiceFailed(listenerKey, error);
2649 } catch (RemoteException e) {
2650 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2651 }
2652 }
2653
Paul Hua6bc4632023-06-26 01:18:29 +00002654 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2655 ClientRequest request) {
2656 mMetrics.reportServiceResolved(
2657 request.mTransactionId,
2658 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002659 request.isServiceFromCache(),
2660 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002661 try {
2662 mCb.onResolveServiceSucceeded(listenerKey, info);
2663 } catch (RemoteException e) {
2664 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2665 }
2666 }
Paul Hub58deb72022-12-26 09:24:42 +00002667
2668 void onStopResolutionFailed(int listenerKey, int error) {
2669 try {
2670 mCb.onStopResolutionFailed(listenerKey, error);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2673 }
2674 }
2675
Paul Hu60149052023-07-31 14:26:08 +08002676 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2677 mMetrics.reportServiceResolutionStop(
2678 request.mTransactionId,
2679 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002680 try {
2681 mCb.onStopResolutionSucceeded(listenerKey);
2682 } catch (RemoteException e) {
2683 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2684 }
2685 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002686
2687 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002688 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002689 try {
2690 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2691 } catch (RemoteException e) {
2692 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2693 }
2694 }
2695
Paul Huddce5912023-08-01 10:26:49 +08002696 void onServiceInfoCallbackRegistered(int transactionId) {
2697 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2698 }
2699
2700 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2701 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002702 try {
2703 mCb.onServiceUpdated(listenerKey, info);
2704 } catch (RemoteException e) {
2705 Log.e(TAG, "Error calling onServiceUpdated", e);
2706 }
2707 }
2708
Paul Huddce5912023-08-01 10:26:49 +08002709 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2710 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002711 try {
2712 mCb.onServiceUpdatedLost(listenerKey);
2713 } catch (RemoteException e) {
2714 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2715 }
2716 }
2717
Paul Huddce5912023-08-01 10:26:49 +08002718 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2719 mMetrics.reportServiceInfoCallbackUnregistered(
2720 request.mTransactionId,
2721 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2722 request.getFoundServiceCount(),
2723 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002724 request.isServiceFromCache(),
2725 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002726 try {
2727 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2728 } catch (RemoteException e) {
2729 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2730 }
2731 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002732 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002733}