blob: 43357e445d796c889c6ace5ad1c24316b847c09d [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;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090029
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090030import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090031import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080032import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
33import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090034import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000035import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090036
Paul Hu23fa2022023-01-13 22:57:24 +080037import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080038import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090039import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090040import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080041import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070042import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090043import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090044import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080045import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090046import android.net.LinkProperties;
47import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080048import android.net.mdns.aidl.DiscoveryInfo;
49import android.net.mdns.aidl.GetAddressInfo;
50import android.net.mdns.aidl.IMDnsEventListener;
51import android.net.mdns.aidl.RegistrationInfo;
52import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070053import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090054import android.net.nsd.INsdManagerCallback;
55import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090056import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080057import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080059import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090060import android.net.nsd.OffloadEngine;
61import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090062import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000063import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090064import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090065import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080066import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090067import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070069import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090070import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090071import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070072import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090073import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080074import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090075import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090076import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090077import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070078import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070079
paulhua262cc12019-08-12 16:25:11 +080080import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000081import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080082import com.android.internal.util.State;
83import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000084import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090085import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090086import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080087import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090088import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080089import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000090import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090092import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080093import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090094import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090095import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080096import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080097import com.android.server.connectivity.mdns.MdnsSearchOptions;
98import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
99import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800100import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900101import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800102
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700103import java.io.FileDescriptor;
104import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900105import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700106import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900107import java.net.NetworkInterface;
108import java.net.SocketException;
109import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800110import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900111import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700112import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800113import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800114import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900115import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000116import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800117import java.util.regex.Matcher;
118import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700119
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700120/**
121 * Network Service Discovery Service handles remote service discovery operation requests by
122 * implementing the INsdManager interface.
123 *
124 * @hide
125 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900126@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700127public class NsdService extends INsdManager.Stub {
128 private static final String TAG = "NsdService";
129 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900130 /**
131 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
132 * implementation.
133 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800134 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800135 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700136
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900137 /**
138 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
139 * implementation.
140 */
141 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
142
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900143 /**
144 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
145 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
146 *
147 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
148 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
149 *
150 * In which case the flags:
151 * "mdns_discovery_manager_allowlist_mytype_version",
152 * "mdns_advertiser_allowlist_mytype_version",
153 * "mdns_discovery_manager_allowlist_othertype_version",
154 * "mdns_advertiser_allowlist_othertype_version"
155 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
156 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900157 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900158 *
159 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
160 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
161 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
162 */
163 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
164
165 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
166 "mdns_discovery_manager_allowlist_";
167 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
168 "mdns_advertiser_allowlist_";
169 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
170
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900171 @VisibleForTesting
172 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
173 "mdns_config_running_app_active_importance_cutoff";
174 @VisibleForTesting
175 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
176 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
177 private final int mRunningAppActiveImportanceCutoff;
178
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900179 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000180 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900181 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000182 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
183 @VisibleForTesting
184 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800185 private static final int NO_SENT_QUERY_COUNT = 0;
186 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800187 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700188
Hugo Benichi32be63d2017-04-05 14:06:11 +0900189 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900190 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800191 private final MDnsManager mMDnsManager;
192 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900193 @NonNull
194 private final Dependencies mDeps;
195 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800196 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900197 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800198 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900199 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800200 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900201 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900202 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000203 @NonNull
204 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800205 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800206 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800207 // state machine thread. If change this outside state machine, it will need to introduce
208 // synchronization.
209 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800210 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700211
212 /**
213 * Clients receiving asynchronous messages
214 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900215 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700216
Paul Hud44e1b72023-06-16 02:07:42 +0000217 /* A map from transaction(unique) id to client info */
218 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700219
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900220 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
221 @Nullable
222 private WifiManager.MulticastLock mHeldMulticastLock;
223 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
224 // (non-null), value is the requested Network (nullable)
225 @NonNull
226 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
227 @NonNull
228 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
229
Luke Huang05298582021-06-13 16:52:05 +0000230 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700231
Hugo Benichi32be63d2017-04-05 14:06:11 +0900232 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700233 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800234 // The count of the connected legacy clients.
235 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000236 // The number of client that ever connected.
237 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700238
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900239 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
240 new RemoteCallbackList<>();
241
242 private static class OffloadEngineInfo {
243 @NonNull final String mInterfaceName;
244 final long mOffloadCapabilities;
245 final long mOffloadType;
246 @NonNull final IOffloadEngine mOffloadEngine;
247
248 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
249 @NonNull String interfaceName, long capabilities, long offloadType) {
250 this.mOffloadEngine = offloadEngine;
251 this.mInterfaceName = interfaceName;
252 this.mOffloadCapabilities = capabilities;
253 this.mOffloadType = offloadType;
254 }
255 }
256
Paul Hu812e9212023-06-20 06:24:53 +0000257 @VisibleForTesting
258 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000259 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800260 protected final int mTransactionId;
261 @NonNull
262 protected final NsdServiceInfo mReqServiceInfo;
263 @NonNull
264 protected final String mListenedServiceType;
265
Paul Hud44e1b72023-06-16 02:07:42 +0000266 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800267 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000268 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800269 mTransactionId = transactionId;
270 mReqServiceInfo = reqServiceInfo;
271 mListenedServiceType = listenedServiceType;
272 }
273
274 @NonNull
275 public String getListenedServiceType() {
276 return mListenedServiceType;
277 }
278
279 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000280 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
281 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800282
283 @Override
284 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
285
286 @Override
287 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
288
289 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000290 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
291 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800292
293 @Override
294 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
295
296 @Override
297 public void onSearchStoppedWithError(int error) { }
298
299 @Override
300 public void onSearchFailedToStart() { }
301
302 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800303 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
304 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800305
306 @Override
307 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
308 }
309
310 private class DiscoveryListener extends MdnsListener {
311
Paul Hud44e1b72023-06-16 02:07:42 +0000312 DiscoveryListener(int clientRequestId, int transactionId,
313 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
314 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800315 }
316
317 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000318 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
319 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800320 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
321 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000322 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800323 }
324
325 @Override
326 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800327 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
328 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000329 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800330 }
Paul Hubad6fe92023-07-24 21:25:22 +0800331
332 @Override
333 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
334 int sentQueryTransactionId) {
335 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
336 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
337 }
Paul Hu23fa2022023-01-13 22:57:24 +0800338 }
339
Paul Hu75069ed2023-01-14 00:31:09 +0800340 private class ResolutionListener extends MdnsListener {
341
Paul Hud44e1b72023-06-16 02:07:42 +0000342 ResolutionListener(int clientRequestId, int transactionId,
343 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
344 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800345 }
346
347 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000348 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800349 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
350 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000351 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800352 }
Paul Hubad6fe92023-07-24 21:25:22 +0800353
354 @Override
355 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
356 int sentQueryTransactionId) {
357 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
358 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
359 }
Paul Hu75069ed2023-01-14 00:31:09 +0800360 }
361
Paul Hu30bd70d2023-02-07 13:20:56 +0000362 private class ServiceInfoListener extends MdnsListener {
363
Paul Hud44e1b72023-06-16 02:07:42 +0000364 ServiceInfoListener(int clientRequestId, int transactionId,
365 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
366 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000367 }
368
369 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000370 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
371 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000372 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
373 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000374 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000375 }
376
377 @Override
378 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
379 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
380 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000381 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000382 }
383
384 @Override
385 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
386 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
387 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000388 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000389 }
Paul Hubad6fe92023-07-24 21:25:22 +0800390
391 @Override
392 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
393 int sentQueryTransactionId) {
394 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
395 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
396 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000397 }
398
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900399 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
400 @Override
401 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
402 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
403 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
404 // filtering on such interfaces, so taking the multicast lock is not necessary to
405 // disable APF filtering of multicast.
406 if (socketNetwork == null
407 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
408 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
409 return;
410 }
411
412 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
413 updateMulticastLock();
414 }
415 }
416
417 @Override
418 public void onSocketDestroyed(@Nullable Network socketNetwork,
419 @NonNull MdnsInterfaceSocket socket) {
420 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
421 updateMulticastLock();
422 }
423 }
424 }
425
426 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
427 private final Handler mHandler;
428
429 private UidImportanceListener(Handler handler) {
430 mHandler = handler;
431 }
432
433 @Override
434 public void onUidImportance(int uid, int importance) {
435 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
436 }
437 }
438
439 private void handleUidImportanceChanged(int uid, int importance) {
440 // Lower importance values are more "important"
441 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
442 ? mRunningAppActiveUids.add(uid)
443 : mRunningAppActiveUids.remove(uid);
444 if (modified) {
445 updateMulticastLock();
446 }
447 }
448
449 /**
450 * Take or release the lock based on updated internal state.
451 *
452 * This determines whether the lock needs to be held based on
453 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
454 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
455 * updated.
456 */
457 private void updateMulticastLock() {
458 final int needsLockUid = getMulticastLockNeededUid();
459 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
460 final WifiManager wm = mContext.getSystemService(WifiManager.class);
461 if (wm == null) {
462 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
463 return;
464 }
465 mHeldMulticastLock = wm.createMulticastLock(TAG);
466 mHeldMulticastLock.acquire();
467 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
468 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
469 mHeldMulticastLock.release();
470 mHeldMulticastLock = null;
471 mServiceLogs.log("Released multicast lock");
472 }
473 }
474
475 /**
476 * @return The UID of an app requiring the multicast lock, or -1 if none.
477 */
478 private int getMulticastLockNeededUid() {
479 if (mWifiLockRequiredNetworks.size() == 0) {
480 // Return early if NSD is not active, or not on any relevant network
481 return -1;
482 }
Paul Hud44e1b72023-06-16 02:07:42 +0000483 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
484 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900485 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
486 // Ignore non-active UIDs
487 continue;
488 }
489
490 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
491 return clientInfo.mUid;
492 }
493 }
494 return -1;
495 }
496
Paul Hu019621e2023-01-13 23:26:49 +0800497 /**
498 * Data class of mdns service callback information.
499 */
500 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000501 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800502 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800503 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000504 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800505
Paul Hubad6fe92023-07-24 21:25:22 +0800506 MdnsEvent(int clientRequestId) {
507 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
508 }
509
510 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000511 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
512 }
513
Paul Hubad6fe92023-07-24 21:25:22 +0800514 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000515 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000516 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800517 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000518 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800519 }
520 }
521
Paul Hu77c11182023-10-23 16:17:32 +0800522 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700523 private class NsdStateMachine extends StateMachine {
524
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700525 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700526
527 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700528 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900529 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700530 }
531
Luke Huang92860f92021-06-23 06:29:30 +0000532 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800533 if (mIsDaemonStarted) {
534 if (DBG) Log.d(TAG, "Daemon is already started.");
535 return;
536 }
537 mMDnsManager.registerEventListener(mMDnsEventCallback);
538 mMDnsManager.startDaemon();
539 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000540 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000541 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000542 }
543
paulhu2b9ed952022-02-10 21:58:32 +0800544 private void maybeStopDaemon() {
545 if (!mIsDaemonStarted) {
546 if (DBG) Log.d(TAG, "Daemon has not been started.");
547 return;
548 }
549 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
550 mMDnsManager.stopDaemon();
551 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000552 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800553 }
554
Luke Huang92860f92021-06-23 06:29:30 +0000555 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000556 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000557 }
558
559 private void scheduleStop() {
560 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
561 }
562 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800563 // The native daemon should stay alive and can't be cleanup
564 // if any legacy client connected.
565 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000566 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000567 }
568 }
569
Luke Huang92860f92021-06-23 06:29:30 +0000570 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000571 this.removeMessages(NsdManager.DAEMON_CLEANUP);
572 }
573
Paul Hu23fa2022023-01-13 22:57:24 +0800574 private void maybeStartMonitoringSockets() {
575 if (mIsMonitoringSocketsStarted) {
576 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
577 return;
578 }
579
580 mMdnsSocketProvider.startMonitoringSockets();
581 mIsMonitoringSocketsStarted = true;
582 }
583
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900584 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
585 if (!mIsMonitoringSocketsStarted) return;
586 if (isAnyRequestActive()) return;
587
Paul Hu58f20602023-02-18 11:41:07 +0800588 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800589 mIsMonitoringSocketsStarted = false;
590 }
591
Hugo Benichi803a2f02017-04-24 11:35:06 +0900592 NsdStateMachine(String name, Handler handler) {
593 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800594 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800595 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900596 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700597 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 }
599
Irfan Sheriff75006652012-04-17 23:15:29 -0700600 class EnabledState extends State {
601 @Override
602 public void enter() {
603 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700604 }
605
606 @Override
607 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000608 // TODO: it is incorrect to stop the daemon without expunging all requests
609 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000610 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700611 }
612
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700613 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900614 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800615 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700616 return true;
617 }
618 return false;
619 }
620
Paul Hu508a0122023-09-11 15:31:33 +0800621 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000622 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800623 final LegacyClientRequest request =
624 new LegacyClientRequest(transactionId, what, startTimeMs);
625 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000626 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000627 // Remove the cleanup event because here comes a new request.
628 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800629 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700630 }
631
Paul Hud44e1b72023-06-16 02:07:42 +0000632 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900633 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000634 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000635 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000636 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900637 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800638 }
639
Paul Hud44e1b72023-06-16 02:07:42 +0000640 private void removeRequestMap(
641 int clientRequestId, int transactionId, ClientInfo clientInfo) {
642 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900643 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000644 clientInfo.mClientRequests.remove(clientRequestId);
645 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900646
647 if (existing instanceof LegacyClientRequest) {
648 maybeScheduleStop();
649 } else {
650 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900651 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900652 }
653 }
654
Paul Hu508a0122023-09-11 15:31:33 +0800655 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
656 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900657 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800658 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
659 listener, requestedNetwork, mClock.elapsedRealtime());
660 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000661 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900662 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800663 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800664 }
665
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900666 /**
667 * Truncate a service name to up to 63 UTF-8 bytes.
668 *
669 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
670 * names used in registerService follows historical behavior (see mdnsresponder
671 * handle_regservice_request).
672 */
673 @NonNull
674 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900675 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800676 }
677
Paul Hud44e1b72023-06-16 02:07:42 +0000678 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
679 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800680 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000681 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800682 }
683
Paul Hu77c11182023-10-23 16:17:32 +0800684 private ClientInfo getClientInfoForReply(Message msg) {
685 final ListenerArgs args = (ListenerArgs) msg.obj;
686 return mClients.get(args.connector);
687 }
688
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 @Override
690 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900691 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000692 final int transactionId;
693 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900694 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900695 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700696 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800697 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800698 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900699 args = (ListenerArgs) msg.obj;
700 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000701 // If the binder death notification for a INsdManagerCallback was received
702 // before any calls are received by NsdService, the clientInfo would be
703 // cleared and cause NPE. Add a null check here to prevent this corner case.
704 if (clientInfo == null) {
705 Log.e(TAG, "Unknown connector in discovery");
706 break;
707 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700708
709 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800710 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
711 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 break;
713 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700714
Paul Hu23fa2022023-01-13 22:57:24 +0800715 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000716 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900717 final Pair<String, String> typeAndSubtype =
718 parseTypeAndSubtype(info.getServiceType());
719 final String serviceType = typeAndSubtype == null
720 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800721 if (clientInfo.mUseJavaBackend
722 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900723 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800724 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800725 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
726 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800727 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700728 }
Paul Hu23fa2022023-01-13 22:57:24 +0800729
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900730 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800731 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000732 final MdnsListener listener = new DiscoveryListener(clientRequestId,
733 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900734 final MdnsSearchOptions.Builder optionsBuilder =
735 MdnsSearchOptions.newBuilder()
736 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900737 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900738 .setIsPassiveMode(true);
739 if (typeAndSubtype.second != null) {
740 // The parsing ensures subtype starts with an underscore.
741 // MdnsSearchOptions expects the underscore to not be present.
742 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
743 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900744 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900745 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800746 final ClientRequest request = storeDiscoveryManagerRequestMap(
747 clientRequestId, transactionId, listener, clientInfo,
748 info.getNetwork());
749 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000750 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000751 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700752 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800753 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000754 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800755 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000756 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800757 + info.getServiceType());
758 }
Paul Hu508a0122023-09-11 15:31:33 +0800759 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
760 transactionId, clientInfo, msg.what,
761 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000762 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800763 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800764 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000765 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800766 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
767 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800768 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700769 }
770 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800771 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900772 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800773 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900774 args = (ListenerArgs) msg.obj;
775 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000776 // If the binder death notification for a INsdManagerCallback was received
777 // before any calls are received by NsdService, the clientInfo would be
778 // cleared and cause NPE. Add a null check here to prevent this corner case.
779 if (clientInfo == null) {
780 Log.e(TAG, "Unknown connector in stop discovery");
781 break;
782 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700783
Paul Hud44e1b72023-06-16 02:07:42 +0000784 final ClientRequest request =
785 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900786 if (request == null) {
787 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700788 break;
789 }
Paul Hud44e1b72023-06-16 02:07:42 +0000790 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900791 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
792 // point, so this needs to check the type of the original request to
793 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900794 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000795 stopDiscoveryManagerRequest(
796 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000797 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000798 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700799 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000800 removeRequestMap(clientRequestId, transactionId, clientInfo);
801 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000802 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800803 } else {
804 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000805 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800806 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700807 }
808 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900809 }
810 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800811 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900812 args = (ListenerArgs) msg.obj;
813 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000814 // If the binder death notification for a INsdManagerCallback was received
815 // before any calls are received by NsdService, the clientInfo would be
816 // cleared and cause NPE. Add a null check here to prevent this corner case.
817 if (clientInfo == null) {
818 Log.e(TAG, "Unknown connector in registration");
819 break;
820 }
821
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700822 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800823 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
824 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700825 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700826 }
827
Paul Hud44e1b72023-06-16 02:07:42 +0000828 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900829 final NsdServiceInfo serviceInfo = args.serviceInfo;
830 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900831 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
832 final String registerServiceType = typeSubtype == null
833 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800834 if (clientInfo.mUseJavaBackend
835 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900836 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900837 if (registerServiceType == null) {
838 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800839 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
840 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900841 break;
842 }
843 serviceInfo.setServiceType(registerServiceType);
844 serviceInfo.setServiceName(truncateServiceName(
845 serviceInfo.getServiceName()));
846
847 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900848 // TODO: pass in the subtype as well. Including the subtype in the
849 // service type would generate service instance names like
850 // Name._subtype._sub._type._tcp, which is incorrect
851 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000852 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
853 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900854 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700855 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900856 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000857 if (registerService(transactionId, serviceInfo)) {
858 if (DBG) {
859 Log.d(TAG, "Register " + clientRequestId
860 + " " + transactionId);
861 }
Paul Hua6bc4632023-06-26 01:18:29 +0000862 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
863 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900864 // Return success after mDns reports success
865 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000866 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800867 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
868 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900869 }
870
Irfan Sheriff75006652012-04-17 23:15:29 -0700871 }
872 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900873 }
874 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800875 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900876 args = (ListenerArgs) msg.obj;
877 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000878 // If the binder death notification for a INsdManagerCallback was received
879 // before any calls are received by NsdService, the clientInfo would be
880 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900881 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800882 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700883 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700884 }
Paul Hud44e1b72023-06-16 02:07:42 +0000885 final ClientRequest request =
886 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900887 if (request == null) {
888 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
889 break;
890 }
Paul Hud44e1b72023-06-16 02:07:42 +0000891 transactionId = request.mTransactionId;
892 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900893
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900894 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
895 // so this needs to check the type of the original request to unregister
896 // instead of looking at the flag value.
897 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800898 final AdvertiserMetrics metrics =
899 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000900 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800901 clientInfo.onUnregisterServiceSucceeded(
902 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700903 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000904 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800905 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800906 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
907 NO_PACKET /* sentPacketCount */,
908 0 /* conflictDuringProbingCount */,
909 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900910 } else {
911 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000912 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900913 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700914 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700915 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900916 }
Paul Hu75069ed2023-01-14 00:31:09 +0800917 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800918 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900919 args = (ListenerArgs) msg.obj;
920 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000921 // If the binder death notification for a INsdManagerCallback was received
922 // before any calls are received by NsdService, the clientInfo would be
923 // cleared and cause NPE. Add a null check here to prevent this corner case.
924 if (clientInfo == null) {
925 Log.e(TAG, "Unknown connector in resolution");
926 break;
927 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700928
Paul Hu75069ed2023-01-14 00:31:09 +0800929 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000930 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900931 final Pair<String, String> typeSubtype =
932 parseTypeAndSubtype(info.getServiceType());
933 final String serviceType = typeSubtype == null
934 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800935 if (clientInfo.mUseJavaBackend
936 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900937 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800938 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800939 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
940 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800941 break;
942 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900943 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800944
945 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000946 final MdnsListener listener = new ResolutionListener(clientRequestId,
947 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800948 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
949 .setNetwork(info.getNetwork())
950 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900951 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900952 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800953 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900954 mMdnsDiscoveryManager.registerListener(
955 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000956 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
957 listener, clientInfo, info.getNetwork());
958 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000959 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700960 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800961 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800962 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
963 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800964 break;
965 }
966
967 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000968 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800969 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +0000970 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
971 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +0800972 } else {
Paul Hu508a0122023-09-11 15:31:33 +0800973 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
974 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800975 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700976 }
977 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800978 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900979 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000980 if (DBG) Log.d(TAG, "Stop service resolution");
981 args = (ListenerArgs) msg.obj;
982 clientInfo = mClients.get(args.connector);
983 // If the binder death notification for a INsdManagerCallback was received
984 // before any calls are received by NsdService, the clientInfo would be
985 // cleared and cause NPE. Add a null check here to prevent this corner case.
986 if (clientInfo == null) {
987 Log.e(TAG, "Unknown connector in stop resolution");
988 break;
989 }
990
Paul Hud44e1b72023-06-16 02:07:42 +0000991 final ClientRequest request =
992 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900993 if (request == null) {
994 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
995 break;
996 }
Paul Hud44e1b72023-06-16 02:07:42 +0000997 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +0800998 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
999 // point, so this needs to check the type of the original request to
1000 // unregister instead of looking at the flag value.
1001 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001002 stopDiscoveryManagerRequest(
1003 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001004 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001005 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001006 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001007 removeRequestMap(clientRequestId, transactionId, clientInfo);
1008 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001009 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001010 } else {
1011 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001012 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001013 }
1014 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001015 }
Paul Hub58deb72022-12-26 09:24:42 +00001016 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001017 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001018 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001019 if (DBG) Log.d(TAG, "Register a service callback");
1020 args = (ListenerArgs) msg.obj;
1021 clientInfo = mClients.get(args.connector);
1022 // If the binder death notification for a INsdManagerCallback was received
1023 // before any calls are received by NsdService, the clientInfo would be
1024 // cleared and cause NPE. Add a null check here to prevent this corner case.
1025 if (clientInfo == null) {
1026 Log.e(TAG, "Unknown connector in callback registration");
1027 break;
1028 }
1029
Paul Hu30bd70d2023-02-07 13:20:56 +00001030 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001031 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001032 final Pair<String, String> typeAndSubtype =
1033 parseTypeAndSubtype(info.getServiceType());
1034 final String serviceType = typeAndSubtype == null
1035 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001036 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001037 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001038 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001039 break;
1040 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001041 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001042
Paul Hu30bd70d2023-02-07 13:20:56 +00001043 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001044 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1045 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001046 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1047 .setNetwork(info.getNetwork())
1048 .setIsPassiveMode(true)
1049 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001050 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001051 .build();
1052 mMdnsDiscoveryManager.registerListener(
1053 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001054 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1055 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001056 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001057 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001058 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001059 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001060 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001061 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001062 if (DBG) Log.d(TAG, "Unregister a service callback");
1063 args = (ListenerArgs) msg.obj;
1064 clientInfo = mClients.get(args.connector);
1065 // If the binder death notification for a INsdManagerCallback was received
1066 // before any calls are received by NsdService, the clientInfo would be
1067 // cleared and cause NPE. Add a null check here to prevent this corner case.
1068 if (clientInfo == null) {
1069 Log.e(TAG, "Unknown connector in callback unregistration");
1070 break;
1071 }
1072
Paul Hud44e1b72023-06-16 02:07:42 +00001073 final ClientRequest request =
1074 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001075 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001076 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001077 break;
1078 }
Paul Hud44e1b72023-06-16 02:07:42 +00001079 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001080 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001081 stopDiscoveryManagerRequest(
1082 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001083 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001084 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001085 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001087 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001088 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001089 }
paulhu2b9ed952022-02-10 21:58:32 +08001090 case MDNS_SERVICE_EVENT:
1091 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001092 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001093 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001094 break;
Paul Hu019621e2023-01-13 23:26:49 +08001095 case MDNS_DISCOVERY_MANAGER_EVENT:
1096 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1097 return NOT_HANDLED;
1098 }
1099 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001100 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1101 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1102 // TODO: Limits the number of registrations created by a given class.
1103 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1104 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001105 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001106 break;
1107 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1108 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1109 break;
Paul Hu77c11182023-10-23 16:17:32 +08001110 case NsdManager.REGISTER_CLIENT:
1111 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1112 final INsdManagerCallback cb = arg.callback;
1113 try {
1114 cb.asBinder().linkToDeath(arg.connector, 0);
1115 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1116 final NetworkNsdReportedMetrics metrics =
1117 mDeps.makeNetworkNsdReportedMetrics(
1118 (int) mClock.elapsedRealtime());
1119 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1120 mServiceLogs.forSubComponent(tag), metrics);
1121 mClients.put(arg.connector, clientInfo);
1122 } catch (RemoteException e) {
1123 Log.w(TAG, "Client request id " + clientRequestId
1124 + " has already died");
1125 }
1126 break;
1127 case NsdManager.UNREGISTER_CLIENT:
1128 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1129 clientInfo = mClients.remove(connector);
1130 if (clientInfo != null) {
1131 clientInfo.expungeAllRequests();
1132 if (clientInfo.isPreSClient()) {
1133 mLegacyClientCount -= 1;
1134 }
1135 }
1136 maybeStopMonitoringSocketsIfNoActiveRequest();
1137 maybeScheduleStop();
1138 break;
1139 case NsdManager.DAEMON_CLEANUP:
1140 maybeStopDaemon();
1141 break;
1142 // This event should be only sent by the legacy (target SDK < S) clients.
1143 // Mark the sending client as legacy.
1144 case NsdManager.DAEMON_STARTUP:
1145 clientInfo = getClientInfoForReply(msg);
1146 if (clientInfo != null) {
1147 cancelStop();
1148 clientInfo.setPreSClient();
1149 mLegacyClientCount += 1;
1150 maybeStartDaemon();
1151 }
1152 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001153 default:
Paul Hu77c11182023-10-23 16:17:32 +08001154 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001155 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001156 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001157 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001158 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001159
Paul Hud44e1b72023-06-16 02:07:42 +00001160 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001161 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001162 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001163 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001164 Log.e(TAG, String.format(
1165 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001166 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001167 }
1168
1169 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001170 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1171 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001172 // This can happen because of race conditions. For example,
1173 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1174 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001175 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1176 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001177 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001178 }
Paul Hu812e9212023-06-20 06:24:53 +00001179 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1180 if (request == null) {
1181 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1182 return false;
1183 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001184 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001185 Log.d(TAG, String.format(
1186 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001187 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001188 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001189 case IMDnsEventListener.SERVICE_FOUND: {
1190 final DiscoveryInfo info = (DiscoveryInfo) obj;
1191 final String name = info.serviceName;
1192 final String type = info.registrationType;
1193 servInfo = new NsdServiceInfo(name, type);
1194 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001195 if (foundNetId == 0L) {
1196 // Ignore services that do not have a Network: they are not usable
1197 // by apps, as they would need privileged permissions to use
1198 // interfaces that do not have an associated Network.
1199 break;
1200 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001201 if (foundNetId == INetd.DUMMY_NET_ID) {
1202 // Ignore services on the dummy0 interface: they are only seen when
1203 // discovering locally advertised services, and are not reachable
1204 // through that interface.
1205 break;
1206 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001207 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001208
1209 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001210 break;
paulhu2b9ed952022-02-10 21:58:32 +08001211 }
1212 case IMDnsEventListener.SERVICE_LOST: {
1213 final DiscoveryInfo info = (DiscoveryInfo) obj;
1214 final String name = info.serviceName;
1215 final String type = info.registrationType;
1216 final int lostNetId = info.netId;
1217 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001218 // The network could be set to null (netId 0) if it was torn down when the
1219 // service is lost
1220 // TODO: avoid returning null in that case, possibly by remembering
1221 // found services on the same interface index and their network at the time
1222 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001223 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001224 break;
paulhu2b9ed952022-02-10 21:58:32 +08001225 }
1226 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001227 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001228 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1229 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001230 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001231 break;
paulhu2b9ed952022-02-10 21:58:32 +08001232 case IMDnsEventListener.SERVICE_REGISTERED: {
1233 final RegistrationInfo info = (RegistrationInfo) obj;
1234 final String name = info.serviceName;
1235 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001236 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001237 break;
paulhu2b9ed952022-02-10 21:58:32 +08001238 }
1239 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001240 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001241 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1242 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001243 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001244 break;
paulhu2b9ed952022-02-10 21:58:32 +08001245 case IMDnsEventListener.SERVICE_RESOLVED: {
1246 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001247 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001248 final String fullName = info.serviceFullName;
1249 while (index < fullName.length() && fullName.charAt(index) != '.') {
1250 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001251 ++index;
1252 }
1253 ++index;
1254 }
paulhu2b9ed952022-02-10 21:58:32 +08001255 if (index >= fullName.length()) {
1256 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001257 break;
1258 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001259
paulhube186602022-04-12 07:18:23 +00001260 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001261 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001262 String type = rest.replace(".local.", "");
1263
Paul Hu30bd70d2023-02-07 13:20:56 +00001264 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001265 serviceInfo.setServiceName(name);
1266 serviceInfo.setServiceType(type);
1267 serviceInfo.setPort(info.port);
1268 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001269 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001270
Paul Hud44e1b72023-06-16 02:07:42 +00001271 stopResolveService(transactionId);
1272 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001273
Paul Hud44e1b72023-06-16 02:07:42 +00001274 final int transactionId2 = getUniqueId();
1275 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1276 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001277 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001278 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001279 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001280 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1281 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001282 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001283 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001284 }
1285 break;
paulhu2b9ed952022-02-10 21:58:32 +08001286 }
1287 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001288 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001289 stopResolveService(transactionId);
1290 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001291 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001292 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1293 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001294 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001295 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001296 break;
paulhu2b9ed952022-02-10 21:58:32 +08001297 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001298 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001299 stopGetAddrInfo(transactionId);
1300 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001301 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001302 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1303 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001304 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001305 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001306 break;
paulhu2b9ed952022-02-10 21:58:32 +08001307 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001308 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001309 final GetAddressInfo info = (GetAddressInfo) obj;
1310 final String address = info.address;
1311 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001312 InetAddress serviceHost = null;
1313 try {
paulhu2b9ed952022-02-10 21:58:32 +08001314 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001315 } catch (UnknownHostException e) {
1316 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1317 }
1318
1319 // If the resolved service is on an interface without a network, consider it
1320 // as a failure: it would not be usable by apps as they would need
1321 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001322 if (netId != NETID_UNSET && serviceHost != null) {
1323 clientInfo.mResolvedService.setHost(serviceHost);
1324 setServiceNetworkForCallback(clientInfo.mResolvedService,
1325 netId, info.interfaceIdx);
1326 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001327 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001328 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001329 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001330 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1331 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001332 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001333 }
Paul Hud44e1b72023-06-16 02:07:42 +00001334 stopGetAddrInfo(transactionId);
1335 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001336 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001337 break;
paulhu2b9ed952022-02-10 21:58:32 +08001338 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001339 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001340 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001342 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 }
Paul Hu019621e2023-01-13 23:26:49 +08001344
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001345 @Nullable
1346 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1347 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001348 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001349 final String[] typeArray = serviceInfo.getServiceType();
1350 final String joinedType;
1351 if (typeArray.length == 0
1352 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1353 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1354 + Arrays.toString(typeArray));
1355 return null;
1356 } else {
1357 joinedType = TextUtils.join(".",
1358 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1359 }
1360 final String serviceType;
1361 switch (code) {
1362 case NsdManager.SERVICE_FOUND:
1363 case NsdManager.SERVICE_LOST:
1364 // For consistency with historical behavior, discovered service types have
1365 // a dot at the end.
1366 serviceType = joinedType + ".";
1367 break;
1368 case RESOLVE_SERVICE_SUCCEEDED:
1369 // For consistency with historical behavior, resolved service types have
1370 // a dot at the beginning.
1371 serviceType = "." + joinedType;
1372 break;
1373 default:
1374 serviceType = joinedType;
1375 break;
1376 }
Paul Hu019621e2023-01-13 23:26:49 +08001377 final String serviceName = serviceInfo.getServiceInstanceName();
1378 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1379 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001380 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1381 // network for Tethering interface. In other words, the network == null means the
1382 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001383 setServiceNetworkForCallback(
1384 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001385 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001386 serviceInfo.getInterfaceIndex());
1387 return servInfo;
1388 }
1389
1390 private boolean handleMdnsDiscoveryManagerEvent(
1391 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001392 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001393 if (clientInfo == null) {
1394 Log.e(TAG, String.format(
1395 "id %d for %d has no client mapping", transactionId, code));
1396 return false;
1397 }
1398
1399 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001400 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001401 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1402 if (request == null) {
1403 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1404 return false;
1405 }
1406
1407 // Deal with the discovery sent callback
1408 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1409 request.onQuerySent();
1410 return true;
1411 }
1412
1413 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001414 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1415 // Errors are already logged if null
1416 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001417 mServiceLogs.log(String.format(
1418 "MdnsDiscoveryManager event code=%s transactionId=%d",
1419 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001420 switch (code) {
1421 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001422 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001423 break;
1424 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001425 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001426 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001427 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1428 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001429 info.setPort(serviceInfo.getPort());
1430
1431 Map<String, String> attrs = serviceInfo.getAttributes();
1432 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1433 final String key = kv.getKey();
1434 try {
1435 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1436 } catch (IllegalArgumentException e) {
1437 Log.e(TAG, "Invalid attribute", e);
1438 }
1439 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001440 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001441 if (addresses.size() != 0) {
1442 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001443 request.setServiceFromCache(event.mIsServiceFromCache);
1444 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001445 } else {
1446 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001447 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001448 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1449 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001450 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001451 }
1452
1453 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001454 if (!(request instanceof DiscoveryManagerRequest)) {
1455 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1456 break;
1457 }
Paul Hud44e1b72023-06-16 02:07:42 +00001458 stopDiscoveryManagerRequest(
1459 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001460 break;
1461 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001462 case NsdManager.SERVICE_UPDATED: {
1463 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1464 info.setPort(serviceInfo.getPort());
1465
1466 Map<String, String> attrs = serviceInfo.getAttributes();
1467 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1468 final String key = kv.getKey();
1469 try {
1470 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1471 } catch (IllegalArgumentException e) {
1472 Log.e(TAG, "Invalid attribute", e);
1473 }
1474 }
1475
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001476 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001477 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001478 clientInfo.onServiceUpdated(clientRequestId, info, request);
1479 // Set the ServiceFromCache flag only if the service is actually being
1480 // retrieved from the cache. This flag should not be overridden by later
1481 // service updates, which may not be cached.
1482 if (event.mIsServiceFromCache) {
1483 request.setServiceFromCache(true);
1484 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001485 break;
1486 }
1487 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001488 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001489 break;
Paul Hu019621e2023-01-13 23:26:49 +08001490 default:
1491 return false;
1492 }
1493 return true;
1494 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001495 }
1496 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001497
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001498 @NonNull
1499 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1500 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1501 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1502 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1503 for (String ipv4Address : v4Addrs) {
1504 try {
1505 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1506 } catch (IllegalArgumentException e) {
1507 Log.wtf(TAG, "Invalid ipv4 address", e);
1508 }
1509 }
1510 for (String ipv6Address : v6Addrs) {
1511 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001512 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1513 ipv6Address);
1514 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1515 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001516 Log.wtf(TAG, "Invalid ipv6 address", e);
1517 }
1518 }
1519 return addresses;
1520 }
1521
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001522 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1523 switch (netId) {
1524 case NETID_UNSET:
1525 info.setNetwork(null);
1526 break;
1527 case INetd.LOCAL_NET_ID:
1528 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1529 // visible / usable for apps, so do not return it. Store the interface
1530 // index instead, so at least if the client tries to resolve the service
1531 // with that NsdServiceInfo, it will be done on the same interface.
1532 // If they recreate the NsdServiceInfo themselves, resolution would be
1533 // done on all interfaces as before T, which should also work.
1534 info.setNetwork(null);
1535 info.setInterfaceIndex(ifaceIdx);
1536 break;
1537 default:
1538 info.setNetwork(new Network(netId));
1539 }
1540 }
1541
paulhube186602022-04-12 07:18:23 +00001542 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1543 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1544 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1545 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1546 private String unescape(String s) {
1547 StringBuilder sb = new StringBuilder(s.length());
1548 for (int i = 0; i < s.length(); ++i) {
1549 char c = s.charAt(i);
1550 if (c == '\\') {
1551 if (++i >= s.length()) {
1552 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1553 break;
1554 }
1555 c = s.charAt(i);
1556 if (c != '.' && c != '\\') {
1557 if (i + 2 >= s.length()) {
1558 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1559 break;
1560 }
1561 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1562 + (s.charAt(i + 2) - '0'));
1563 i += 2;
1564 }
1565 }
1566 sb.append(c);
1567 }
1568 return sb.toString();
1569 }
1570
Paul Hu7445e3d2023-03-03 15:14:00 +08001571 /**
1572 * Check the given service type is valid and construct it to a service type
1573 * which can use for discovery / resolution service.
1574 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001575 * <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 +08001576 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1577 * underscore; they are alphanumerical characters or dashes or underscore, except the
1578 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1579 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001580 * <p>The subtype may also be specified with a comma after the service type, for example
1581 * _type._tcp,_subtype.
1582 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001583 * @param serviceType the request service type for discovery / resolution service
1584 * @return constructed service type or null if the given service type is invalid.
1585 */
1586 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001587 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001588 if (TextUtils.isEmpty(serviceType)) return null;
1589
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001590 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001591 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001592 // Optional leading subtype (_subtype._type._tcp)
1593 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1594 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1595 // Actual type (_type._tcp.local)
1596 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001597 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001598 // e.g. allow "_type._tcp.local."
1599 + "\\.?"
1600 // Optional subtype after comma, for "_type._tcp,_subtype" format
1601 + "(?:,(" + typeOrSubtypePattern + "))?"
1602 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001603 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1604 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001605 // Use the subtype either at the beginning or after the comma
1606 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1607 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001608 }
1609
Hugo Benichi803a2f02017-04-24 11:35:06 +09001610 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001611 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001612 this(ctx, handler, cleanupDelayMs, new Dependencies());
1613 }
1614
1615 @VisibleForTesting
1616 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001617 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001618 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001619 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001620 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001621 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1622 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001623 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001624
Paul Hu14667de2023-04-17 22:42:47 +08001625 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001626 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001627 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001628 // address events are received. When the netlink monitor starts, any IP addresses already
1629 // on the interfaces will not be seen. In practice, the network will not connect at boot
1630 // time As a result, all the netlink message should be observed if the netlink monitor
1631 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001632 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001633
1634 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1635 // startBootstrapServices).
1636 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1637 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1638 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1639 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1640 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1641 mRunningAppActiveImportanceCutoff);
1642
Paul Huf3fe3332023-10-16 17:13:25 +08001643 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1644 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1645 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1646 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1647 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
1648 .setIsExpiredServicesRemovalEnabled(mDeps.isTrunkStableFeatureEnabled(
1649 MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001650 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1651 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001652 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001653 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001654 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001655 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001656 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001657 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001658 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1659 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001660 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001661 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001662 }
1663
1664 /**
1665 * Dependencies of NsdService, for injection in tests.
1666 */
1667 @VisibleForTesting
1668 public static class Dependencies {
1669 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001670 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001671 *
1672 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001673 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001674 */
1675 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001676 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001677 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001678 }
1679
1680 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001681 * Check whether the MdnsAdvertiser feature is enabled.
1682 *
1683 * @param context The global context information about an app environment.
1684 * @return true if the MdnsAdvertiser feature is enabled.
1685 */
1686 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001687 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001688 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001689 }
1690
1691 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001692 * Get the type allowlist flag value.
1693 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1694 */
1695 @Nullable
1696 public String getTypeAllowlistFlags() {
1697 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1698 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1699 }
1700
1701 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001702 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001703 */
1704 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001705 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001706 }
1707
1708 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001709 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1710 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001711 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1712 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001713 }
1714
1715 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001716 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1717 */
1718 public boolean isTrunkStableFeatureEnabled(String feature) {
1719 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1720 }
1721
1722 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001723 * @see MdnsDiscoveryManager
1724 */
1725 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001726 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001727 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1728 @NonNull MdnsFeatureFlags featureFlags) {
1729 return new MdnsDiscoveryManager(
1730 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001731 }
1732
1733 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001734 * @see MdnsAdvertiser
1735 */
1736 public MdnsAdvertiser makeMdnsAdvertiser(
1737 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001738 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1739 MdnsFeatureFlags featureFlags) {
1740 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001741 }
1742
1743 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001744 * @see MdnsSocketProvider
1745 */
Paul Hu14667de2023-04-17 22:42:47 +08001746 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001747 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1748 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1749 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1750 }
1751
1752 /**
1753 * @see DeviceConfig#getInt(String, String, int)
1754 */
1755 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1756 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1757 }
1758
1759 /**
1760 * @see Binder#getCallingUid()
1761 */
1762 public int getCallingUid() {
1763 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001764 }
Paul Hu777ed052023-06-19 13:35:15 +00001765
1766 /**
1767 * @see NetworkNsdReportedMetrics
1768 */
Paul Hu508a0122023-09-11 15:31:33 +08001769 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1770 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001771 }
1772
1773 /**
1774 * @see MdnsUtils.Clock
1775 */
1776 public Clock makeClock() {
1777 return new Clock();
1778 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001779 }
1780
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001781 /**
1782 * Return whether a type is allowlisted to use the Java backend.
1783 * @param type The service type
1784 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1785 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1786 */
1787 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1788 @NonNull String flagPrefix) {
1789 if (type == null) return false;
1790 final String typesConfig = mDeps.getTypeAllowlistFlags();
1791 if (TextUtils.isEmpty(typesConfig)) return false;
1792
1793 final String mappingPrefix = type + ":";
1794 String mappedFlag = null;
1795 for (String mapping : TextUtils.split(typesConfig, ",")) {
1796 if (mapping.startsWith(mappingPrefix)) {
1797 mappedFlag = mapping.substring(mappingPrefix.length());
1798 break;
1799 }
1800 }
1801
1802 if (mappedFlag == null) return false;
1803
1804 return mDeps.isFeatureEnabled(mContext,
1805 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1806 }
1807
1808 private boolean useDiscoveryManagerForType(@Nullable String type) {
1809 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1810 }
1811
1812 private boolean useAdvertiserForType(@Nullable String type) {
1813 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1814 }
1815
paulhu1b35e822022-04-08 14:48:41 +08001816 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001817 HandlerThread thread = new HandlerThread(TAG);
1818 thread.start();
1819 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001820 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001821 return service;
1822 }
1823
paulhu2b9ed952022-02-10 21:58:32 +08001824 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1825 private final StateMachine mStateMachine;
1826
1827 MDnsEventCallback(StateMachine sm) {
1828 mStateMachine = sm;
1829 }
1830
1831 @Override
1832 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1833 mStateMachine.sendMessage(
1834 MDNS_SERVICE_EVENT, status.result, status.id, status);
1835 }
1836
1837 @Override
1838 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1839 mStateMachine.sendMessage(
1840 MDNS_SERVICE_EVENT, status.result, status.id, status);
1841 }
1842
1843 @Override
1844 public void onServiceResolutionStatus(final ResolutionInfo status) {
1845 mStateMachine.sendMessage(
1846 MDNS_SERVICE_EVENT, status.result, status.id, status);
1847 }
1848
1849 @Override
1850 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1851 mStateMachine.sendMessage(
1852 MDNS_SERVICE_EVENT, status.result, status.id, status);
1853 }
1854
1855 @Override
1856 public int getInterfaceVersion() throws RemoteException {
1857 return this.VERSION;
1858 }
1859
1860 @Override
1861 public String getInterfaceHash() throws RemoteException {
1862 return this.HASH;
1863 }
1864 }
1865
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001866 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1867 final String targetInterface = offloadEngineInfo.mInterfaceName;
1868 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1869 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1870 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1871 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1872 try {
1873 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1874 } catch (RemoteException e) {
1875 // Can happen in regular cases, do not log a stacktrace
1876 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1877 }
1878 }
1879 }
1880
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001881 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1882 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1883 final int count = mOffloadEngines.beginBroadcast();
1884 try {
1885 for (int i = 0; i < count; i++) {
1886 final OffloadEngineInfo offloadEngineInfo =
1887 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1888 final String interfaceName = offloadEngineInfo.mInterfaceName;
1889 if (!targetInterfaceName.equals(interfaceName)
1890 || ((offloadEngineInfo.mOffloadType
1891 & offloadServiceInfo.getOffloadType()) == 0)) {
1892 continue;
1893 }
1894 try {
1895 if (isRemove) {
1896 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1897 offloadServiceInfo);
1898 } else {
1899 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1900 offloadServiceInfo);
1901 }
1902 } catch (RemoteException e) {
1903 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001904 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001905 }
1906 }
1907 } finally {
1908 mOffloadEngines.finishBroadcast();
1909 }
1910 }
1911
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001912 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001913 // TODO: add a callback to notify when a service is being added on each interface (as soon
1914 // as probing starts), and call mOffloadCallbacks. This callback is for
1915 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1916
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001917 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001918 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1919 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1920 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001921 if (clientInfo == null) return;
1922
Paul Hud44e1b72023-06-16 02:07:42 +00001923 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1924 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001925
1926 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1927 // historical behavior.
1928 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001929 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001930 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001931 }
1932
1933 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001934 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1935 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001936 if (clientInfo == null) return;
1937
Paul Hud44e1b72023-06-16 02:07:42 +00001938 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1939 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001940 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001941 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1942 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001943 }
1944
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001945 @Override
1946 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1947 @NonNull OffloadServiceInfo offloadServiceInfo) {
1948 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1949 }
1950
1951 @Override
1952 public void onOffloadStop(@NonNull String interfaceName,
1953 @NonNull OffloadServiceInfo offloadServiceInfo) {
1954 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1955 }
1956
Paul Hud44e1b72023-06-16 02:07:42 +00001957 private ClientInfo getClientInfoOrLog(int transactionId) {
1958 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001959 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001960 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001961 }
1962 return clientInfo;
1963 }
1964
Paul Hud44e1b72023-06-16 02:07:42 +00001965 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1966 final int clientRequestId = info.getClientRequestId(transactionId);
1967 if (clientRequestId < 0) {
1968 Log.e(TAG, String.format(
1969 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001970 }
Paul Hud44e1b72023-06-16 02:07:42 +00001971 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001972 }
1973 }
1974
Paul Hu2e0a88c2023-03-09 16:05:01 +08001975 private static class ConnectorArgs {
1976 @NonNull public final NsdServiceConnector connector;
1977 @NonNull public final INsdManagerCallback callback;
1978 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001979 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001980
1981 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001982 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001983 this.connector = connector;
1984 this.callback = callback;
1985 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001986 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001987 }
1988 }
1989
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001990 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001991 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001993 final int uid = mDeps.getCallingUid();
1994 if (cb == null) {
1995 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1996 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001997 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001998 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001999 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002000 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002001 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002002 }
2003
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002004 private static class ListenerArgs {
2005 public final NsdServiceConnector connector;
2006 public final NsdServiceInfo serviceInfo;
2007 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2008 this.connector = connector;
2009 this.serviceInfo = serviceInfo;
2010 }
2011 }
2012
2013 private class NsdServiceConnector extends INsdServiceConnector.Stub
2014 implements IBinder.DeathRecipient {
2015 @Override
2016 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2017 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2018 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2019 new ListenerArgs(this, serviceInfo)));
2020 }
2021
2022 @Override
2023 public void unregisterService(int listenerKey) {
2024 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2025 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2026 new ListenerArgs(this, null)));
2027 }
2028
2029 @Override
2030 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2031 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2032 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2033 new ListenerArgs(this, serviceInfo)));
2034 }
2035
2036 @Override
2037 public void stopDiscovery(int listenerKey) {
2038 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2039 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2040 }
2041
2042 @Override
2043 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2044 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2045 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2046 new ListenerArgs(this, serviceInfo)));
2047 }
2048
2049 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002050 public void stopResolution(int listenerKey) {
2051 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2052 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2053 }
2054
2055 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002056 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2057 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2058 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2059 new ListenerArgs(this, serviceInfo)));
2060 }
2061
2062 @Override
2063 public void unregisterServiceInfoCallback(int listenerKey) {
2064 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2065 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2066 new ListenerArgs(this, null)));
2067 }
2068
2069 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002070 public void startDaemon() {
2071 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2072 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2073 }
2074
2075 @Override
2076 public void binderDied() {
2077 mNsdStateMachine.sendMessage(
2078 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002079
2080 }
2081
2082 @Override
2083 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2084 @OffloadEngine.OffloadCapability long offloadCapabilities,
2085 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002086 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002087 Objects.requireNonNull(ifaceName);
2088 Objects.requireNonNull(cb);
2089 mNsdStateMachine.sendMessage(
2090 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2091 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2092 offloadTypes)));
2093 }
2094
2095 @Override
2096 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002097 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002098 Objects.requireNonNull(cb);
2099 mNsdStateMachine.sendMessage(
2100 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002101 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002102
2103 private static void checkOffloadEnginePermission(Context context) {
2104 if (!SdkLevel.isAtLeastT()) {
2105 throw new SecurityException("API is not available in before API level 33");
2106 }
2107 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2108 // be back ported to older builds: accept it as long as it's signature-protected
2109 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2110 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2111 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2112 return;
2113 }
2114 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2115 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2116 return;
2117 }
2118 throw new SecurityException("Requires one of the following permissions: "
2119 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2120 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2121 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002122 }
2123
Hugo Benichi912db992017-04-24 16:41:03 +09002124 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002125 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002126 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002127 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2128 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002129 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002130 }
2131
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002132 private int getUniqueId() {
2133 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2134 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002135 }
2136
Paul Hud44e1b72023-06-16 02:07:42 +00002137 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002138 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002139 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002140 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002141 String name = service.getServiceName();
2142 String type = service.getServiceType();
2143 int port = service.getPort();
2144 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002145 final int registerInterface = getNetworkInterfaceIndex(service);
2146 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002147 Log.e(TAG, "Interface to register service on not found");
2148 return false;
2149 }
Paul Hud44e1b72023-06-16 02:07:42 +00002150 return mMDnsManager.registerService(
2151 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002152 }
2153
Paul Hud44e1b72023-06-16 02:07:42 +00002154 private boolean unregisterService(int transactionId) {
2155 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002156 }
2157
Paul Hud44e1b72023-06-16 02:07:42 +00002158 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002159 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002160 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2161 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002162 Log.e(TAG, "Interface to discover service on not found");
2163 return false;
2164 }
Paul Hud44e1b72023-06-16 02:07:42 +00002165 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002166 }
2167
Paul Hud44e1b72023-06-16 02:07:42 +00002168 private boolean stopServiceDiscovery(int transactionId) {
2169 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002170 }
2171
Paul Hud44e1b72023-06-16 02:07:42 +00002172 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002173 final String name = service.getServiceName();
2174 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002175 final int resolveInterface = getNetworkInterfaceIndex(service);
2176 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002177 Log.e(TAG, "Interface to resolve service on not found");
2178 return false;
2179 }
Paul Hud44e1b72023-06-16 02:07:42 +00002180 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002181 }
2182
2183 /**
2184 * Guess the interface to use to resolve or discover a service on a specific network.
2185 *
2186 * This is an imperfect guess, as for example the network may be gone or not yet fully
2187 * registered. This is fine as failing is correct if the network is gone, and a client
2188 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2189 * this is to support the legacy mdnsresponder implementation, which historically resolved
2190 * services on an unspecified network.
2191 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002192 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2193 final Network network = serviceInfo.getNetwork();
2194 if (network == null) {
2195 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2196 // provided by NsdService from discovery results, and the service was found on an
2197 // interface that has no app-usable Network).
2198 if (serviceInfo.getInterfaceIndex() != 0) {
2199 return serviceInfo.getInterfaceIndex();
2200 }
2201 return IFACE_IDX_ANY;
2202 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002203
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002204 String interfaceName = getNetworkInterfaceName(network);
2205 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002206 return IFACE_IDX_ANY;
2207 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002208 return getNetworkInterfaceIndexByName(interfaceName);
2209 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002210
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002211 private String getNetworkInterfaceName(@Nullable Network network) {
2212 if (network == null) {
2213 return null;
2214 }
2215 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2216 if (cm == null) {
2217 Log.wtf(TAG, "No ConnectivityManager");
2218 return null;
2219 }
2220 final LinkProperties lp = cm.getLinkProperties(network);
2221 if (lp == null) {
2222 return null;
2223 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002224 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002225 return lp.getInterfaceName();
2226 }
2227
2228 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002229 final NetworkInterface iface;
2230 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002231 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002232 } catch (SocketException e) {
2233 Log.e(TAG, "Error querying interface", e);
2234 return IFACE_IDX_ANY;
2235 }
2236
2237 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002238 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002239 return IFACE_IDX_ANY;
2240 }
2241
2242 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002243 }
2244
Paul Hud44e1b72023-06-16 02:07:42 +00002245 private boolean stopResolveService(int transactionId) {
2246 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002247 }
2248
Paul Hud44e1b72023-06-16 02:07:42 +00002249 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2250 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002251 }
2252
Paul Hud44e1b72023-06-16 02:07:42 +00002253 private boolean stopGetAddrInfo(int transactionId) {
2254 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002255 }
2256
2257 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002258 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2259 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002260
Paul Hub2e67d32023-04-18 05:50:14 +00002261 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2262 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002263 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002264
2265 // Dump service and clients logs
2266 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002267 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002268 pw.increaseIndent();
2269 mServiceLogs.reverseDump(pw);
2270 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002271 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002272
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002273 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002274 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002275 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002276 private int mFoundServiceCount = 0;
2277 private int mLostServiceCount = 0;
2278 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002279 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002280 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002281
Paul Hu812e9212023-06-20 06:24:53 +00002282 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002283 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002284 mStartTimeMs = startTimeMs;
2285 }
2286
Paul Hu812e9212023-06-20 06:24:53 +00002287 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002288 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002289 }
Paul Hu812e9212023-06-20 06:24:53 +00002290
2291 public void onServiceFound(String serviceName) {
2292 mFoundServiceCount++;
2293 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2294 mServices.add(serviceName);
2295 }
2296 }
2297
2298 public void onServiceLost() {
2299 mLostServiceCount++;
2300 }
2301
2302 public int getFoundServiceCount() {
2303 return mFoundServiceCount;
2304 }
2305
2306 public int getLostServiceCount() {
2307 return mLostServiceCount;
2308 }
2309
2310 public int getServicesCount() {
2311 return mServices.size();
2312 }
Paul Hua6bc4632023-06-26 01:18:29 +00002313
2314 public void setServiceFromCache(boolean isServiceFromCache) {
2315 mIsServiceFromCache = isServiceFromCache;
2316 }
2317
2318 public boolean isServiceFromCache() {
2319 return mIsServiceFromCache;
2320 }
Paul Hubad6fe92023-07-24 21:25:22 +08002321
2322 public void onQuerySent() {
2323 mSentQueryCount++;
2324 }
2325
2326 public int getSentQueryCount() {
2327 return mSentQueryCount;
2328 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002329 }
2330
2331 private static class LegacyClientRequest extends ClientRequest {
2332 private final int mRequestCode;
2333
Paul Hu812e9212023-06-20 06:24:53 +00002334 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2335 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002336 mRequestCode = requestCode;
2337 }
2338 }
2339
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002340 private abstract static class JavaBackendClientRequest extends ClientRequest {
2341 @Nullable
2342 private final Network mRequestedNetwork;
2343
Paul Hu777ed052023-06-19 13:35:15 +00002344 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002345 long startTimeMs) {
2346 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002347 mRequestedNetwork = requestedNetwork;
2348 }
2349
2350 @Nullable
2351 public Network getRequestedNetwork() {
2352 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002353 }
2354 }
2355
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002356 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002357 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002358 long startTimeMs) {
2359 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002360 }
2361 }
2362
2363 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002364 @NonNull
2365 private final MdnsListener mListener;
2366
Paul Hud44e1b72023-06-16 02:07:42 +00002367 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002368 @Nullable Network requestedNetwork, long startTimeMs) {
2369 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002370 mListener = listener;
2371 }
2372 }
2373
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002374 /* Information tracked per client */
2375 private class ClientInfo {
2376
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002377 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002378 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002379 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002380 private NsdServiceInfo mResolvedService;
2381
Paul Hud44e1b72023-06-16 02:07:42 +00002382 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002383 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002384
Luke Huangf7277ed2021-07-12 21:15:10 +08002385 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002386 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002387 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002388 // The flag of using java backend if the client's target SDK >= U
2389 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002390 // Store client logs
2391 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002392 // Report the nsd metrics data
2393 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002394
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002395 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002396 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002397 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002398 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002399 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002400 mClientLogs = sharedLog;
2401 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002402 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002403 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002404
2405 @Override
2406 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002407 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002408 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002409 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002410 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2411 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002412 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002413 int clientRequestId = mClientRequests.keyAt(i);
2414 sb.append("clientRequestId ")
2415 .append(clientRequestId)
2416 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002417 .append(" type ").append(
2418 mClientRequests.valueAt(i).getClass().getSimpleName())
2419 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002420 }
2421 return sb.toString();
2422 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002423
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002424 private boolean isPreSClient() {
2425 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002426 }
2427
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002428 private void setPreSClient() {
2429 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002430 }
2431
Paul Hu812e9212023-06-20 06:24:53 +00002432 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002433 final MdnsListener listener =
2434 ((DiscoveryManagerRequest) request).mListener;
2435 mMdnsDiscoveryManager.unregisterListener(
2436 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002437 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002438 }
2439
Dave Plattfeff2af2014-03-07 14:48:22 -08002440 // Remove any pending requests from the global map when we get rid of a client,
2441 // and send cancellations to the daemon.
2442 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002443 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002444 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002445 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002446 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002447 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002448 final int transactionId = request.mTransactionId;
2449 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002450 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002451 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2452 + " transactionId " + transactionId
2453 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002454 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002455
2456 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002457 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2458 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002459 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002460 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2461 request.getFoundServiceCount(),
2462 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002463 request.getServicesCount(),
2464 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002465 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002466 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002467 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002468 } else if (listener instanceof ServiceInfoListener) {
2469 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2470 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2471 request.getFoundServiceCount(),
2472 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002473 request.isServiceFromCache(),
2474 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002475 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002476 continue;
2477 }
2478
2479 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002480 final AdvertiserMetrics metrics =
2481 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002482 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002483 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002484 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2485 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2486 metrics.mConflictDuringProbingCount,
2487 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002488 continue;
2489 }
2490
2491 if (!(request instanceof LegacyClientRequest)) {
2492 throw new IllegalStateException("Unknown request type: " + request.getClass());
2493 }
2494
2495 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002496 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002497 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002498 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002499 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2500 request.getFoundServiceCount(),
2501 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002502 request.getServicesCount(),
2503 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002504 break;
2505 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002506 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002507 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002508 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002509 break;
2510 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002511 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002512 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002513 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2514 NO_PACKET /* repliedRequestsCount */,
2515 NO_PACKET /* sentPacketCount */,
2516 0 /* conflictDuringProbingCount */,
2517 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002518 break;
2519 default:
2520 break;
2521 }
2522 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002523 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002524 updateMulticastLock();
2525 }
2526
2527 /**
2528 * Returns true if this client has any Java backend request that requests one of the given
2529 * networks.
2530 */
2531 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2532 for (int i = 0; i < mClientRequests.size(); i++) {
2533 final ClientRequest req = mClientRequests.valueAt(i);
2534 if (!(req instanceof JavaBackendClientRequest)) {
2535 continue;
2536 }
2537 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2538 .getRequestedNetwork();
2539 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2540 return true;
2541 }
2542 }
2543 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002544 }
2545
Paul Hud44e1b72023-06-16 02:07:42 +00002546 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2547 // transaction id, return the corresponding client request id.
2548 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002549 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002550 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002551 return mClientRequests.keyAt(i);
2552 }
Christopher Lane74411222014-04-25 18:39:07 -07002553 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002554 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002555 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002556
Paul Hub2e67d32023-04-18 05:50:14 +00002557 private void log(String message) {
2558 mClientLogs.log(message);
2559 }
2560
Paul Hu508a0122023-09-11 15:31:33 +08002561 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2562 return !(request instanceof DiscoveryManagerRequest)
2563 && !(request instanceof AdvertiserClientRequest);
2564 }
2565
2566 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2567 ClientRequest request) {
2568 mMetrics.reportServiceDiscoveryStarted(
2569 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002570 try {
2571 mCb.onDiscoverServicesStarted(listenerKey, info);
2572 } catch (RemoteException e) {
2573 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2574 }
2575 }
Paul Hu508a0122023-09-11 15:31:33 +08002576 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2577 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2578 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002579 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002580
Paul Hu508a0122023-09-11 15:31:33 +08002581 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2582 int transactionId, long durationMs) {
2583 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002584 try {
2585 mCb.onDiscoverServicesFailed(listenerKey, error);
2586 } catch (RemoteException e) {
2587 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2588 }
2589 }
2590
Paul Hu812e9212023-06-20 06:24:53 +00002591 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2592 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002593 try {
2594 mCb.onServiceFound(listenerKey, info);
2595 } catch (RemoteException e) {
2596 Log.e(TAG, "Error calling onServiceFound(", e);
2597 }
2598 }
2599
Paul Hu812e9212023-06-20 06:24:53 +00002600 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2601 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002602 try {
2603 mCb.onServiceLost(listenerKey, info);
2604 } catch (RemoteException e) {
2605 Log.e(TAG, "Error calling onServiceLost(", e);
2606 }
2607 }
2608
2609 void onStopDiscoveryFailed(int listenerKey, int error) {
2610 try {
2611 mCb.onStopDiscoveryFailed(listenerKey, error);
2612 } catch (RemoteException e) {
2613 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2614 }
2615 }
2616
Paul Hu812e9212023-06-20 06:24:53 +00002617 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2618 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002619 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002620 request.mTransactionId,
2621 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2622 request.getFoundServiceCount(),
2623 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002624 request.getServicesCount(),
2625 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002626 try {
2627 mCb.onStopDiscoverySucceeded(listenerKey);
2628 } catch (RemoteException e) {
2629 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2630 }
2631 }
2632
Paul Hu508a0122023-09-11 15:31:33 +08002633 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2634 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2635 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002636 }
2637
Paul Hu508a0122023-09-11 15:31:33 +08002638 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2639 int transactionId, long durationMs) {
2640 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002641 try {
2642 mCb.onRegisterServiceFailed(listenerKey, error);
2643 } catch (RemoteException e) {
2644 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2645 }
2646 }
2647
Paul Hu508a0122023-09-11 15:31:33 +08002648 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2649 ClientRequest request) {
2650 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2651 request.mTransactionId,
2652 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002653 try {
2654 mCb.onRegisterServiceSucceeded(listenerKey, info);
2655 } catch (RemoteException e) {
2656 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2657 }
2658 }
2659
2660 void onUnregisterServiceFailed(int listenerKey, int error) {
2661 try {
2662 mCb.onUnregisterServiceFailed(listenerKey, error);
2663 } catch (RemoteException e) {
2664 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2665 }
2666 }
2667
Paul Hu508a0122023-09-11 15:31:33 +08002668 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002669 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002670 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2671 request.mTransactionId,
2672 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002673 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2674 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002675 try {
2676 mCb.onUnregisterServiceSucceeded(listenerKey);
2677 } catch (RemoteException e) {
2678 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2679 }
2680 }
2681
Paul Hu508a0122023-09-11 15:31:33 +08002682 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2683 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2684 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002685 }
2686
Paul Hu508a0122023-09-11 15:31:33 +08002687 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2688 int transactionId, long durationMs) {
2689 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002690 try {
2691 mCb.onResolveServiceFailed(listenerKey, error);
2692 } catch (RemoteException e) {
2693 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2694 }
2695 }
2696
Paul Hua6bc4632023-06-26 01:18:29 +00002697 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2698 ClientRequest request) {
2699 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002700 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002701 request.mTransactionId,
2702 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002703 request.isServiceFromCache(),
2704 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002705 try {
2706 mCb.onResolveServiceSucceeded(listenerKey, info);
2707 } catch (RemoteException e) {
2708 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2709 }
2710 }
Paul Hub58deb72022-12-26 09:24:42 +00002711
2712 void onStopResolutionFailed(int listenerKey, int error) {
2713 try {
2714 mCb.onStopResolutionFailed(listenerKey, error);
2715 } catch (RemoteException e) {
2716 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2717 }
2718 }
2719
Paul Hu60149052023-07-31 14:26:08 +08002720 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2721 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002722 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002723 request.mTransactionId,
2724 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002725 try {
2726 mCb.onStopResolutionSucceeded(listenerKey);
2727 } catch (RemoteException e) {
2728 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2729 }
2730 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002731
2732 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002733 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002734 try {
2735 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2736 } catch (RemoteException e) {
2737 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2738 }
2739 }
2740
Paul Huddce5912023-08-01 10:26:49 +08002741 void onServiceInfoCallbackRegistered(int transactionId) {
2742 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2743 }
2744
2745 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2746 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002747 try {
2748 mCb.onServiceUpdated(listenerKey, info);
2749 } catch (RemoteException e) {
2750 Log.e(TAG, "Error calling onServiceUpdated", e);
2751 }
2752 }
2753
Paul Huddce5912023-08-01 10:26:49 +08002754 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2755 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002756 try {
2757 mCb.onServiceUpdatedLost(listenerKey);
2758 } catch (RemoteException e) {
2759 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2760 }
2761 }
2762
Paul Huddce5912023-08-01 10:26:49 +08002763 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2764 mMetrics.reportServiceInfoCallbackUnregistered(
2765 request.mTransactionId,
2766 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2767 request.getFoundServiceCount(),
2768 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002769 request.isServiceFromCache(),
2770 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002771 try {
2772 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2773 } catch (RemoteException e) {
2774 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2775 }
2776 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002777 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002778}