blob: c951e9840cc7ac5e1b1f6e735e184f0c34424cc1 [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;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090020import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090022import static android.net.NetworkCapabilities.TRANSPORT_VPN;
23import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090024import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080025import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080026import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090027import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090028import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090030import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080031import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
32import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090033import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000034import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090035
Paul Hu23fa2022023-01-13 22:57:24 +080036import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080037import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090038import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080039import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070040import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090041import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090042import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080043import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.LinkProperties;
45import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080046import android.net.mdns.aidl.DiscoveryInfo;
47import android.net.mdns.aidl.GetAddressInfo;
48import android.net.mdns.aidl.IMDnsEventListener;
49import android.net.mdns.aidl.RegistrationInfo;
50import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070051import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.net.nsd.INsdManagerCallback;
53import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090054import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080055import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070056import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080057import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090058import android.net.nsd.OffloadEngine;
59import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090060import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000061import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090062import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080063import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090064import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070066import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090067import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070069import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090070import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080071import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090072import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090073import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090074import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070075import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070076
paulhua262cc12019-08-12 16:25:11 +080077import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000078import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080079import com.android.internal.util.State;
80import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000081import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090082import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090083import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080084import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090085import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080086import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000087import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090089import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080090import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090091import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090092import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080093import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080094import com.android.server.connectivity.mdns.MdnsSearchOptions;
95import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
96import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080097import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090098import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080099
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700100import java.io.FileDescriptor;
101import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900102import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700103import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900104import java.net.NetworkInterface;
105import java.net.SocketException;
106import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800107import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900108import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700109import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800110import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800111import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900112import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000113import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800114import java.util.regex.Matcher;
115import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700117/**
118 * Network Service Discovery Service handles remote service discovery operation requests by
119 * implementing the INsdManager interface.
120 *
121 * @hide
122 */
123public class NsdService extends INsdManager.Stub {
124 private static final String TAG = "NsdService";
125 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900126 /**
127 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
128 * implementation.
129 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800130 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800131 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700132
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900133 /**
134 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
135 * implementation.
136 */
137 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
138
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900139 /**
140 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
141 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
142 *
143 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
144 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
145 *
146 * In which case the flags:
147 * "mdns_discovery_manager_allowlist_mytype_version",
148 * "mdns_advertiser_allowlist_mytype_version",
149 * "mdns_discovery_manager_allowlist_othertype_version",
150 * "mdns_advertiser_allowlist_othertype_version"
151 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
152 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900153 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900154 *
155 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
156 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
157 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
158 */
159 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
160
161 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
162 "mdns_discovery_manager_allowlist_";
163 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
164 "mdns_advertiser_allowlist_";
165 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
166
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900167 @VisibleForTesting
168 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
169 "mdns_config_running_app_active_importance_cutoff";
170 @VisibleForTesting
171 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
172 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
173 private final int mRunningAppActiveImportanceCutoff;
174
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900175 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000176 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900177 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000178 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
179 @VisibleForTesting
180 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800181 private static final int NO_SENT_QUERY_COUNT = 0;
182 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800183 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700184
Hugo Benichi32be63d2017-04-05 14:06:11 +0900185 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900186 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800187 private final MDnsManager mMDnsManager;
188 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900189 @NonNull
190 private final Dependencies mDeps;
191 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800192 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900193 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800194 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900195 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800196 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900197 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900198 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000199 @NonNull
200 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800201 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800202 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800203 // state machine thread. If change this outside state machine, it will need to introduce
204 // synchronization.
205 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800206 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700207
208 /**
209 * Clients receiving asynchronous messages
210 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900211 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700212
Paul Hud44e1b72023-06-16 02:07:42 +0000213 /* A map from transaction(unique) id to client info */
214 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700215
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900216 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
217 @Nullable
218 private WifiManager.MulticastLock mHeldMulticastLock;
219 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
220 // (non-null), value is the requested Network (nullable)
221 @NonNull
222 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
223 @NonNull
224 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
225
Luke Huang05298582021-06-13 16:52:05 +0000226 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700227
Hugo Benichi32be63d2017-04-05 14:06:11 +0900228 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700229 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800230 // The count of the connected legacy clients.
231 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000232 // The number of client that ever connected.
233 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700234
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900235 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
236 new RemoteCallbackList<>();
237
238 private static class OffloadEngineInfo {
239 @NonNull final String mInterfaceName;
240 final long mOffloadCapabilities;
241 final long mOffloadType;
242 @NonNull final IOffloadEngine mOffloadEngine;
243
244 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
245 @NonNull String interfaceName, long capabilities, long offloadType) {
246 this.mOffloadEngine = offloadEngine;
247 this.mInterfaceName = interfaceName;
248 this.mOffloadCapabilities = capabilities;
249 this.mOffloadType = offloadType;
250 }
251 }
252
Paul Hu812e9212023-06-20 06:24:53 +0000253 @VisibleForTesting
254 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000255 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800256 protected final int mTransactionId;
257 @NonNull
258 protected final NsdServiceInfo mReqServiceInfo;
259 @NonNull
260 protected final String mListenedServiceType;
261
Paul Hud44e1b72023-06-16 02:07:42 +0000262 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800263 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000264 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800265 mTransactionId = transactionId;
266 mReqServiceInfo = reqServiceInfo;
267 mListenedServiceType = listenedServiceType;
268 }
269
270 @NonNull
271 public String getListenedServiceType() {
272 return mListenedServiceType;
273 }
274
275 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000276 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
277 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800278
279 @Override
280 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
281
282 @Override
283 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
284
285 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000286 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
287 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800288
289 @Override
290 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
291
292 @Override
293 public void onSearchStoppedWithError(int error) { }
294
295 @Override
296 public void onSearchFailedToStart() { }
297
298 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800299 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
300 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800301
302 @Override
303 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
304 }
305
306 private class DiscoveryListener extends MdnsListener {
307
Paul Hud44e1b72023-06-16 02:07:42 +0000308 DiscoveryListener(int clientRequestId, int transactionId,
309 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
310 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800311 }
312
313 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000314 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
315 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800316 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
317 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000318 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800319 }
320
321 @Override
322 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800323 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
324 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000325 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800326 }
Paul Hubad6fe92023-07-24 21:25:22 +0800327
328 @Override
329 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
330 int sentQueryTransactionId) {
331 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
332 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
333 }
Paul Hu23fa2022023-01-13 22:57:24 +0800334 }
335
Paul Hu75069ed2023-01-14 00:31:09 +0800336 private class ResolutionListener extends MdnsListener {
337
Paul Hud44e1b72023-06-16 02:07:42 +0000338 ResolutionListener(int clientRequestId, int transactionId,
339 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
340 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800341 }
342
343 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000344 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800345 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
346 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000347 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800348 }
Paul Hubad6fe92023-07-24 21:25:22 +0800349
350 @Override
351 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
352 int sentQueryTransactionId) {
353 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
354 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
355 }
Paul Hu75069ed2023-01-14 00:31:09 +0800356 }
357
Paul Hu30bd70d2023-02-07 13:20:56 +0000358 private class ServiceInfoListener extends MdnsListener {
359
Paul Hud44e1b72023-06-16 02:07:42 +0000360 ServiceInfoListener(int clientRequestId, int transactionId,
361 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
362 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000363 }
364
365 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000366 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
367 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000368 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
369 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000370 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000371 }
372
373 @Override
374 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
375 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
376 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000377 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000378 }
379
380 @Override
381 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
382 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
383 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000384 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000385 }
Paul Hubad6fe92023-07-24 21:25:22 +0800386
387 @Override
388 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
389 int sentQueryTransactionId) {
390 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
391 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
392 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000393 }
394
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900395 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
396 @Override
397 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
398 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
399 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
400 // filtering on such interfaces, so taking the multicast lock is not necessary to
401 // disable APF filtering of multicast.
402 if (socketNetwork == null
403 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
404 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
405 return;
406 }
407
408 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
409 updateMulticastLock();
410 }
411 }
412
413 @Override
414 public void onSocketDestroyed(@Nullable Network socketNetwork,
415 @NonNull MdnsInterfaceSocket socket) {
416 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
417 updateMulticastLock();
418 }
419 }
420 }
421
422 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
423 private final Handler mHandler;
424
425 private UidImportanceListener(Handler handler) {
426 mHandler = handler;
427 }
428
429 @Override
430 public void onUidImportance(int uid, int importance) {
431 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
432 }
433 }
434
435 private void handleUidImportanceChanged(int uid, int importance) {
436 // Lower importance values are more "important"
437 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
438 ? mRunningAppActiveUids.add(uid)
439 : mRunningAppActiveUids.remove(uid);
440 if (modified) {
441 updateMulticastLock();
442 }
443 }
444
445 /**
446 * Take or release the lock based on updated internal state.
447 *
448 * This determines whether the lock needs to be held based on
449 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
450 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
451 * updated.
452 */
453 private void updateMulticastLock() {
454 final int needsLockUid = getMulticastLockNeededUid();
455 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
456 final WifiManager wm = mContext.getSystemService(WifiManager.class);
457 if (wm == null) {
458 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
459 return;
460 }
461 mHeldMulticastLock = wm.createMulticastLock(TAG);
462 mHeldMulticastLock.acquire();
463 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
464 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
465 mHeldMulticastLock.release();
466 mHeldMulticastLock = null;
467 mServiceLogs.log("Released multicast lock");
468 }
469 }
470
471 /**
472 * @return The UID of an app requiring the multicast lock, or -1 if none.
473 */
474 private int getMulticastLockNeededUid() {
475 if (mWifiLockRequiredNetworks.size() == 0) {
476 // Return early if NSD is not active, or not on any relevant network
477 return -1;
478 }
Paul Hud44e1b72023-06-16 02:07:42 +0000479 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
480 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900481 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
482 // Ignore non-active UIDs
483 continue;
484 }
485
486 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
487 return clientInfo.mUid;
488 }
489 }
490 return -1;
491 }
492
Paul Hu019621e2023-01-13 23:26:49 +0800493 /**
494 * Data class of mdns service callback information.
495 */
496 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000497 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800498 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800499 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000500 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800501
Paul Hubad6fe92023-07-24 21:25:22 +0800502 MdnsEvent(int clientRequestId) {
503 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
504 }
505
506 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000507 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
508 }
509
Paul Hubad6fe92023-07-24 21:25:22 +0800510 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000511 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000512 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800513 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000514 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800515 }
516 }
517
Irfan Sheriff75006652012-04-17 23:15:29 -0700518 private class NsdStateMachine extends StateMachine {
519
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700520 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700521 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700522
523 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700524 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900525 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700526 }
527
Luke Huang92860f92021-06-23 06:29:30 +0000528 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800529 if (mIsDaemonStarted) {
530 if (DBG) Log.d(TAG, "Daemon is already started.");
531 return;
532 }
533 mMDnsManager.registerEventListener(mMDnsEventCallback);
534 mMDnsManager.startDaemon();
535 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000536 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000537 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000538 }
539
paulhu2b9ed952022-02-10 21:58:32 +0800540 private void maybeStopDaemon() {
541 if (!mIsDaemonStarted) {
542 if (DBG) Log.d(TAG, "Daemon has not been started.");
543 return;
544 }
545 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
546 mMDnsManager.stopDaemon();
547 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000548 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800549 }
550
Luke Huang92860f92021-06-23 06:29:30 +0000551 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000552 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000553 }
554
555 private void scheduleStop() {
556 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
557 }
558 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800559 // The native daemon should stay alive and can't be cleanup
560 // if any legacy client connected.
561 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000562 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000563 }
564 }
565
Luke Huang92860f92021-06-23 06:29:30 +0000566 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000567 this.removeMessages(NsdManager.DAEMON_CLEANUP);
568 }
569
Paul Hu23fa2022023-01-13 22:57:24 +0800570 private void maybeStartMonitoringSockets() {
571 if (mIsMonitoringSocketsStarted) {
572 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
573 return;
574 }
575
576 mMdnsSocketProvider.startMonitoringSockets();
577 mIsMonitoringSocketsStarted = true;
578 }
579
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900580 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
581 if (!mIsMonitoringSocketsStarted) return;
582 if (isAnyRequestActive()) return;
583
Paul Hu58f20602023-02-18 11:41:07 +0800584 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800585 mIsMonitoringSocketsStarted = false;
586 }
587
Hugo Benichi803a2f02017-04-24 11:35:06 +0900588 NsdStateMachine(String name, Handler handler) {
589 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700590 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700591 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800592 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900593 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700594 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700595 }
596
597 class DefaultState extends State {
598 @Override
599 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900600 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000601 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700602 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800604 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
605 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800607 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000608 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000609 final NetworkNsdReportedMetrics metrics =
610 mDeps.makeNetworkNsdReportedMetrics(
Paul Hu508a0122023-09-11 15:31:33 +0800611 (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900612 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000613 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800614 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900615 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000616 Log.w(TAG, "Client request id " + clientRequestId
617 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 }
619 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 case NsdManager.UNREGISTER_CLIENT:
621 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
622 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800623 if (cInfo != null) {
624 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900625 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800626 mLegacyClientCount -= 1;
627 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800628 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900629 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800630 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700631 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700632 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900633 cInfo = getClientInfoForReply(msg);
634 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800635 cInfo.onDiscoverServicesFailedImmediately(clientRequestId,
636 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900637 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700638 break;
639 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900640 cInfo = getClientInfoForReply(msg);
641 if (cInfo != null) {
642 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000643 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900644 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700645 break;
646 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 cInfo = getClientInfoForReply(msg);
648 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800649 cInfo.onRegisterServiceFailedImmediately(clientRequestId,
650 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900651 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700652 break;
653 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 cInfo = getClientInfoForReply(msg);
655 if (cInfo != null) {
656 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000657 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900658 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700659 break;
660 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900661 cInfo = getClientInfoForReply(msg);
662 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800663 cInfo.onResolveServiceFailedImmediately(clientRequestId,
664 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900665 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700666 break;
Paul Hub58deb72022-12-26 09:24:42 +0000667 case NsdManager.STOP_RESOLUTION:
668 cInfo = getClientInfoForReply(msg);
669 if (cInfo != null) {
670 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000671 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000672 }
673 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000674 case NsdManager.REGISTER_SERVICE_CALLBACK:
675 cInfo = getClientInfoForReply(msg);
676 if (cInfo != null) {
677 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000678 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000679 }
680 break;
Luke Huang05298582021-06-13 16:52:05 +0000681 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800682 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000683 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800684 // This event should be only sent by the legacy (target SDK < S) clients.
685 // Mark the sending client as legacy.
686 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900687 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800688 if (cInfo != null) {
689 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900690 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800691 mLegacyClientCount += 1;
692 maybeStartDaemon();
693 }
694 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700695 default:
paulhub2225702021-11-17 09:35:33 +0800696 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700697 return NOT_HANDLED;
698 }
699 return HANDLED;
700 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900701
702 private ClientInfo getClientInfoForReply(Message msg) {
703 final ListenerArgs args = (ListenerArgs) msg.obj;
704 return mClients.get(args.connector);
705 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700706 }
707
Irfan Sheriff75006652012-04-17 23:15:29 -0700708 class EnabledState extends State {
709 @Override
710 public void enter() {
711 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 }
713
714 @Override
715 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000716 // TODO: it is incorrect to stop the daemon without expunging all requests
717 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000718 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700719 }
720
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700721 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900722 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800723 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700724 return true;
725 }
726 return false;
727 }
728
Paul Hu508a0122023-09-11 15:31:33 +0800729 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000730 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800731 final LegacyClientRequest request =
732 new LegacyClientRequest(transactionId, what, startTimeMs);
733 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000734 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000735 // Remove the cleanup event because here comes a new request.
736 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800737 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700738 }
739
Paul Hud44e1b72023-06-16 02:07:42 +0000740 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900741 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000742 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000743 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000744 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900745 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800746 }
747
Paul Hud44e1b72023-06-16 02:07:42 +0000748 private void removeRequestMap(
749 int clientRequestId, int transactionId, ClientInfo clientInfo) {
750 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900751 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000752 clientInfo.mClientRequests.remove(clientRequestId);
753 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900754
755 if (existing instanceof LegacyClientRequest) {
756 maybeScheduleStop();
757 } else {
758 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900759 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900760 }
761 }
762
Paul Hu508a0122023-09-11 15:31:33 +0800763 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
764 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900765 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800766 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
767 listener, requestedNetwork, mClock.elapsedRealtime());
768 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000769 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900770 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800771 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800772 }
773
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900774 /**
775 * Truncate a service name to up to 63 UTF-8 bytes.
776 *
777 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
778 * names used in registerService follows historical behavior (see mdnsresponder
779 * handle_regservice_request).
780 */
781 @NonNull
782 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900783 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800784 }
785
Paul Hud44e1b72023-06-16 02:07:42 +0000786 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
787 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800788 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000789 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800790 }
791
Irfan Sheriff75006652012-04-17 23:15:29 -0700792 @Override
793 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900794 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000795 final int transactionId;
796 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900797 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900798 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700799 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800800 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800801 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900802 args = (ListenerArgs) msg.obj;
803 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000804 // If the binder death notification for a INsdManagerCallback was received
805 // before any calls are received by NsdService, the clientInfo would be
806 // cleared and cause NPE. Add a null check here to prevent this corner case.
807 if (clientInfo == null) {
808 Log.e(TAG, "Unknown connector in discovery");
809 break;
810 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700811
812 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800813 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
814 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700815 break;
816 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700817
Paul Hu23fa2022023-01-13 22:57:24 +0800818 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000819 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900820 final Pair<String, String> typeAndSubtype =
821 parseTypeAndSubtype(info.getServiceType());
822 final String serviceType = typeAndSubtype == null
823 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800824 if (clientInfo.mUseJavaBackend
825 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900826 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800827 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800828 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
829 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800830 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700831 }
Paul Hu23fa2022023-01-13 22:57:24 +0800832
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900833 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800834 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000835 final MdnsListener listener = new DiscoveryListener(clientRequestId,
836 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900837 final MdnsSearchOptions.Builder optionsBuilder =
838 MdnsSearchOptions.newBuilder()
839 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900840 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900841 .setIsPassiveMode(true);
842 if (typeAndSubtype.second != null) {
843 // The parsing ensures subtype starts with an underscore.
844 // MdnsSearchOptions expects the underscore to not be present.
845 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
846 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900847 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900848 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800849 final ClientRequest request = storeDiscoveryManagerRequestMap(
850 clientRequestId, transactionId, listener, clientInfo,
851 info.getNetwork());
852 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000853 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000854 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700855 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800856 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000857 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800858 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000859 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800860 + info.getServiceType());
861 }
Paul Hu508a0122023-09-11 15:31:33 +0800862 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
863 transactionId, clientInfo, msg.what,
864 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000865 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800866 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800867 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000868 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800869 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
870 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800871 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700872 }
873 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800874 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900875 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800876 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900877 args = (ListenerArgs) msg.obj;
878 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000879 // If the binder death notification for a INsdManagerCallback was received
880 // before any calls are received by NsdService, the clientInfo would be
881 // cleared and cause NPE. Add a null check here to prevent this corner case.
882 if (clientInfo == null) {
883 Log.e(TAG, "Unknown connector in stop discovery");
884 break;
885 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700886
Paul Hud44e1b72023-06-16 02:07:42 +0000887 final ClientRequest request =
888 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900889 if (request == null) {
890 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700891 break;
892 }
Paul Hud44e1b72023-06-16 02:07:42 +0000893 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900894 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
895 // point, so this needs to check the type of the original request to
896 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900897 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000898 stopDiscoveryManagerRequest(
899 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000900 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000901 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700902 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000903 removeRequestMap(clientRequestId, transactionId, clientInfo);
904 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000905 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800906 } else {
907 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000908 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800909 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700910 }
911 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900912 }
913 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800914 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900915 args = (ListenerArgs) msg.obj;
916 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000917 // If the binder death notification for a INsdManagerCallback was received
918 // before any calls are received by NsdService, the clientInfo would be
919 // cleared and cause NPE. Add a null check here to prevent this corner case.
920 if (clientInfo == null) {
921 Log.e(TAG, "Unknown connector in registration");
922 break;
923 }
924
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700925 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800926 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
927 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700928 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700929 }
930
Paul Hud44e1b72023-06-16 02:07:42 +0000931 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900932 final NsdServiceInfo serviceInfo = args.serviceInfo;
933 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900934 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
935 final String registerServiceType = typeSubtype == null
936 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800937 if (clientInfo.mUseJavaBackend
938 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900939 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900940 if (registerServiceType == null) {
941 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800942 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
943 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900944 break;
945 }
946 serviceInfo.setServiceType(registerServiceType);
947 serviceInfo.setServiceName(truncateServiceName(
948 serviceInfo.getServiceName()));
949
950 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900951 // TODO: pass in the subtype as well. Including the subtype in the
952 // service type would generate service instance names like
953 // Name._subtype._sub._type._tcp, which is incorrect
954 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000955 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
956 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900957 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700958 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900959 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000960 if (registerService(transactionId, serviceInfo)) {
961 if (DBG) {
962 Log.d(TAG, "Register " + clientRequestId
963 + " " + transactionId);
964 }
Paul Hua6bc4632023-06-26 01:18:29 +0000965 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
966 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900967 // Return success after mDns reports success
968 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000969 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800970 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
971 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900972 }
973
Irfan Sheriff75006652012-04-17 23:15:29 -0700974 }
975 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900976 }
977 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800978 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900979 args = (ListenerArgs) msg.obj;
980 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000981 // If the binder death notification for a INsdManagerCallback was received
982 // before any calls are received by NsdService, the clientInfo would be
983 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900984 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800985 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700986 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700987 }
Paul Hud44e1b72023-06-16 02:07:42 +0000988 final ClientRequest request =
989 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900990 if (request == null) {
991 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
992 break;
993 }
Paul Hud44e1b72023-06-16 02:07:42 +0000994 transactionId = request.mTransactionId;
995 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900996
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900997 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
998 // so this needs to check the type of the original request to unregister
999 // instead of looking at the flag value.
1000 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001001 final AdvertiserMetrics metrics =
1002 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001003 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001004 clientInfo.onUnregisterServiceSucceeded(
1005 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001006 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001007 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001008 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001009 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1010 NO_PACKET /* sentPacketCount */,
1011 0 /* conflictDuringProbingCount */,
1012 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001013 } else {
1014 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001015 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001016 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001017 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001018 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001019 }
Paul Hu75069ed2023-01-14 00:31:09 +08001020 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001021 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001022 args = (ListenerArgs) msg.obj;
1023 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001024 // If the binder death notification for a INsdManagerCallback was received
1025 // before any calls are received by NsdService, the clientInfo would be
1026 // cleared and cause NPE. Add a null check here to prevent this corner case.
1027 if (clientInfo == null) {
1028 Log.e(TAG, "Unknown connector in resolution");
1029 break;
1030 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001031
Paul Hu75069ed2023-01-14 00:31:09 +08001032 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001033 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001034 final Pair<String, String> typeSubtype =
1035 parseTypeAndSubtype(info.getServiceType());
1036 final String serviceType = typeSubtype == null
1037 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001038 if (clientInfo.mUseJavaBackend
1039 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001040 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001041 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001042 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1043 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001044 break;
1045 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001046 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001047
1048 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001049 final MdnsListener listener = new ResolutionListener(clientRequestId,
1050 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001051 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1052 .setNetwork(info.getNetwork())
1053 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001054 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001055 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001056 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001057 mMdnsDiscoveryManager.registerListener(
1058 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001059 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1060 listener, clientInfo, info.getNetwork());
1061 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001062 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001063 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001064 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001065 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1066 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001067 break;
1068 }
1069
1070 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001071 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001072 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001073 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1074 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001075 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001076 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1077 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001078 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001079 }
1080 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001081 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001082 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001083 if (DBG) Log.d(TAG, "Stop service resolution");
1084 args = (ListenerArgs) msg.obj;
1085 clientInfo = mClients.get(args.connector);
1086 // If the binder death notification for a INsdManagerCallback was received
1087 // before any calls are received by NsdService, the clientInfo would be
1088 // cleared and cause NPE. Add a null check here to prevent this corner case.
1089 if (clientInfo == null) {
1090 Log.e(TAG, "Unknown connector in stop resolution");
1091 break;
1092 }
1093
Paul Hud44e1b72023-06-16 02:07:42 +00001094 final ClientRequest request =
1095 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001096 if (request == null) {
1097 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1098 break;
1099 }
Paul Hud44e1b72023-06-16 02:07:42 +00001100 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001101 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1102 // point, so this needs to check the type of the original request to
1103 // unregister instead of looking at the flag value.
1104 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001105 stopDiscoveryManagerRequest(
1106 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001107 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001108 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001109 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001110 removeRequestMap(clientRequestId, transactionId, clientInfo);
1111 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001112 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001113 } else {
1114 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001115 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001116 }
1117 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001118 }
Paul Hub58deb72022-12-26 09:24:42 +00001119 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001120 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001121 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001122 if (DBG) Log.d(TAG, "Register a service callback");
1123 args = (ListenerArgs) msg.obj;
1124 clientInfo = mClients.get(args.connector);
1125 // If the binder death notification for a INsdManagerCallback was received
1126 // before any calls are received by NsdService, the clientInfo would be
1127 // cleared and cause NPE. Add a null check here to prevent this corner case.
1128 if (clientInfo == null) {
1129 Log.e(TAG, "Unknown connector in callback registration");
1130 break;
1131 }
1132
Paul Hu30bd70d2023-02-07 13:20:56 +00001133 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001134 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001135 final Pair<String, String> typeAndSubtype =
1136 parseTypeAndSubtype(info.getServiceType());
1137 final String serviceType = typeAndSubtype == null
1138 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001139 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001140 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001141 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001142 break;
1143 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001145
Paul Hu30bd70d2023-02-07 13:20:56 +00001146 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001147 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1148 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001149 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1150 .setNetwork(info.getNetwork())
1151 .setIsPassiveMode(true)
1152 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001153 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001154 .build();
1155 mMdnsDiscoveryManager.registerListener(
1156 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001157 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1158 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001159 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001160 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001161 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001162 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001163 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001164 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001165 if (DBG) Log.d(TAG, "Unregister a service callback");
1166 args = (ListenerArgs) msg.obj;
1167 clientInfo = mClients.get(args.connector);
1168 // If the binder death notification for a INsdManagerCallback was received
1169 // before any calls are received by NsdService, the clientInfo would be
1170 // cleared and cause NPE. Add a null check here to prevent this corner case.
1171 if (clientInfo == null) {
1172 Log.e(TAG, "Unknown connector in callback unregistration");
1173 break;
1174 }
1175
Paul Hud44e1b72023-06-16 02:07:42 +00001176 final ClientRequest request =
1177 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001178 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001179 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001180 break;
1181 }
Paul Hud44e1b72023-06-16 02:07:42 +00001182 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001183 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001184 stopDiscoveryManagerRequest(
1185 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001186 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001187 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001188 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001189 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001190 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001191 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001192 }
paulhu2b9ed952022-02-10 21:58:32 +08001193 case MDNS_SERVICE_EVENT:
1194 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001195 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001196 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001197 break;
Paul Hu019621e2023-01-13 23:26:49 +08001198 case MDNS_DISCOVERY_MANAGER_EVENT:
1199 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1200 return NOT_HANDLED;
1201 }
1202 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001203 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1204 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1205 // TODO: Limits the number of registrations created by a given class.
1206 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1207 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001208 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001209 break;
1210 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1211 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1212 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001213 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001214 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001215 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001216 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001217 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001218
Paul Hud44e1b72023-06-16 02:07:42 +00001219 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001220 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001221 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001222 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001223 Log.e(TAG, String.format(
1224 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001225 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001226 }
1227
1228 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001229 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1230 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001231 // This can happen because of race conditions. For example,
1232 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1233 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001234 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1235 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001236 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001237 }
Paul Hu812e9212023-06-20 06:24:53 +00001238 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1239 if (request == null) {
1240 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1241 return false;
1242 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001243 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001244 Log.d(TAG, String.format(
1245 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001246 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001247 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001248 case IMDnsEventListener.SERVICE_FOUND: {
1249 final DiscoveryInfo info = (DiscoveryInfo) obj;
1250 final String name = info.serviceName;
1251 final String type = info.registrationType;
1252 servInfo = new NsdServiceInfo(name, type);
1253 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001254 if (foundNetId == 0L) {
1255 // Ignore services that do not have a Network: they are not usable
1256 // by apps, as they would need privileged permissions to use
1257 // interfaces that do not have an associated Network.
1258 break;
1259 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001260 if (foundNetId == INetd.DUMMY_NET_ID) {
1261 // Ignore services on the dummy0 interface: they are only seen when
1262 // discovering locally advertised services, and are not reachable
1263 // through that interface.
1264 break;
1265 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001266 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001267
1268 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001269 break;
paulhu2b9ed952022-02-10 21:58:32 +08001270 }
1271 case IMDnsEventListener.SERVICE_LOST: {
1272 final DiscoveryInfo info = (DiscoveryInfo) obj;
1273 final String name = info.serviceName;
1274 final String type = info.registrationType;
1275 final int lostNetId = info.netId;
1276 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001277 // The network could be set to null (netId 0) if it was torn down when the
1278 // service is lost
1279 // TODO: avoid returning null in that case, possibly by remembering
1280 // found services on the same interface index and their network at the time
1281 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001282 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001283 break;
paulhu2b9ed952022-02-10 21:58:32 +08001284 }
1285 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001286 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001287 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1288 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001289 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001290 break;
paulhu2b9ed952022-02-10 21:58:32 +08001291 case IMDnsEventListener.SERVICE_REGISTERED: {
1292 final RegistrationInfo info = (RegistrationInfo) obj;
1293 final String name = info.serviceName;
1294 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001295 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001296 break;
paulhu2b9ed952022-02-10 21:58:32 +08001297 }
1298 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001299 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001300 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1301 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001302 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001303 break;
paulhu2b9ed952022-02-10 21:58:32 +08001304 case IMDnsEventListener.SERVICE_RESOLVED: {
1305 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001306 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001307 final String fullName = info.serviceFullName;
1308 while (index < fullName.length() && fullName.charAt(index) != '.') {
1309 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001310 ++index;
1311 }
1312 ++index;
1313 }
paulhu2b9ed952022-02-10 21:58:32 +08001314 if (index >= fullName.length()) {
1315 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001316 break;
1317 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001318
paulhube186602022-04-12 07:18:23 +00001319 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001320 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321 String type = rest.replace(".local.", "");
1322
Paul Hu30bd70d2023-02-07 13:20:56 +00001323 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001324 serviceInfo.setServiceName(name);
1325 serviceInfo.setServiceType(type);
1326 serviceInfo.setPort(info.port);
1327 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001328 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001329
Paul Hud44e1b72023-06-16 02:07:42 +00001330 stopResolveService(transactionId);
1331 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001332
Paul Hud44e1b72023-06-16 02:07:42 +00001333 final int transactionId2 = getUniqueId();
1334 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1335 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001336 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001337 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001338 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001339 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1340 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001341 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001342 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 }
1344 break;
paulhu2b9ed952022-02-10 21:58:32 +08001345 }
1346 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001348 stopResolveService(transactionId);
1349 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001350 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001351 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1352 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001353 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001354 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001355 break;
paulhu2b9ed952022-02-10 21:58:32 +08001356 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001357 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001358 stopGetAddrInfo(transactionId);
1359 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001360 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001361 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1362 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001363 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001364 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001365 break;
paulhu2b9ed952022-02-10 21:58:32 +08001366 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001367 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001368 final GetAddressInfo info = (GetAddressInfo) obj;
1369 final String address = info.address;
1370 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001371 InetAddress serviceHost = null;
1372 try {
paulhu2b9ed952022-02-10 21:58:32 +08001373 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001374 } catch (UnknownHostException e) {
1375 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1376 }
1377
1378 // If the resolved service is on an interface without a network, consider it
1379 // as a failure: it would not be usable by apps as they would need
1380 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001381 if (netId != NETID_UNSET && serviceHost != null) {
1382 clientInfo.mResolvedService.setHost(serviceHost);
1383 setServiceNetworkForCallback(clientInfo.mResolvedService,
1384 netId, info.interfaceIdx);
1385 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001386 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001387 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001388 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001389 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1390 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001391 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001392 }
Paul Hud44e1b72023-06-16 02:07:42 +00001393 stopGetAddrInfo(transactionId);
1394 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001395 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001396 break;
paulhu2b9ed952022-02-10 21:58:32 +08001397 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001398 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001399 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001400 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001401 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001402 }
Paul Hu019621e2023-01-13 23:26:49 +08001403
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001404 @Nullable
1405 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1406 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001407 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001408 final String[] typeArray = serviceInfo.getServiceType();
1409 final String joinedType;
1410 if (typeArray.length == 0
1411 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1412 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1413 + Arrays.toString(typeArray));
1414 return null;
1415 } else {
1416 joinedType = TextUtils.join(".",
1417 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1418 }
1419 final String serviceType;
1420 switch (code) {
1421 case NsdManager.SERVICE_FOUND:
1422 case NsdManager.SERVICE_LOST:
1423 // For consistency with historical behavior, discovered service types have
1424 // a dot at the end.
1425 serviceType = joinedType + ".";
1426 break;
1427 case RESOLVE_SERVICE_SUCCEEDED:
1428 // For consistency with historical behavior, resolved service types have
1429 // a dot at the beginning.
1430 serviceType = "." + joinedType;
1431 break;
1432 default:
1433 serviceType = joinedType;
1434 break;
1435 }
Paul Hu019621e2023-01-13 23:26:49 +08001436 final String serviceName = serviceInfo.getServiceInstanceName();
1437 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1438 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001439 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1440 // network for Tethering interface. In other words, the network == null means the
1441 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001442 setServiceNetworkForCallback(
1443 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001444 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001445 serviceInfo.getInterfaceIndex());
1446 return servInfo;
1447 }
1448
1449 private boolean handleMdnsDiscoveryManagerEvent(
1450 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001451 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001452 if (clientInfo == null) {
1453 Log.e(TAG, String.format(
1454 "id %d for %d has no client mapping", transactionId, code));
1455 return false;
1456 }
1457
1458 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001459 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001460 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1461 if (request == null) {
1462 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1463 return false;
1464 }
1465
1466 // Deal with the discovery sent callback
1467 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1468 request.onQuerySent();
1469 return true;
1470 }
1471
1472 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001473 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1474 // Errors are already logged if null
1475 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001476 mServiceLogs.log(String.format(
1477 "MdnsDiscoveryManager event code=%s transactionId=%d",
1478 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001479 switch (code) {
1480 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001481 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001482 break;
1483 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001484 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001485 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001486 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1487 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001488 info.setPort(serviceInfo.getPort());
1489
1490 Map<String, String> attrs = serviceInfo.getAttributes();
1491 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1492 final String key = kv.getKey();
1493 try {
1494 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1495 } catch (IllegalArgumentException e) {
1496 Log.e(TAG, "Invalid attribute", e);
1497 }
1498 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001499 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001500 if (addresses.size() != 0) {
1501 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001502 request.setServiceFromCache(event.mIsServiceFromCache);
1503 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001504 } else {
1505 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001506 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001507 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1508 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001509 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001510 }
1511
1512 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001513 if (!(request instanceof DiscoveryManagerRequest)) {
1514 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1515 break;
1516 }
Paul Hud44e1b72023-06-16 02:07:42 +00001517 stopDiscoveryManagerRequest(
1518 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001519 break;
1520 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001521 case NsdManager.SERVICE_UPDATED: {
1522 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1523 info.setPort(serviceInfo.getPort());
1524
1525 Map<String, String> attrs = serviceInfo.getAttributes();
1526 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1527 final String key = kv.getKey();
1528 try {
1529 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1530 } catch (IllegalArgumentException e) {
1531 Log.e(TAG, "Invalid attribute", e);
1532 }
1533 }
1534
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001535 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001536 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001537 clientInfo.onServiceUpdated(clientRequestId, info, request);
1538 // Set the ServiceFromCache flag only if the service is actually being
1539 // retrieved from the cache. This flag should not be overridden by later
1540 // service updates, which may not be cached.
1541 if (event.mIsServiceFromCache) {
1542 request.setServiceFromCache(true);
1543 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001544 break;
1545 }
1546 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001547 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001548 break;
Paul Hu019621e2023-01-13 23:26:49 +08001549 default:
1550 return false;
1551 }
1552 return true;
1553 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001554 }
1555 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001556
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001557 @NonNull
1558 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1559 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1560 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1561 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1562 for (String ipv4Address : v4Addrs) {
1563 try {
1564 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1565 } catch (IllegalArgumentException e) {
1566 Log.wtf(TAG, "Invalid ipv4 address", e);
1567 }
1568 }
1569 for (String ipv6Address : v6Addrs) {
1570 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001571 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1572 ipv6Address);
1573 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1574 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001575 Log.wtf(TAG, "Invalid ipv6 address", e);
1576 }
1577 }
1578 return addresses;
1579 }
1580
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001581 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1582 switch (netId) {
1583 case NETID_UNSET:
1584 info.setNetwork(null);
1585 break;
1586 case INetd.LOCAL_NET_ID:
1587 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1588 // visible / usable for apps, so do not return it. Store the interface
1589 // index instead, so at least if the client tries to resolve the service
1590 // with that NsdServiceInfo, it will be done on the same interface.
1591 // If they recreate the NsdServiceInfo themselves, resolution would be
1592 // done on all interfaces as before T, which should also work.
1593 info.setNetwork(null);
1594 info.setInterfaceIndex(ifaceIdx);
1595 break;
1596 default:
1597 info.setNetwork(new Network(netId));
1598 }
1599 }
1600
paulhube186602022-04-12 07:18:23 +00001601 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1602 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1603 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1604 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1605 private String unescape(String s) {
1606 StringBuilder sb = new StringBuilder(s.length());
1607 for (int i = 0; i < s.length(); ++i) {
1608 char c = s.charAt(i);
1609 if (c == '\\') {
1610 if (++i >= s.length()) {
1611 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1612 break;
1613 }
1614 c = s.charAt(i);
1615 if (c != '.' && c != '\\') {
1616 if (i + 2 >= s.length()) {
1617 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1618 break;
1619 }
1620 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1621 + (s.charAt(i + 2) - '0'));
1622 i += 2;
1623 }
1624 }
1625 sb.append(c);
1626 }
1627 return sb.toString();
1628 }
1629
Paul Hu7445e3d2023-03-03 15:14:00 +08001630 /**
1631 * Check the given service type is valid and construct it to a service type
1632 * which can use for discovery / resolution service.
1633 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001634 * <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 +08001635 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1636 * underscore; they are alphanumerical characters or dashes or underscore, except the
1637 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1638 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001639 * <p>The subtype may also be specified with a comma after the service type, for example
1640 * _type._tcp,_subtype.
1641 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001642 * @param serviceType the request service type for discovery / resolution service
1643 * @return constructed service type or null if the given service type is invalid.
1644 */
1645 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001646 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001647 if (TextUtils.isEmpty(serviceType)) return null;
1648
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001649 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001650 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001651 // Optional leading subtype (_subtype._type._tcp)
1652 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1653 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1654 // Actual type (_type._tcp.local)
1655 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001656 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001657 // e.g. allow "_type._tcp.local."
1658 + "\\.?"
1659 // Optional subtype after comma, for "_type._tcp,_subtype" format
1660 + "(?:,(" + typeOrSubtypePattern + "))?"
1661 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001662 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1663 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001664 // Use the subtype either at the beginning or after the comma
1665 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1666 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001667 }
1668
Hugo Benichi803a2f02017-04-24 11:35:06 +09001669 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001670 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001671 this(ctx, handler, cleanupDelayMs, new Dependencies());
1672 }
1673
1674 @VisibleForTesting
1675 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001676 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001677 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001678 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001679 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001680 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1681 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001682 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001683
Paul Hu14667de2023-04-17 22:42:47 +08001684 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001685 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001686 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1687 // address events are received.
1688 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001689
1690 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1691 // startBootstrapServices).
1692 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1693 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1694 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1695 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1696 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1697 mRunningAppActiveImportanceCutoff);
1698
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001699 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001700 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1701 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001702 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001703 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001704 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
Yuyang Huangb96a0712023-09-07 15:13:15 +09001705 MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder().setIsMdnsOffloadFeatureEnabled(
1706 mDeps.isTetheringFeatureNotChickenedOut(
1707 MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD)).build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001708 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001709 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001710 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001711 }
1712
1713 /**
1714 * Dependencies of NsdService, for injection in tests.
1715 */
1716 @VisibleForTesting
1717 public static class Dependencies {
1718 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001719 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001720 *
1721 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001722 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001723 */
1724 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001725 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001726 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001727 }
1728
1729 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001730 * Check whether the MdnsAdvertiser feature is enabled.
1731 *
1732 * @param context The global context information about an app environment.
1733 * @return true if the MdnsAdvertiser feature is enabled.
1734 */
1735 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001736 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001737 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001738 }
1739
1740 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001741 * Get the type allowlist flag value.
1742 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1743 */
1744 @Nullable
1745 public String getTypeAllowlistFlags() {
1746 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1747 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1748 }
1749
1750 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001751 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001752 */
1753 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001754 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001755 }
1756
1757 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001758 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1759 */
1760 public boolean isTetheringFeatureNotChickenedOut(String feature) {
1761 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(feature);
1762 }
1763
1764 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001765 * @see MdnsDiscoveryManager
1766 */
1767 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001768 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001769 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1770 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001771 }
1772
1773 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001774 * @see MdnsAdvertiser
1775 */
1776 public MdnsAdvertiser makeMdnsAdvertiser(
1777 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001778 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1779 MdnsFeatureFlags featureFlags) {
1780 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001781 }
1782
1783 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001784 * @see MdnsSocketProvider
1785 */
Paul Hu14667de2023-04-17 22:42:47 +08001786 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001787 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1788 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1789 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1790 }
1791
1792 /**
1793 * @see DeviceConfig#getInt(String, String, int)
1794 */
1795 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1796 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1797 }
1798
1799 /**
1800 * @see Binder#getCallingUid()
1801 */
1802 public int getCallingUid() {
1803 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001804 }
Paul Hu777ed052023-06-19 13:35:15 +00001805
1806 /**
1807 * @see NetworkNsdReportedMetrics
1808 */
Paul Hu508a0122023-09-11 15:31:33 +08001809 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1810 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001811 }
1812
1813 /**
1814 * @see MdnsUtils.Clock
1815 */
1816 public Clock makeClock() {
1817 return new Clock();
1818 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001819 }
1820
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001821 /**
1822 * Return whether a type is allowlisted to use the Java backend.
1823 * @param type The service type
1824 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1825 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1826 */
1827 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1828 @NonNull String flagPrefix) {
1829 if (type == null) return false;
1830 final String typesConfig = mDeps.getTypeAllowlistFlags();
1831 if (TextUtils.isEmpty(typesConfig)) return false;
1832
1833 final String mappingPrefix = type + ":";
1834 String mappedFlag = null;
1835 for (String mapping : TextUtils.split(typesConfig, ",")) {
1836 if (mapping.startsWith(mappingPrefix)) {
1837 mappedFlag = mapping.substring(mappingPrefix.length());
1838 break;
1839 }
1840 }
1841
1842 if (mappedFlag == null) return false;
1843
1844 return mDeps.isFeatureEnabled(mContext,
1845 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1846 }
1847
1848 private boolean useDiscoveryManagerForType(@Nullable String type) {
1849 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1850 }
1851
1852 private boolean useAdvertiserForType(@Nullable String type) {
1853 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1854 }
1855
paulhu1b35e822022-04-08 14:48:41 +08001856 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001857 HandlerThread thread = new HandlerThread(TAG);
1858 thread.start();
1859 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001860 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001861 return service;
1862 }
1863
paulhu2b9ed952022-02-10 21:58:32 +08001864 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1865 private final StateMachine mStateMachine;
1866
1867 MDnsEventCallback(StateMachine sm) {
1868 mStateMachine = sm;
1869 }
1870
1871 @Override
1872 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1873 mStateMachine.sendMessage(
1874 MDNS_SERVICE_EVENT, status.result, status.id, status);
1875 }
1876
1877 @Override
1878 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1879 mStateMachine.sendMessage(
1880 MDNS_SERVICE_EVENT, status.result, status.id, status);
1881 }
1882
1883 @Override
1884 public void onServiceResolutionStatus(final ResolutionInfo status) {
1885 mStateMachine.sendMessage(
1886 MDNS_SERVICE_EVENT, status.result, status.id, status);
1887 }
1888
1889 @Override
1890 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1891 mStateMachine.sendMessage(
1892 MDNS_SERVICE_EVENT, status.result, status.id, status);
1893 }
1894
1895 @Override
1896 public int getInterfaceVersion() throws RemoteException {
1897 return this.VERSION;
1898 }
1899
1900 @Override
1901 public String getInterfaceHash() throws RemoteException {
1902 return this.HASH;
1903 }
1904 }
1905
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001906 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1907 final String targetInterface = offloadEngineInfo.mInterfaceName;
1908 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1909 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1910 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1911 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1912 try {
1913 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1914 } catch (RemoteException e) {
1915 // Can happen in regular cases, do not log a stacktrace
1916 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1917 }
1918 }
1919 }
1920
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001921 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1922 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1923 final int count = mOffloadEngines.beginBroadcast();
1924 try {
1925 for (int i = 0; i < count; i++) {
1926 final OffloadEngineInfo offloadEngineInfo =
1927 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1928 final String interfaceName = offloadEngineInfo.mInterfaceName;
1929 if (!targetInterfaceName.equals(interfaceName)
1930 || ((offloadEngineInfo.mOffloadType
1931 & offloadServiceInfo.getOffloadType()) == 0)) {
1932 continue;
1933 }
1934 try {
1935 if (isRemove) {
1936 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1937 offloadServiceInfo);
1938 } else {
1939 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1940 offloadServiceInfo);
1941 }
1942 } catch (RemoteException e) {
1943 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001944 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001945 }
1946 }
1947 } finally {
1948 mOffloadEngines.finishBroadcast();
1949 }
1950 }
1951
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001952 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001953 // TODO: add a callback to notify when a service is being added on each interface (as soon
1954 // as probing starts), and call mOffloadCallbacks. This callback is for
1955 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1956
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001957 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001958 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1959 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1960 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001961 if (clientInfo == null) return;
1962
Paul Hud44e1b72023-06-16 02:07:42 +00001963 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1964 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001965
1966 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1967 // historical behavior.
1968 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001969 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001970 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001971 }
1972
1973 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001974 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1975 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001976 if (clientInfo == null) return;
1977
Paul Hud44e1b72023-06-16 02:07:42 +00001978 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1979 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001980 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001981 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1982 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001983 }
1984
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001985 @Override
1986 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1987 @NonNull OffloadServiceInfo offloadServiceInfo) {
1988 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1989 }
1990
1991 @Override
1992 public void onOffloadStop(@NonNull String interfaceName,
1993 @NonNull OffloadServiceInfo offloadServiceInfo) {
1994 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1995 }
1996
Paul Hud44e1b72023-06-16 02:07:42 +00001997 private ClientInfo getClientInfoOrLog(int transactionId) {
1998 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001999 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002000 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002001 }
2002 return clientInfo;
2003 }
2004
Paul Hud44e1b72023-06-16 02:07:42 +00002005 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2006 final int clientRequestId = info.getClientRequestId(transactionId);
2007 if (clientRequestId < 0) {
2008 Log.e(TAG, String.format(
2009 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002010 }
Paul Hud44e1b72023-06-16 02:07:42 +00002011 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002012 }
2013 }
2014
Paul Hu2e0a88c2023-03-09 16:05:01 +08002015 private static class ConnectorArgs {
2016 @NonNull public final NsdServiceConnector connector;
2017 @NonNull public final INsdManagerCallback callback;
2018 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002019 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002020
2021 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002022 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002023 this.connector = connector;
2024 this.callback = callback;
2025 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002026 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002027 }
2028 }
2029
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002030 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002031 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002033 final int uid = mDeps.getCallingUid();
2034 if (cb == null) {
2035 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2036 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002037 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002038 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002039 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002040 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002041 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002042 }
2043
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002044 private static class ListenerArgs {
2045 public final NsdServiceConnector connector;
2046 public final NsdServiceInfo serviceInfo;
2047 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2048 this.connector = connector;
2049 this.serviceInfo = serviceInfo;
2050 }
2051 }
2052
2053 private class NsdServiceConnector extends INsdServiceConnector.Stub
2054 implements IBinder.DeathRecipient {
2055 @Override
2056 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2057 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2058 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2059 new ListenerArgs(this, serviceInfo)));
2060 }
2061
2062 @Override
2063 public void unregisterService(int listenerKey) {
2064 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2065 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2066 new ListenerArgs(this, null)));
2067 }
2068
2069 @Override
2070 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2071 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2072 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2073 new ListenerArgs(this, serviceInfo)));
2074 }
2075
2076 @Override
2077 public void stopDiscovery(int listenerKey) {
2078 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2079 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2080 }
2081
2082 @Override
2083 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2084 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2085 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2086 new ListenerArgs(this, serviceInfo)));
2087 }
2088
2089 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002090 public void stopResolution(int listenerKey) {
2091 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2092 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2093 }
2094
2095 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002096 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2097 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2098 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2099 new ListenerArgs(this, serviceInfo)));
2100 }
2101
2102 @Override
2103 public void unregisterServiceInfoCallback(int listenerKey) {
2104 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2105 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2106 new ListenerArgs(this, null)));
2107 }
2108
2109 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002110 public void startDaemon() {
2111 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2112 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2113 }
2114
2115 @Override
2116 public void binderDied() {
2117 mNsdStateMachine.sendMessage(
2118 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002119
2120 }
2121
2122 @Override
2123 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2124 @OffloadEngine.OffloadCapability long offloadCapabilities,
2125 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002126 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002127 Objects.requireNonNull(ifaceName);
2128 Objects.requireNonNull(cb);
2129 mNsdStateMachine.sendMessage(
2130 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2131 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2132 offloadTypes)));
2133 }
2134
2135 @Override
2136 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002137 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002138 Objects.requireNonNull(cb);
2139 mNsdStateMachine.sendMessage(
2140 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002141 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002142
2143 private static void checkOffloadEnginePermission(Context context) {
2144 if (!SdkLevel.isAtLeastT()) {
2145 throw new SecurityException("API is not available in before API level 33");
2146 }
2147 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2148 // be back ported to older builds: accept it as long as it's signature-protected
2149 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2150 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2151 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2152 return;
2153 }
2154 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2155 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2156 return;
2157 }
2158 throw new SecurityException("Requires one of the following permissions: "
2159 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2160 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2161 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002162 }
2163
Hugo Benichi912db992017-04-24 16:41:03 +09002164 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002165 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002166 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002167 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2168 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002169 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002170 }
2171
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002172 private int getUniqueId() {
2173 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2174 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002175 }
2176
Paul Hud44e1b72023-06-16 02:07:42 +00002177 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002178 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002179 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002180 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002181 String name = service.getServiceName();
2182 String type = service.getServiceType();
2183 int port = service.getPort();
2184 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002185 final int registerInterface = getNetworkInterfaceIndex(service);
2186 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002187 Log.e(TAG, "Interface to register service on not found");
2188 return false;
2189 }
Paul Hud44e1b72023-06-16 02:07:42 +00002190 return mMDnsManager.registerService(
2191 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002192 }
2193
Paul Hud44e1b72023-06-16 02:07:42 +00002194 private boolean unregisterService(int transactionId) {
2195 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002196 }
2197
Paul Hud44e1b72023-06-16 02:07:42 +00002198 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002199 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002200 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2201 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002202 Log.e(TAG, "Interface to discover service on not found");
2203 return false;
2204 }
Paul Hud44e1b72023-06-16 02:07:42 +00002205 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002206 }
2207
Paul Hud44e1b72023-06-16 02:07:42 +00002208 private boolean stopServiceDiscovery(int transactionId) {
2209 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002210 }
2211
Paul Hud44e1b72023-06-16 02:07:42 +00002212 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002213 final String name = service.getServiceName();
2214 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002215 final int resolveInterface = getNetworkInterfaceIndex(service);
2216 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002217 Log.e(TAG, "Interface to resolve service on not found");
2218 return false;
2219 }
Paul Hud44e1b72023-06-16 02:07:42 +00002220 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002221 }
2222
2223 /**
2224 * Guess the interface to use to resolve or discover a service on a specific network.
2225 *
2226 * This is an imperfect guess, as for example the network may be gone or not yet fully
2227 * registered. This is fine as failing is correct if the network is gone, and a client
2228 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2229 * this is to support the legacy mdnsresponder implementation, which historically resolved
2230 * services on an unspecified network.
2231 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002232 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2233 final Network network = serviceInfo.getNetwork();
2234 if (network == null) {
2235 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2236 // provided by NsdService from discovery results, and the service was found on an
2237 // interface that has no app-usable Network).
2238 if (serviceInfo.getInterfaceIndex() != 0) {
2239 return serviceInfo.getInterfaceIndex();
2240 }
2241 return IFACE_IDX_ANY;
2242 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002243
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002244 String interfaceName = getNetworkInterfaceName(network);
2245 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002246 return IFACE_IDX_ANY;
2247 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002248 return getNetworkInterfaceIndexByName(interfaceName);
2249 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002250
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002251 private String getNetworkInterfaceName(@Nullable Network network) {
2252 if (network == null) {
2253 return null;
2254 }
2255 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2256 if (cm == null) {
2257 Log.wtf(TAG, "No ConnectivityManager");
2258 return null;
2259 }
2260 final LinkProperties lp = cm.getLinkProperties(network);
2261 if (lp == null) {
2262 return null;
2263 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002264 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002265 return lp.getInterfaceName();
2266 }
2267
2268 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002269 final NetworkInterface iface;
2270 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002271 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002272 } catch (SocketException e) {
2273 Log.e(TAG, "Error querying interface", e);
2274 return IFACE_IDX_ANY;
2275 }
2276
2277 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002278 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002279 return IFACE_IDX_ANY;
2280 }
2281
2282 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002283 }
2284
Paul Hud44e1b72023-06-16 02:07:42 +00002285 private boolean stopResolveService(int transactionId) {
2286 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002287 }
2288
Paul Hud44e1b72023-06-16 02:07:42 +00002289 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2290 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002291 }
2292
Paul Hud44e1b72023-06-16 02:07:42 +00002293 private boolean stopGetAddrInfo(int transactionId) {
2294 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002295 }
2296
2297 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002298 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2299 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002300
Paul Hub2e67d32023-04-18 05:50:14 +00002301 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2302 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002303 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002304
2305 // Dump service and clients logs
2306 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002307 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002308 pw.increaseIndent();
2309 mServiceLogs.reverseDump(pw);
2310 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002311 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002312
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002313 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002314 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002315 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002316 private int mFoundServiceCount = 0;
2317 private int mLostServiceCount = 0;
2318 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002319 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002320 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002321
Paul Hu812e9212023-06-20 06:24:53 +00002322 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002323 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002324 mStartTimeMs = startTimeMs;
2325 }
2326
Paul Hu812e9212023-06-20 06:24:53 +00002327 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002328 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002329 }
Paul Hu812e9212023-06-20 06:24:53 +00002330
2331 public void onServiceFound(String serviceName) {
2332 mFoundServiceCount++;
2333 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2334 mServices.add(serviceName);
2335 }
2336 }
2337
2338 public void onServiceLost() {
2339 mLostServiceCount++;
2340 }
2341
2342 public int getFoundServiceCount() {
2343 return mFoundServiceCount;
2344 }
2345
2346 public int getLostServiceCount() {
2347 return mLostServiceCount;
2348 }
2349
2350 public int getServicesCount() {
2351 return mServices.size();
2352 }
Paul Hua6bc4632023-06-26 01:18:29 +00002353
2354 public void setServiceFromCache(boolean isServiceFromCache) {
2355 mIsServiceFromCache = isServiceFromCache;
2356 }
2357
2358 public boolean isServiceFromCache() {
2359 return mIsServiceFromCache;
2360 }
Paul Hubad6fe92023-07-24 21:25:22 +08002361
2362 public void onQuerySent() {
2363 mSentQueryCount++;
2364 }
2365
2366 public int getSentQueryCount() {
2367 return mSentQueryCount;
2368 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002369 }
2370
2371 private static class LegacyClientRequest extends ClientRequest {
2372 private final int mRequestCode;
2373
Paul Hu812e9212023-06-20 06:24:53 +00002374 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2375 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002376 mRequestCode = requestCode;
2377 }
2378 }
2379
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002380 private abstract static class JavaBackendClientRequest extends ClientRequest {
2381 @Nullable
2382 private final Network mRequestedNetwork;
2383
Paul Hu777ed052023-06-19 13:35:15 +00002384 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002385 long startTimeMs) {
2386 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002387 mRequestedNetwork = requestedNetwork;
2388 }
2389
2390 @Nullable
2391 public Network getRequestedNetwork() {
2392 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002393 }
2394 }
2395
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002396 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002397 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002398 long startTimeMs) {
2399 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002400 }
2401 }
2402
2403 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002404 @NonNull
2405 private final MdnsListener mListener;
2406
Paul Hud44e1b72023-06-16 02:07:42 +00002407 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002408 @Nullable Network requestedNetwork, long startTimeMs) {
2409 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002410 mListener = listener;
2411 }
2412 }
2413
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002414 /* Information tracked per client */
2415 private class ClientInfo {
2416
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002417 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002418 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002419 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002420 private NsdServiceInfo mResolvedService;
2421
Paul Hud44e1b72023-06-16 02:07:42 +00002422 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002423 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002424
Luke Huangf7277ed2021-07-12 21:15:10 +08002425 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002426 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002427 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002428 // The flag of using java backend if the client's target SDK >= U
2429 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002430 // Store client logs
2431 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002432 // Report the nsd metrics data
2433 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002434
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002435 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002436 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002437 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002438 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002439 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002440 mClientLogs = sharedLog;
2441 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002442 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002443 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002444
2445 @Override
2446 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002447 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002448 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002449 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002450 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2451 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002452 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002453 int clientRequestId = mClientRequests.keyAt(i);
2454 sb.append("clientRequestId ")
2455 .append(clientRequestId)
2456 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002457 .append(" type ").append(
2458 mClientRequests.valueAt(i).getClass().getSimpleName())
2459 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002460 }
2461 return sb.toString();
2462 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002463
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002464 private boolean isPreSClient() {
2465 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002466 }
2467
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002468 private void setPreSClient() {
2469 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002470 }
2471
Paul Hu812e9212023-06-20 06:24:53 +00002472 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002473 final MdnsListener listener =
2474 ((DiscoveryManagerRequest) request).mListener;
2475 mMdnsDiscoveryManager.unregisterListener(
2476 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002477 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002478 }
2479
Dave Plattfeff2af2014-03-07 14:48:22 -08002480 // Remove any pending requests from the global map when we get rid of a client,
2481 // and send cancellations to the daemon.
2482 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002483 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002484 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002485 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002486 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002487 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002488 final int transactionId = request.mTransactionId;
2489 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002490 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002491 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2492 + " transactionId " + transactionId
2493 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002494 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002495
2496 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002497 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2498 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002499 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002500 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2501 request.getFoundServiceCount(),
2502 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002503 request.getServicesCount(),
2504 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002505 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002506 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002507 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002508 } else if (listener instanceof ServiceInfoListener) {
2509 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2510 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2511 request.getFoundServiceCount(),
2512 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002513 request.isServiceFromCache(),
2514 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002515 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002516 continue;
2517 }
2518
2519 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002520 final AdvertiserMetrics metrics =
2521 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002522 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002523 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002524 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2525 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2526 metrics.mConflictDuringProbingCount,
2527 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002528 continue;
2529 }
2530
2531 if (!(request instanceof LegacyClientRequest)) {
2532 throw new IllegalStateException("Unknown request type: " + request.getClass());
2533 }
2534
2535 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002536 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002537 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002538 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002539 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2540 request.getFoundServiceCount(),
2541 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002542 request.getServicesCount(),
2543 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002544 break;
2545 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002546 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002547 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002548 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002549 break;
2550 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002551 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002552 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002553 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2554 NO_PACKET /* repliedRequestsCount */,
2555 NO_PACKET /* sentPacketCount */,
2556 0 /* conflictDuringProbingCount */,
2557 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002558 break;
2559 default:
2560 break;
2561 }
2562 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002563 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002564 updateMulticastLock();
2565 }
2566
2567 /**
2568 * Returns true if this client has any Java backend request that requests one of the given
2569 * networks.
2570 */
2571 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2572 for (int i = 0; i < mClientRequests.size(); i++) {
2573 final ClientRequest req = mClientRequests.valueAt(i);
2574 if (!(req instanceof JavaBackendClientRequest)) {
2575 continue;
2576 }
2577 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2578 .getRequestedNetwork();
2579 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2580 return true;
2581 }
2582 }
2583 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002584 }
2585
Paul Hud44e1b72023-06-16 02:07:42 +00002586 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2587 // transaction id, return the corresponding client request id.
2588 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002589 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002590 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002591 return mClientRequests.keyAt(i);
2592 }
Christopher Lane74411222014-04-25 18:39:07 -07002593 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002594 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002595 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002596
Paul Hub2e67d32023-04-18 05:50:14 +00002597 private void log(String message) {
2598 mClientLogs.log(message);
2599 }
2600
Paul Hu508a0122023-09-11 15:31:33 +08002601 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2602 return !(request instanceof DiscoveryManagerRequest)
2603 && !(request instanceof AdvertiserClientRequest);
2604 }
2605
2606 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2607 ClientRequest request) {
2608 mMetrics.reportServiceDiscoveryStarted(
2609 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002610 try {
2611 mCb.onDiscoverServicesStarted(listenerKey, info);
2612 } catch (RemoteException e) {
2613 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2614 }
2615 }
Paul Hu508a0122023-09-11 15:31:33 +08002616 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2617 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2618 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002619 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002620
Paul Hu508a0122023-09-11 15:31:33 +08002621 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2622 int transactionId, long durationMs) {
2623 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002624 try {
2625 mCb.onDiscoverServicesFailed(listenerKey, error);
2626 } catch (RemoteException e) {
2627 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2628 }
2629 }
2630
Paul Hu812e9212023-06-20 06:24:53 +00002631 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2632 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002633 try {
2634 mCb.onServiceFound(listenerKey, info);
2635 } catch (RemoteException e) {
2636 Log.e(TAG, "Error calling onServiceFound(", e);
2637 }
2638 }
2639
Paul Hu812e9212023-06-20 06:24:53 +00002640 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2641 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002642 try {
2643 mCb.onServiceLost(listenerKey, info);
2644 } catch (RemoteException e) {
2645 Log.e(TAG, "Error calling onServiceLost(", e);
2646 }
2647 }
2648
2649 void onStopDiscoveryFailed(int listenerKey, int error) {
2650 try {
2651 mCb.onStopDiscoveryFailed(listenerKey, error);
2652 } catch (RemoteException e) {
2653 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2654 }
2655 }
2656
Paul Hu812e9212023-06-20 06:24:53 +00002657 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2658 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002659 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002660 request.mTransactionId,
2661 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2662 request.getFoundServiceCount(),
2663 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002664 request.getServicesCount(),
2665 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002666 try {
2667 mCb.onStopDiscoverySucceeded(listenerKey);
2668 } catch (RemoteException e) {
2669 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2670 }
2671 }
2672
Paul Hu508a0122023-09-11 15:31:33 +08002673 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2674 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2675 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002676 }
2677
Paul Hu508a0122023-09-11 15:31:33 +08002678 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2679 int transactionId, long durationMs) {
2680 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002681 try {
2682 mCb.onRegisterServiceFailed(listenerKey, error);
2683 } catch (RemoteException e) {
2684 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2685 }
2686 }
2687
Paul Hu508a0122023-09-11 15:31:33 +08002688 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2689 ClientRequest request) {
2690 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2691 request.mTransactionId,
2692 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002693 try {
2694 mCb.onRegisterServiceSucceeded(listenerKey, info);
2695 } catch (RemoteException e) {
2696 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2697 }
2698 }
2699
2700 void onUnregisterServiceFailed(int listenerKey, int error) {
2701 try {
2702 mCb.onUnregisterServiceFailed(listenerKey, error);
2703 } catch (RemoteException e) {
2704 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2705 }
2706 }
2707
Paul Hu508a0122023-09-11 15:31:33 +08002708 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002709 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002710 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2711 request.mTransactionId,
2712 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002713 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2714 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002715 try {
2716 mCb.onUnregisterServiceSucceeded(listenerKey);
2717 } catch (RemoteException e) {
2718 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2719 }
2720 }
2721
Paul Hu508a0122023-09-11 15:31:33 +08002722 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2723 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2724 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002725 }
2726
Paul Hu508a0122023-09-11 15:31:33 +08002727 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2728 int transactionId, long durationMs) {
2729 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002730 try {
2731 mCb.onResolveServiceFailed(listenerKey, error);
2732 } catch (RemoteException e) {
2733 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2734 }
2735 }
2736
Paul Hua6bc4632023-06-26 01:18:29 +00002737 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2738 ClientRequest request) {
2739 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002740 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002741 request.mTransactionId,
2742 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002743 request.isServiceFromCache(),
2744 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002745 try {
2746 mCb.onResolveServiceSucceeded(listenerKey, info);
2747 } catch (RemoteException e) {
2748 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2749 }
2750 }
Paul Hub58deb72022-12-26 09:24:42 +00002751
2752 void onStopResolutionFailed(int listenerKey, int error) {
2753 try {
2754 mCb.onStopResolutionFailed(listenerKey, error);
2755 } catch (RemoteException e) {
2756 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2757 }
2758 }
2759
Paul Hu60149052023-07-31 14:26:08 +08002760 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2761 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002762 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002763 request.mTransactionId,
2764 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002765 try {
2766 mCb.onStopResolutionSucceeded(listenerKey);
2767 } catch (RemoteException e) {
2768 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2769 }
2770 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002771
2772 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002773 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002774 try {
2775 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2776 } catch (RemoteException e) {
2777 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2778 }
2779 }
2780
Paul Huddce5912023-08-01 10:26:49 +08002781 void onServiceInfoCallbackRegistered(int transactionId) {
2782 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2783 }
2784
2785 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2786 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002787 try {
2788 mCb.onServiceUpdated(listenerKey, info);
2789 } catch (RemoteException e) {
2790 Log.e(TAG, "Error calling onServiceUpdated", e);
2791 }
2792 }
2793
Paul Huddce5912023-08-01 10:26:49 +08002794 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2795 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002796 try {
2797 mCb.onServiceUpdatedLost(listenerKey);
2798 } catch (RemoteException e) {
2799 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2800 }
2801 }
2802
Paul Huddce5912023-08-01 10:26:49 +08002803 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2804 mMetrics.reportServiceInfoCallbackUnregistered(
2805 request.mTransactionId,
2806 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2807 request.getFoundServiceCount(),
2808 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002809 request.isServiceFromCache(),
2810 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002811 try {
2812 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2813 } catch (RemoteException e) {
2814 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2815 }
2816 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002817 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002818}