blob: c74f229e4dc4faf4291562cc938d4b7de4a9bbfb [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))
1650 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001651 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001652 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1653 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001654 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001655 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001656 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1657 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001658 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001659 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001660 }
1661
1662 /**
1663 * Dependencies of NsdService, for injection in tests.
1664 */
1665 @VisibleForTesting
1666 public static class Dependencies {
1667 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001668 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001669 *
1670 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001671 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001672 */
1673 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001674 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001675 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001676 }
1677
1678 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001679 * Check whether the MdnsAdvertiser feature is enabled.
1680 *
1681 * @param context The global context information about an app environment.
1682 * @return true if the MdnsAdvertiser feature is enabled.
1683 */
1684 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001685 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001686 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001687 }
1688
1689 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001690 * Get the type allowlist flag value.
1691 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1692 */
1693 @Nullable
1694 public String getTypeAllowlistFlags() {
1695 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1696 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1697 }
1698
1699 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001700 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001701 */
1702 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001703 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001704 }
1705
1706 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001707 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1708 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001709 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1710 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001711 }
1712
1713 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001714 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1715 */
1716 public boolean isTrunkStableFeatureEnabled(String feature) {
1717 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1718 }
1719
1720 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001721 * @see MdnsDiscoveryManager
1722 */
1723 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001724 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001725 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1726 @NonNull MdnsFeatureFlags featureFlags) {
1727 return new MdnsDiscoveryManager(
1728 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001729 }
1730
1731 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001732 * @see MdnsAdvertiser
1733 */
1734 public MdnsAdvertiser makeMdnsAdvertiser(
1735 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001736 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1737 MdnsFeatureFlags featureFlags) {
1738 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001739 }
1740
1741 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001742 * @see MdnsSocketProvider
1743 */
Paul Hu14667de2023-04-17 22:42:47 +08001744 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001745 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1746 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1747 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1748 }
1749
1750 /**
1751 * @see DeviceConfig#getInt(String, String, int)
1752 */
1753 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1754 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1755 }
1756
1757 /**
1758 * @see Binder#getCallingUid()
1759 */
1760 public int getCallingUid() {
1761 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001762 }
Paul Hu777ed052023-06-19 13:35:15 +00001763
1764 /**
1765 * @see NetworkNsdReportedMetrics
1766 */
Paul Hu508a0122023-09-11 15:31:33 +08001767 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1768 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001769 }
1770
1771 /**
1772 * @see MdnsUtils.Clock
1773 */
1774 public Clock makeClock() {
1775 return new Clock();
1776 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001777 }
1778
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001779 /**
1780 * Return whether a type is allowlisted to use the Java backend.
1781 * @param type The service type
1782 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1783 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1784 */
1785 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1786 @NonNull String flagPrefix) {
1787 if (type == null) return false;
1788 final String typesConfig = mDeps.getTypeAllowlistFlags();
1789 if (TextUtils.isEmpty(typesConfig)) return false;
1790
1791 final String mappingPrefix = type + ":";
1792 String mappedFlag = null;
1793 for (String mapping : TextUtils.split(typesConfig, ",")) {
1794 if (mapping.startsWith(mappingPrefix)) {
1795 mappedFlag = mapping.substring(mappingPrefix.length());
1796 break;
1797 }
1798 }
1799
1800 if (mappedFlag == null) return false;
1801
1802 return mDeps.isFeatureEnabled(mContext,
1803 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1804 }
1805
1806 private boolean useDiscoveryManagerForType(@Nullable String type) {
1807 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1808 }
1809
1810 private boolean useAdvertiserForType(@Nullable String type) {
1811 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1812 }
1813
paulhu1b35e822022-04-08 14:48:41 +08001814 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001815 HandlerThread thread = new HandlerThread(TAG);
1816 thread.start();
1817 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001818 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001819 return service;
1820 }
1821
paulhu2b9ed952022-02-10 21:58:32 +08001822 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1823 private final StateMachine mStateMachine;
1824
1825 MDnsEventCallback(StateMachine sm) {
1826 mStateMachine = sm;
1827 }
1828
1829 @Override
1830 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1831 mStateMachine.sendMessage(
1832 MDNS_SERVICE_EVENT, status.result, status.id, status);
1833 }
1834
1835 @Override
1836 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1837 mStateMachine.sendMessage(
1838 MDNS_SERVICE_EVENT, status.result, status.id, status);
1839 }
1840
1841 @Override
1842 public void onServiceResolutionStatus(final ResolutionInfo status) {
1843 mStateMachine.sendMessage(
1844 MDNS_SERVICE_EVENT, status.result, status.id, status);
1845 }
1846
1847 @Override
1848 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1849 mStateMachine.sendMessage(
1850 MDNS_SERVICE_EVENT, status.result, status.id, status);
1851 }
1852
1853 @Override
1854 public int getInterfaceVersion() throws RemoteException {
1855 return this.VERSION;
1856 }
1857
1858 @Override
1859 public String getInterfaceHash() throws RemoteException {
1860 return this.HASH;
1861 }
1862 }
1863
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001864 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1865 final String targetInterface = offloadEngineInfo.mInterfaceName;
1866 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1867 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1868 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1869 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1870 try {
1871 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1872 } catch (RemoteException e) {
1873 // Can happen in regular cases, do not log a stacktrace
1874 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1875 }
1876 }
1877 }
1878
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001879 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1880 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1881 final int count = mOffloadEngines.beginBroadcast();
1882 try {
1883 for (int i = 0; i < count; i++) {
1884 final OffloadEngineInfo offloadEngineInfo =
1885 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1886 final String interfaceName = offloadEngineInfo.mInterfaceName;
1887 if (!targetInterfaceName.equals(interfaceName)
1888 || ((offloadEngineInfo.mOffloadType
1889 & offloadServiceInfo.getOffloadType()) == 0)) {
1890 continue;
1891 }
1892 try {
1893 if (isRemove) {
1894 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1895 offloadServiceInfo);
1896 } else {
1897 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1898 offloadServiceInfo);
1899 }
1900 } catch (RemoteException e) {
1901 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001902 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001903 }
1904 }
1905 } finally {
1906 mOffloadEngines.finishBroadcast();
1907 }
1908 }
1909
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001910 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001911 // TODO: add a callback to notify when a service is being added on each interface (as soon
1912 // as probing starts), and call mOffloadCallbacks. This callback is for
1913 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1914
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001915 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001916 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1917 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1918 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001919 if (clientInfo == null) return;
1920
Paul Hud44e1b72023-06-16 02:07:42 +00001921 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1922 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001923
1924 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1925 // historical behavior.
1926 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001927 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001928 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001929 }
1930
1931 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001932 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1933 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001934 if (clientInfo == null) return;
1935
Paul Hud44e1b72023-06-16 02:07:42 +00001936 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1937 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001938 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001939 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1940 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001941 }
1942
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001943 @Override
1944 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1945 @NonNull OffloadServiceInfo offloadServiceInfo) {
1946 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1947 }
1948
1949 @Override
1950 public void onOffloadStop(@NonNull String interfaceName,
1951 @NonNull OffloadServiceInfo offloadServiceInfo) {
1952 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1953 }
1954
Paul Hud44e1b72023-06-16 02:07:42 +00001955 private ClientInfo getClientInfoOrLog(int transactionId) {
1956 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001957 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001958 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001959 }
1960 return clientInfo;
1961 }
1962
Paul Hud44e1b72023-06-16 02:07:42 +00001963 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1964 final int clientRequestId = info.getClientRequestId(transactionId);
1965 if (clientRequestId < 0) {
1966 Log.e(TAG, String.format(
1967 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001968 }
Paul Hud44e1b72023-06-16 02:07:42 +00001969 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001970 }
1971 }
1972
Paul Hu2e0a88c2023-03-09 16:05:01 +08001973 private static class ConnectorArgs {
1974 @NonNull public final NsdServiceConnector connector;
1975 @NonNull public final INsdManagerCallback callback;
1976 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001977 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001978
1979 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001980 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001981 this.connector = connector;
1982 this.callback = callback;
1983 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001984 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001985 }
1986 }
1987
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001988 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001989 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001990 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001991 final int uid = mDeps.getCallingUid();
1992 if (cb == null) {
1993 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1994 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001995 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001996 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001997 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001998 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001999 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002000 }
2001
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002002 private static class ListenerArgs {
2003 public final NsdServiceConnector connector;
2004 public final NsdServiceInfo serviceInfo;
2005 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2006 this.connector = connector;
2007 this.serviceInfo = serviceInfo;
2008 }
2009 }
2010
2011 private class NsdServiceConnector extends INsdServiceConnector.Stub
2012 implements IBinder.DeathRecipient {
2013 @Override
2014 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2015 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2016 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2017 new ListenerArgs(this, serviceInfo)));
2018 }
2019
2020 @Override
2021 public void unregisterService(int listenerKey) {
2022 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2023 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2024 new ListenerArgs(this, null)));
2025 }
2026
2027 @Override
2028 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2029 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2030 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2031 new ListenerArgs(this, serviceInfo)));
2032 }
2033
2034 @Override
2035 public void stopDiscovery(int listenerKey) {
2036 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2037 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2038 }
2039
2040 @Override
2041 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2042 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2043 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2044 new ListenerArgs(this, serviceInfo)));
2045 }
2046
2047 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002048 public void stopResolution(int listenerKey) {
2049 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2050 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2051 }
2052
2053 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002054 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2055 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2056 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2057 new ListenerArgs(this, serviceInfo)));
2058 }
2059
2060 @Override
2061 public void unregisterServiceInfoCallback(int listenerKey) {
2062 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2063 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2064 new ListenerArgs(this, null)));
2065 }
2066
2067 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002068 public void startDaemon() {
2069 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2070 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2071 }
2072
2073 @Override
2074 public void binderDied() {
2075 mNsdStateMachine.sendMessage(
2076 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002077
2078 }
2079
2080 @Override
2081 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2082 @OffloadEngine.OffloadCapability long offloadCapabilities,
2083 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002084 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002085 Objects.requireNonNull(ifaceName);
2086 Objects.requireNonNull(cb);
2087 mNsdStateMachine.sendMessage(
2088 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2089 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2090 offloadTypes)));
2091 }
2092
2093 @Override
2094 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002095 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002096 Objects.requireNonNull(cb);
2097 mNsdStateMachine.sendMessage(
2098 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002099 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002100
2101 private static void checkOffloadEnginePermission(Context context) {
2102 if (!SdkLevel.isAtLeastT()) {
2103 throw new SecurityException("API is not available in before API level 33");
2104 }
2105 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2106 // be back ported to older builds: accept it as long as it's signature-protected
2107 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2108 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2109 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2110 return;
2111 }
2112 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2113 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2114 return;
2115 }
2116 throw new SecurityException("Requires one of the following permissions: "
2117 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2118 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2119 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002120 }
2121
Hugo Benichi912db992017-04-24 16:41:03 +09002122 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002123 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002124 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002125 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2126 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002127 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002128 }
2129
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002130 private int getUniqueId() {
2131 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2132 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002133 }
2134
Paul Hud44e1b72023-06-16 02:07:42 +00002135 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002136 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002137 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002138 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002139 String name = service.getServiceName();
2140 String type = service.getServiceType();
2141 int port = service.getPort();
2142 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002143 final int registerInterface = getNetworkInterfaceIndex(service);
2144 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002145 Log.e(TAG, "Interface to register service on not found");
2146 return false;
2147 }
Paul Hud44e1b72023-06-16 02:07:42 +00002148 return mMDnsManager.registerService(
2149 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002150 }
2151
Paul Hud44e1b72023-06-16 02:07:42 +00002152 private boolean unregisterService(int transactionId) {
2153 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002154 }
2155
Paul Hud44e1b72023-06-16 02:07:42 +00002156 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002157 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002158 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2159 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002160 Log.e(TAG, "Interface to discover service on not found");
2161 return false;
2162 }
Paul Hud44e1b72023-06-16 02:07:42 +00002163 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002164 }
2165
Paul Hud44e1b72023-06-16 02:07:42 +00002166 private boolean stopServiceDiscovery(int transactionId) {
2167 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002168 }
2169
Paul Hud44e1b72023-06-16 02:07:42 +00002170 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002171 final String name = service.getServiceName();
2172 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002173 final int resolveInterface = getNetworkInterfaceIndex(service);
2174 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002175 Log.e(TAG, "Interface to resolve service on not found");
2176 return false;
2177 }
Paul Hud44e1b72023-06-16 02:07:42 +00002178 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002179 }
2180
2181 /**
2182 * Guess the interface to use to resolve or discover a service on a specific network.
2183 *
2184 * This is an imperfect guess, as for example the network may be gone or not yet fully
2185 * registered. This is fine as failing is correct if the network is gone, and a client
2186 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2187 * this is to support the legacy mdnsresponder implementation, which historically resolved
2188 * services on an unspecified network.
2189 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002190 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2191 final Network network = serviceInfo.getNetwork();
2192 if (network == null) {
2193 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2194 // provided by NsdService from discovery results, and the service was found on an
2195 // interface that has no app-usable Network).
2196 if (serviceInfo.getInterfaceIndex() != 0) {
2197 return serviceInfo.getInterfaceIndex();
2198 }
2199 return IFACE_IDX_ANY;
2200 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002201
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002202 String interfaceName = getNetworkInterfaceName(network);
2203 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002204 return IFACE_IDX_ANY;
2205 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002206 return getNetworkInterfaceIndexByName(interfaceName);
2207 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002208
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002209 private String getNetworkInterfaceName(@Nullable Network network) {
2210 if (network == null) {
2211 return null;
2212 }
2213 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2214 if (cm == null) {
2215 Log.wtf(TAG, "No ConnectivityManager");
2216 return null;
2217 }
2218 final LinkProperties lp = cm.getLinkProperties(network);
2219 if (lp == null) {
2220 return null;
2221 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002222 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002223 return lp.getInterfaceName();
2224 }
2225
2226 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002227 final NetworkInterface iface;
2228 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002229 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002230 } catch (SocketException e) {
2231 Log.e(TAG, "Error querying interface", e);
2232 return IFACE_IDX_ANY;
2233 }
2234
2235 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002236 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002237 return IFACE_IDX_ANY;
2238 }
2239
2240 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002241 }
2242
Paul Hud44e1b72023-06-16 02:07:42 +00002243 private boolean stopResolveService(int transactionId) {
2244 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002245 }
2246
Paul Hud44e1b72023-06-16 02:07:42 +00002247 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2248 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002249 }
2250
Paul Hud44e1b72023-06-16 02:07:42 +00002251 private boolean stopGetAddrInfo(int transactionId) {
2252 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002253 }
2254
2255 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002256 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2257 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002258
Paul Hub2e67d32023-04-18 05:50:14 +00002259 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2260 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002261 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002262
2263 // Dump service and clients logs
2264 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002265 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002266 pw.increaseIndent();
2267 mServiceLogs.reverseDump(pw);
2268 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002269 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002270
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002271 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002272 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002273 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002274 private int mFoundServiceCount = 0;
2275 private int mLostServiceCount = 0;
2276 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002277 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002278 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002279
Paul Hu812e9212023-06-20 06:24:53 +00002280 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002281 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002282 mStartTimeMs = startTimeMs;
2283 }
2284
Paul Hu812e9212023-06-20 06:24:53 +00002285 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002286 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002287 }
Paul Hu812e9212023-06-20 06:24:53 +00002288
2289 public void onServiceFound(String serviceName) {
2290 mFoundServiceCount++;
2291 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2292 mServices.add(serviceName);
2293 }
2294 }
2295
2296 public void onServiceLost() {
2297 mLostServiceCount++;
2298 }
2299
2300 public int getFoundServiceCount() {
2301 return mFoundServiceCount;
2302 }
2303
2304 public int getLostServiceCount() {
2305 return mLostServiceCount;
2306 }
2307
2308 public int getServicesCount() {
2309 return mServices.size();
2310 }
Paul Hua6bc4632023-06-26 01:18:29 +00002311
2312 public void setServiceFromCache(boolean isServiceFromCache) {
2313 mIsServiceFromCache = isServiceFromCache;
2314 }
2315
2316 public boolean isServiceFromCache() {
2317 return mIsServiceFromCache;
2318 }
Paul Hubad6fe92023-07-24 21:25:22 +08002319
2320 public void onQuerySent() {
2321 mSentQueryCount++;
2322 }
2323
2324 public int getSentQueryCount() {
2325 return mSentQueryCount;
2326 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002327 }
2328
2329 private static class LegacyClientRequest extends ClientRequest {
2330 private final int mRequestCode;
2331
Paul Hu812e9212023-06-20 06:24:53 +00002332 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2333 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002334 mRequestCode = requestCode;
2335 }
2336 }
2337
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002338 private abstract static class JavaBackendClientRequest extends ClientRequest {
2339 @Nullable
2340 private final Network mRequestedNetwork;
2341
Paul Hu777ed052023-06-19 13:35:15 +00002342 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002343 long startTimeMs) {
2344 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002345 mRequestedNetwork = requestedNetwork;
2346 }
2347
2348 @Nullable
2349 public Network getRequestedNetwork() {
2350 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002351 }
2352 }
2353
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002354 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002355 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002356 long startTimeMs) {
2357 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002358 }
2359 }
2360
2361 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002362 @NonNull
2363 private final MdnsListener mListener;
2364
Paul Hud44e1b72023-06-16 02:07:42 +00002365 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002366 @Nullable Network requestedNetwork, long startTimeMs) {
2367 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002368 mListener = listener;
2369 }
2370 }
2371
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002372 /* Information tracked per client */
2373 private class ClientInfo {
2374
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002375 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002376 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002377 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002378 private NsdServiceInfo mResolvedService;
2379
Paul Hud44e1b72023-06-16 02:07:42 +00002380 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002381 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002382
Luke Huangf7277ed2021-07-12 21:15:10 +08002383 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002384 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002385 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002386 // The flag of using java backend if the client's target SDK >= U
2387 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002388 // Store client logs
2389 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002390 // Report the nsd metrics data
2391 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002392
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002393 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002394 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002395 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002396 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002397 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002398 mClientLogs = sharedLog;
2399 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002400 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002401 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002402
2403 @Override
2404 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002405 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002406 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002407 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002408 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2409 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002410 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002411 int clientRequestId = mClientRequests.keyAt(i);
2412 sb.append("clientRequestId ")
2413 .append(clientRequestId)
2414 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002415 .append(" type ").append(
2416 mClientRequests.valueAt(i).getClass().getSimpleName())
2417 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002418 }
2419 return sb.toString();
2420 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002421
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002422 private boolean isPreSClient() {
2423 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002424 }
2425
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002426 private void setPreSClient() {
2427 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002428 }
2429
Paul Hu812e9212023-06-20 06:24:53 +00002430 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002431 final MdnsListener listener =
2432 ((DiscoveryManagerRequest) request).mListener;
2433 mMdnsDiscoveryManager.unregisterListener(
2434 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002435 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002436 }
2437
Dave Plattfeff2af2014-03-07 14:48:22 -08002438 // Remove any pending requests from the global map when we get rid of a client,
2439 // and send cancellations to the daemon.
2440 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002441 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002442 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002443 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002444 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002445 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002446 final int transactionId = request.mTransactionId;
2447 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002448 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002449 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2450 + " transactionId " + transactionId
2451 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002452 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002453
2454 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002455 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2456 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002457 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002458 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2459 request.getFoundServiceCount(),
2460 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002461 request.getServicesCount(),
2462 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002463 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002464 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002465 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002466 } else if (listener instanceof ServiceInfoListener) {
2467 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2468 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2469 request.getFoundServiceCount(),
2470 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002471 request.isServiceFromCache(),
2472 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002473 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002474 continue;
2475 }
2476
2477 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002478 final AdvertiserMetrics metrics =
2479 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002480 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002481 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002482 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2483 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2484 metrics.mConflictDuringProbingCount,
2485 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002486 continue;
2487 }
2488
2489 if (!(request instanceof LegacyClientRequest)) {
2490 throw new IllegalStateException("Unknown request type: " + request.getClass());
2491 }
2492
2493 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002494 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002495 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002496 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002497 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2498 request.getFoundServiceCount(),
2499 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002500 request.getServicesCount(),
2501 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002502 break;
2503 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002504 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002505 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002506 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002507 break;
2508 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002509 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002510 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002511 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2512 NO_PACKET /* repliedRequestsCount */,
2513 NO_PACKET /* sentPacketCount */,
2514 0 /* conflictDuringProbingCount */,
2515 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002516 break;
2517 default:
2518 break;
2519 }
2520 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002521 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002522 updateMulticastLock();
2523 }
2524
2525 /**
2526 * Returns true if this client has any Java backend request that requests one of the given
2527 * networks.
2528 */
2529 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2530 for (int i = 0; i < mClientRequests.size(); i++) {
2531 final ClientRequest req = mClientRequests.valueAt(i);
2532 if (!(req instanceof JavaBackendClientRequest)) {
2533 continue;
2534 }
2535 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2536 .getRequestedNetwork();
2537 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2538 return true;
2539 }
2540 }
2541 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002542 }
2543
Paul Hud44e1b72023-06-16 02:07:42 +00002544 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2545 // transaction id, return the corresponding client request id.
2546 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002547 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002548 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002549 return mClientRequests.keyAt(i);
2550 }
Christopher Lane74411222014-04-25 18:39:07 -07002551 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002552 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002553 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002554
Paul Hub2e67d32023-04-18 05:50:14 +00002555 private void log(String message) {
2556 mClientLogs.log(message);
2557 }
2558
Paul Hu508a0122023-09-11 15:31:33 +08002559 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2560 return !(request instanceof DiscoveryManagerRequest)
2561 && !(request instanceof AdvertiserClientRequest);
2562 }
2563
2564 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2565 ClientRequest request) {
2566 mMetrics.reportServiceDiscoveryStarted(
2567 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002568 try {
2569 mCb.onDiscoverServicesStarted(listenerKey, info);
2570 } catch (RemoteException e) {
2571 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2572 }
2573 }
Paul Hu508a0122023-09-11 15:31:33 +08002574 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2575 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2576 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002577 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002578
Paul Hu508a0122023-09-11 15:31:33 +08002579 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2580 int transactionId, long durationMs) {
2581 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002582 try {
2583 mCb.onDiscoverServicesFailed(listenerKey, error);
2584 } catch (RemoteException e) {
2585 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2586 }
2587 }
2588
Paul Hu812e9212023-06-20 06:24:53 +00002589 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2590 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002591 try {
2592 mCb.onServiceFound(listenerKey, info);
2593 } catch (RemoteException e) {
2594 Log.e(TAG, "Error calling onServiceFound(", e);
2595 }
2596 }
2597
Paul Hu812e9212023-06-20 06:24:53 +00002598 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2599 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002600 try {
2601 mCb.onServiceLost(listenerKey, info);
2602 } catch (RemoteException e) {
2603 Log.e(TAG, "Error calling onServiceLost(", e);
2604 }
2605 }
2606
2607 void onStopDiscoveryFailed(int listenerKey, int error) {
2608 try {
2609 mCb.onStopDiscoveryFailed(listenerKey, error);
2610 } catch (RemoteException e) {
2611 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2612 }
2613 }
2614
Paul Hu812e9212023-06-20 06:24:53 +00002615 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2616 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002617 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002618 request.mTransactionId,
2619 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2620 request.getFoundServiceCount(),
2621 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002622 request.getServicesCount(),
2623 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002624 try {
2625 mCb.onStopDiscoverySucceeded(listenerKey);
2626 } catch (RemoteException e) {
2627 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2628 }
2629 }
2630
Paul Hu508a0122023-09-11 15:31:33 +08002631 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2632 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2633 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002634 }
2635
Paul Hu508a0122023-09-11 15:31:33 +08002636 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2637 int transactionId, long durationMs) {
2638 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002639 try {
2640 mCb.onRegisterServiceFailed(listenerKey, error);
2641 } catch (RemoteException e) {
2642 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2643 }
2644 }
2645
Paul Hu508a0122023-09-11 15:31:33 +08002646 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2647 ClientRequest request) {
2648 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2649 request.mTransactionId,
2650 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002651 try {
2652 mCb.onRegisterServiceSucceeded(listenerKey, info);
2653 } catch (RemoteException e) {
2654 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2655 }
2656 }
2657
2658 void onUnregisterServiceFailed(int listenerKey, int error) {
2659 try {
2660 mCb.onUnregisterServiceFailed(listenerKey, error);
2661 } catch (RemoteException e) {
2662 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2663 }
2664 }
2665
Paul Hu508a0122023-09-11 15:31:33 +08002666 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002667 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002668 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2669 request.mTransactionId,
2670 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002671 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2672 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002673 try {
2674 mCb.onUnregisterServiceSucceeded(listenerKey);
2675 } catch (RemoteException e) {
2676 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2677 }
2678 }
2679
Paul Hu508a0122023-09-11 15:31:33 +08002680 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2681 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2682 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002683 }
2684
Paul Hu508a0122023-09-11 15:31:33 +08002685 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2686 int transactionId, long durationMs) {
2687 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002688 try {
2689 mCb.onResolveServiceFailed(listenerKey, error);
2690 } catch (RemoteException e) {
2691 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2692 }
2693 }
2694
Paul Hua6bc4632023-06-26 01:18:29 +00002695 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2696 ClientRequest request) {
2697 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002698 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002699 request.mTransactionId,
2700 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002701 request.isServiceFromCache(),
2702 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002703 try {
2704 mCb.onResolveServiceSucceeded(listenerKey, info);
2705 } catch (RemoteException e) {
2706 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2707 }
2708 }
Paul Hub58deb72022-12-26 09:24:42 +00002709
2710 void onStopResolutionFailed(int listenerKey, int error) {
2711 try {
2712 mCb.onStopResolutionFailed(listenerKey, error);
2713 } catch (RemoteException e) {
2714 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2715 }
2716 }
2717
Paul Hu60149052023-07-31 14:26:08 +08002718 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2719 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002720 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002721 request.mTransactionId,
2722 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002723 try {
2724 mCb.onStopResolutionSucceeded(listenerKey);
2725 } catch (RemoteException e) {
2726 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2727 }
2728 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002729
2730 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002731 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002732 try {
2733 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2734 } catch (RemoteException e) {
2735 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2736 }
2737 }
2738
Paul Huddce5912023-08-01 10:26:49 +08002739 void onServiceInfoCallbackRegistered(int transactionId) {
2740 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2741 }
2742
2743 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2744 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002745 try {
2746 mCb.onServiceUpdated(listenerKey, info);
2747 } catch (RemoteException e) {
2748 Log.e(TAG, "Error calling onServiceUpdated", e);
2749 }
2750 }
2751
Paul Huddce5912023-08-01 10:26:49 +08002752 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2753 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002754 try {
2755 mCb.onServiceUpdatedLost(listenerKey);
2756 } catch (RemoteException e) {
2757 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2758 }
2759 }
2760
Paul Huddce5912023-08-01 10:26:49 +08002761 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2762 mMetrics.reportServiceInfoCallbackUnregistered(
2763 request.mTransactionId,
2764 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2765 request.getFoundServiceCount(),
2766 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002767 request.isServiceFromCache(),
2768 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002769 try {
2770 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2771 } catch (RemoteException e) {
2772 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2773 }
2774 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002775 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002776}