blob: 8cf6db7df7244f4d6bf7bad22aff3490a0959aac [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 Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090029import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090030
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090032import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080033import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
34import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090035import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000036import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090037
Paul Hu23fa2022023-01-13 22:57:24 +080038import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080039import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090040import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090041import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080042import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070043import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090045import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080046import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090047import android.net.LinkProperties;
48import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080049import android.net.mdns.aidl.DiscoveryInfo;
50import android.net.mdns.aidl.GetAddressInfo;
51import android.net.mdns.aidl.IMDnsEventListener;
52import android.net.mdns.aidl.RegistrationInfo;
53import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.net.nsd.INsdManagerCallback;
56import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090057import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080058import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080060import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090061import android.net.nsd.OffloadEngine;
62import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090063import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000064import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090065import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090066import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080067import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070070import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090071import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070073import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080075import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090076import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090077import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090078import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070079import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080083import com.android.internal.util.State;
84import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000085import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090086import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090087import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090089import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080090import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000091import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090093import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080094import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090095import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090096import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080097import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080098import com.android.server.connectivity.mdns.MdnsSearchOptions;
99import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
100import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800101import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900102import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800103
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700104import java.io.FileDescriptor;
105import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900106import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700107import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900108import java.net.NetworkInterface;
109import java.net.SocketException;
110import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800111import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900112import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700113import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800114import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800115import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900116import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000117import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800118import java.util.regex.Matcher;
119import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700120
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700121/**
122 * Network Service Discovery Service handles remote service discovery operation requests by
123 * implementing the INsdManager interface.
124 *
125 * @hide
126 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900127@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700128public class NsdService extends INsdManager.Stub {
129 private static final String TAG = "NsdService";
130 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900131 /**
132 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
133 * implementation.
134 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800135 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800136 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700137
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900138 /**
139 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
140 * implementation.
141 */
142 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
143
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900144 /**
145 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
146 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
147 *
148 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
149 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
150 *
151 * In which case the flags:
152 * "mdns_discovery_manager_allowlist_mytype_version",
153 * "mdns_advertiser_allowlist_mytype_version",
154 * "mdns_discovery_manager_allowlist_othertype_version",
155 * "mdns_advertiser_allowlist_othertype_version"
156 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
157 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900158 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900159 *
160 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
161 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
162 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
163 */
164 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
165
166 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
167 "mdns_discovery_manager_allowlist_";
168 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
169 "mdns_advertiser_allowlist_";
170 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
171
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900172 @VisibleForTesting
173 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
174 "mdns_config_running_app_active_importance_cutoff";
175 @VisibleForTesting
176 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
177 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
178 private final int mRunningAppActiveImportanceCutoff;
179
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900180 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000181 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900182 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000183 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
184 @VisibleForTesting
185 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800186 private static final int NO_SENT_QUERY_COUNT = 0;
187 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800188 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700189
Hugo Benichi32be63d2017-04-05 14:06:11 +0900190 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900191 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800192 private final MDnsManager mMDnsManager;
193 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900194 @NonNull
195 private final Dependencies mDeps;
196 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800197 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900198 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800199 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900200 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800201 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900202 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900203 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000204 @NonNull
205 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800206 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800207 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800208 // state machine thread. If change this outside state machine, it will need to introduce
209 // synchronization.
210 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800211 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700212
213 /**
214 * Clients receiving asynchronous messages
215 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900216 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700217
Paul Hud44e1b72023-06-16 02:07:42 +0000218 /* A map from transaction(unique) id to client info */
219 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700220
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900221 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
222 @Nullable
223 private WifiManager.MulticastLock mHeldMulticastLock;
224 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
225 // (non-null), value is the requested Network (nullable)
226 @NonNull
227 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
228 @NonNull
229 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
230
Luke Huang05298582021-06-13 16:52:05 +0000231 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700232
Hugo Benichi32be63d2017-04-05 14:06:11 +0900233 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700234 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800235 // The count of the connected legacy clients.
236 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000237 // The number of client that ever connected.
238 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700239
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900240 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
241 new RemoteCallbackList<>();
242
243 private static class OffloadEngineInfo {
244 @NonNull final String mInterfaceName;
245 final long mOffloadCapabilities;
246 final long mOffloadType;
247 @NonNull final IOffloadEngine mOffloadEngine;
248
249 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
250 @NonNull String interfaceName, long capabilities, long offloadType) {
251 this.mOffloadEngine = offloadEngine;
252 this.mInterfaceName = interfaceName;
253 this.mOffloadCapabilities = capabilities;
254 this.mOffloadType = offloadType;
255 }
256 }
257
Paul Hu812e9212023-06-20 06:24:53 +0000258 @VisibleForTesting
259 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000260 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800261 protected final int mTransactionId;
262 @NonNull
263 protected final NsdServiceInfo mReqServiceInfo;
264 @NonNull
265 protected final String mListenedServiceType;
266
Paul Hud44e1b72023-06-16 02:07:42 +0000267 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800268 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000269 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800270 mTransactionId = transactionId;
271 mReqServiceInfo = reqServiceInfo;
272 mListenedServiceType = listenedServiceType;
273 }
274
275 @NonNull
276 public String getListenedServiceType() {
277 return mListenedServiceType;
278 }
279
280 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000281 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
282 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800283
284 @Override
285 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
286
287 @Override
288 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
289
290 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000291 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
292 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800293
294 @Override
295 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
296
297 @Override
298 public void onSearchStoppedWithError(int error) { }
299
300 @Override
301 public void onSearchFailedToStart() { }
302
303 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800304 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
305 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800306
307 @Override
308 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
309 }
310
311 private class DiscoveryListener extends MdnsListener {
312
Paul Hud44e1b72023-06-16 02:07:42 +0000313 DiscoveryListener(int clientRequestId, int transactionId,
314 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
315 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800316 }
317
318 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000319 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
320 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800321 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
322 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000323 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800324 }
325
326 @Override
327 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800328 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
329 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000330 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800331 }
Paul Hubad6fe92023-07-24 21:25:22 +0800332
333 @Override
334 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
335 int sentQueryTransactionId) {
336 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
337 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
338 }
Paul Hu23fa2022023-01-13 22:57:24 +0800339 }
340
Paul Hu75069ed2023-01-14 00:31:09 +0800341 private class ResolutionListener extends MdnsListener {
342
Paul Hud44e1b72023-06-16 02:07:42 +0000343 ResolutionListener(int clientRequestId, int transactionId,
344 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
345 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800346 }
347
348 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000349 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800350 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
351 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000352 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800353 }
Paul Hubad6fe92023-07-24 21:25:22 +0800354
355 @Override
356 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
357 int sentQueryTransactionId) {
358 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
359 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
360 }
Paul Hu75069ed2023-01-14 00:31:09 +0800361 }
362
Paul Hu30bd70d2023-02-07 13:20:56 +0000363 private class ServiceInfoListener extends MdnsListener {
364
Paul Hud44e1b72023-06-16 02:07:42 +0000365 ServiceInfoListener(int clientRequestId, int transactionId,
366 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
367 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000368 }
369
370 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000371 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
372 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000373 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
374 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000375 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000376 }
377
378 @Override
379 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
380 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
381 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000382 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
384
385 @Override
386 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
387 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
388 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000389 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000390 }
Paul Hubad6fe92023-07-24 21:25:22 +0800391
392 @Override
393 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
394 int sentQueryTransactionId) {
395 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
396 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
397 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000398 }
399
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900400 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
401 @Override
402 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
403 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
404 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
405 // filtering on such interfaces, so taking the multicast lock is not necessary to
406 // disable APF filtering of multicast.
407 if (socketNetwork == null
408 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
409 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
410 return;
411 }
412
413 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
414 updateMulticastLock();
415 }
416 }
417
418 @Override
419 public void onSocketDestroyed(@Nullable Network socketNetwork,
420 @NonNull MdnsInterfaceSocket socket) {
421 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
422 updateMulticastLock();
423 }
424 }
425 }
426
427 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
428 private final Handler mHandler;
429
430 private UidImportanceListener(Handler handler) {
431 mHandler = handler;
432 }
433
434 @Override
435 public void onUidImportance(int uid, int importance) {
436 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
437 }
438 }
439
440 private void handleUidImportanceChanged(int uid, int importance) {
441 // Lower importance values are more "important"
442 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
443 ? mRunningAppActiveUids.add(uid)
444 : mRunningAppActiveUids.remove(uid);
445 if (modified) {
446 updateMulticastLock();
447 }
448 }
449
450 /**
451 * Take or release the lock based on updated internal state.
452 *
453 * This determines whether the lock needs to be held based on
454 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
455 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
456 * updated.
457 */
458 private void updateMulticastLock() {
459 final int needsLockUid = getMulticastLockNeededUid();
460 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
461 final WifiManager wm = mContext.getSystemService(WifiManager.class);
462 if (wm == null) {
463 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
464 return;
465 }
466 mHeldMulticastLock = wm.createMulticastLock(TAG);
467 mHeldMulticastLock.acquire();
468 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
469 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
470 mHeldMulticastLock.release();
471 mHeldMulticastLock = null;
472 mServiceLogs.log("Released multicast lock");
473 }
474 }
475
476 /**
477 * @return The UID of an app requiring the multicast lock, or -1 if none.
478 */
479 private int getMulticastLockNeededUid() {
480 if (mWifiLockRequiredNetworks.size() == 0) {
481 // Return early if NSD is not active, or not on any relevant network
482 return -1;
483 }
Paul Hud44e1b72023-06-16 02:07:42 +0000484 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
485 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900486 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
487 // Ignore non-active UIDs
488 continue;
489 }
490
491 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
492 return clientInfo.mUid;
493 }
494 }
495 return -1;
496 }
497
Paul Hu019621e2023-01-13 23:26:49 +0800498 /**
499 * Data class of mdns service callback information.
500 */
501 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000502 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800503 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800504 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000505 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800506
Paul Hubad6fe92023-07-24 21:25:22 +0800507 MdnsEvent(int clientRequestId) {
508 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
509 }
510
511 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000512 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
513 }
514
Paul Hubad6fe92023-07-24 21:25:22 +0800515 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000516 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000517 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800518 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000519 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800520 }
521 }
522
Paul Hu77c11182023-10-23 16:17:32 +0800523 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700524 private class NsdStateMachine extends StateMachine {
525
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700526 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700527
528 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700529 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900530 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700531 }
532
Luke Huang92860f92021-06-23 06:29:30 +0000533 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800534 if (mIsDaemonStarted) {
535 if (DBG) Log.d(TAG, "Daemon is already started.");
536 return;
537 }
538 mMDnsManager.registerEventListener(mMDnsEventCallback);
539 mMDnsManager.startDaemon();
540 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000541 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000542 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000543 }
544
paulhu2b9ed952022-02-10 21:58:32 +0800545 private void maybeStopDaemon() {
546 if (!mIsDaemonStarted) {
547 if (DBG) Log.d(TAG, "Daemon has not been started.");
548 return;
549 }
550 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
551 mMDnsManager.stopDaemon();
552 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000553 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800554 }
555
Luke Huang92860f92021-06-23 06:29:30 +0000556 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000557 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000558 }
559
560 private void scheduleStop() {
561 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
562 }
563 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800564 // The native daemon should stay alive and can't be cleanup
565 // if any legacy client connected.
566 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000567 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000568 }
569 }
570
Luke Huang92860f92021-06-23 06:29:30 +0000571 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000572 this.removeMessages(NsdManager.DAEMON_CLEANUP);
573 }
574
Paul Hu23fa2022023-01-13 22:57:24 +0800575 private void maybeStartMonitoringSockets() {
576 if (mIsMonitoringSocketsStarted) {
577 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
578 return;
579 }
580
581 mMdnsSocketProvider.startMonitoringSockets();
582 mIsMonitoringSocketsStarted = true;
583 }
584
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900585 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
586 if (!mIsMonitoringSocketsStarted) return;
587 if (isAnyRequestActive()) return;
588
Paul Hu58f20602023-02-18 11:41:07 +0800589 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800590 mIsMonitoringSocketsStarted = false;
591 }
592
Hugo Benichi803a2f02017-04-24 11:35:06 +0900593 NsdStateMachine(String name, Handler handler) {
594 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800595 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800596 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900597 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700598 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700599 }
600
Irfan Sheriff75006652012-04-17 23:15:29 -0700601 class EnabledState extends State {
602 @Override
603 public void enter() {
604 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 }
606
607 @Override
608 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000609 // TODO: it is incorrect to stop the daemon without expunging all requests
610 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000611 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700612 }
613
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700614 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900615 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800616 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617 return true;
618 }
619 return false;
620 }
621
Paul Hu508a0122023-09-11 15:31:33 +0800622 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000623 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800624 final LegacyClientRequest request =
625 new LegacyClientRequest(transactionId, what, startTimeMs);
626 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000627 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000628 // Remove the cleanup event because here comes a new request.
629 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800630 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700631 }
632
Paul Hud44e1b72023-06-16 02:07:42 +0000633 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900634 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000635 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000636 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000637 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900638 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800639 }
640
Paul Hud44e1b72023-06-16 02:07:42 +0000641 private void removeRequestMap(
642 int clientRequestId, int transactionId, ClientInfo clientInfo) {
643 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900644 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000645 clientInfo.mClientRequests.remove(clientRequestId);
646 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900647
648 if (existing instanceof LegacyClientRequest) {
649 maybeScheduleStop();
650 } else {
651 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900652 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900653 }
654 }
655
Paul Hu508a0122023-09-11 15:31:33 +0800656 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
657 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900658 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800659 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
660 listener, requestedNetwork, mClock.elapsedRealtime());
661 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000662 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900663 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800664 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800665 }
666
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900667 /**
668 * Truncate a service name to up to 63 UTF-8 bytes.
669 *
670 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
671 * names used in registerService follows historical behavior (see mdnsresponder
672 * handle_regservice_request).
673 */
674 @NonNull
675 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900676 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800677 }
678
Paul Hud44e1b72023-06-16 02:07:42 +0000679 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
680 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800681 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000682 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800683 }
684
Paul Hu77c11182023-10-23 16:17:32 +0800685 private ClientInfo getClientInfoForReply(Message msg) {
686 final ListenerArgs args = (ListenerArgs) msg.obj;
687 return mClients.get(args.connector);
688 }
689
Irfan Sheriff75006652012-04-17 23:15:29 -0700690 @Override
691 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900692 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000693 final int transactionId;
694 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900695 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900696 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700697 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800698 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800699 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900700 args = (ListenerArgs) msg.obj;
701 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000702 // If the binder death notification for a INsdManagerCallback was received
703 // before any calls are received by NsdService, the clientInfo would be
704 // cleared and cause NPE. Add a null check here to prevent this corner case.
705 if (clientInfo == null) {
706 Log.e(TAG, "Unknown connector in discovery");
707 break;
708 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700709
710 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800711 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
712 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700713 break;
714 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700715
Paul Hu23fa2022023-01-13 22:57:24 +0800716 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000717 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900718 final Pair<String, String> typeAndSubtype =
719 parseTypeAndSubtype(info.getServiceType());
720 final String serviceType = typeAndSubtype == null
721 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800722 if (clientInfo.mUseJavaBackend
723 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900724 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800725 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800726 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
727 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800728 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700729 }
Paul Hu23fa2022023-01-13 22:57:24 +0800730
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900731 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800732 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000733 final MdnsListener listener = new DiscoveryListener(clientRequestId,
734 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900735 final MdnsSearchOptions.Builder optionsBuilder =
736 MdnsSearchOptions.newBuilder()
737 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900738 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900739 .setIsPassiveMode(true);
740 if (typeAndSubtype.second != null) {
741 // The parsing ensures subtype starts with an underscore.
742 // MdnsSearchOptions expects the underscore to not be present.
743 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
744 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900745 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900746 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800747 final ClientRequest request = storeDiscoveryManagerRequestMap(
748 clientRequestId, transactionId, listener, clientInfo,
749 info.getNetwork());
750 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000751 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000752 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700753 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800754 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000755 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800756 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000757 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800758 + info.getServiceType());
759 }
Paul Hu508a0122023-09-11 15:31:33 +0800760 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
761 transactionId, clientInfo, msg.what,
762 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000763 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800764 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800765 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000766 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800767 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
768 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800769 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700770 }
771 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800772 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900773 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800774 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900775 args = (ListenerArgs) msg.obj;
776 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000777 // If the binder death notification for a INsdManagerCallback was received
778 // before any calls are received by NsdService, the clientInfo would be
779 // cleared and cause NPE. Add a null check here to prevent this corner case.
780 if (clientInfo == null) {
781 Log.e(TAG, "Unknown connector in stop discovery");
782 break;
783 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700784
Paul Hud44e1b72023-06-16 02:07:42 +0000785 final ClientRequest request =
786 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900787 if (request == null) {
788 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700789 break;
790 }
Paul Hud44e1b72023-06-16 02:07:42 +0000791 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900792 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
793 // point, so this needs to check the type of the original request to
794 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900795 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000796 stopDiscoveryManagerRequest(
797 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000798 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000799 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700800 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000801 removeRequestMap(clientRequestId, transactionId, clientInfo);
802 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000803 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800804 } else {
805 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000806 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800807 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700808 }
809 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900810 }
811 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800812 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900813 args = (ListenerArgs) msg.obj;
814 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000815 // If the binder death notification for a INsdManagerCallback was received
816 // before any calls are received by NsdService, the clientInfo would be
817 // cleared and cause NPE. Add a null check here to prevent this corner case.
818 if (clientInfo == null) {
819 Log.e(TAG, "Unknown connector in registration");
820 break;
821 }
822
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700823 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800824 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
825 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700826 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700827 }
828
Paul Hud44e1b72023-06-16 02:07:42 +0000829 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900830 final NsdServiceInfo serviceInfo = args.serviceInfo;
831 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900832 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
833 final String registerServiceType = typeSubtype == null
834 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800835 if (clientInfo.mUseJavaBackend
836 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900837 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900838 if (registerServiceType == null) {
839 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800840 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
841 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900842 break;
843 }
844 serviceInfo.setServiceType(registerServiceType);
845 serviceInfo.setServiceName(truncateServiceName(
846 serviceInfo.getServiceName()));
847
848 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900849 // TODO: pass in the subtype as well. Including the subtype in the
850 // service type would generate service instance names like
851 // Name._subtype._sub._type._tcp, which is incorrect
852 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000853 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
854 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900855 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700856 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900857 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000858 if (registerService(transactionId, serviceInfo)) {
859 if (DBG) {
860 Log.d(TAG, "Register " + clientRequestId
861 + " " + transactionId);
862 }
Paul Hua6bc4632023-06-26 01:18:29 +0000863 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
864 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900865 // Return success after mDns reports success
866 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000867 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800868 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
869 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900870 }
871
Irfan Sheriff75006652012-04-17 23:15:29 -0700872 }
873 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900874 }
875 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800876 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900877 args = (ListenerArgs) msg.obj;
878 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000879 // If the binder death notification for a INsdManagerCallback was received
880 // before any calls are received by NsdService, the clientInfo would be
881 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900882 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800883 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700884 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700885 }
Paul Hud44e1b72023-06-16 02:07:42 +0000886 final ClientRequest request =
887 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900888 if (request == null) {
889 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
890 break;
891 }
Paul Hud44e1b72023-06-16 02:07:42 +0000892 transactionId = request.mTransactionId;
893 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900894
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900895 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
896 // so this needs to check the type of the original request to unregister
897 // instead of looking at the flag value.
898 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800899 final AdvertiserMetrics metrics =
900 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000901 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800902 clientInfo.onUnregisterServiceSucceeded(
903 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700904 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000905 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800906 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800907 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
908 NO_PACKET /* sentPacketCount */,
909 0 /* conflictDuringProbingCount */,
910 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900911 } else {
912 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000913 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900914 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700915 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700916 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900917 }
Paul Hu75069ed2023-01-14 00:31:09 +0800918 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800919 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900920 args = (ListenerArgs) msg.obj;
921 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000922 // If the binder death notification for a INsdManagerCallback was received
923 // before any calls are received by NsdService, the clientInfo would be
924 // cleared and cause NPE. Add a null check here to prevent this corner case.
925 if (clientInfo == null) {
926 Log.e(TAG, "Unknown connector in resolution");
927 break;
928 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700929
Paul Hu75069ed2023-01-14 00:31:09 +0800930 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000931 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900932 final Pair<String, String> typeSubtype =
933 parseTypeAndSubtype(info.getServiceType());
934 final String serviceType = typeSubtype == null
935 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800936 if (clientInfo.mUseJavaBackend
937 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900938 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800939 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800940 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
941 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800942 break;
943 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900944 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800945
946 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000947 final MdnsListener listener = new ResolutionListener(clientRequestId,
948 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800949 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
950 .setNetwork(info.getNetwork())
951 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900952 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900953 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800954 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900955 mMdnsDiscoveryManager.registerListener(
956 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000957 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
958 listener, clientInfo, info.getNetwork());
959 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000960 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700961 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800962 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800963 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
964 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800965 break;
966 }
967
968 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000969 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800970 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +0000971 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
972 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +0800973 } else {
Paul Hu508a0122023-09-11 15:31:33 +0800974 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
975 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800976 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700977 }
978 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800979 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900980 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000981 if (DBG) Log.d(TAG, "Stop service resolution");
982 args = (ListenerArgs) msg.obj;
983 clientInfo = mClients.get(args.connector);
984 // If the binder death notification for a INsdManagerCallback was received
985 // before any calls are received by NsdService, the clientInfo would be
986 // cleared and cause NPE. Add a null check here to prevent this corner case.
987 if (clientInfo == null) {
988 Log.e(TAG, "Unknown connector in stop resolution");
989 break;
990 }
991
Paul Hud44e1b72023-06-16 02:07:42 +0000992 final ClientRequest request =
993 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900994 if (request == null) {
995 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
996 break;
997 }
Paul Hud44e1b72023-06-16 02:07:42 +0000998 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +0800999 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1000 // point, so this needs to check the type of the original request to
1001 // unregister instead of looking at the flag value.
1002 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001003 stopDiscoveryManagerRequest(
1004 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001005 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001006 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001007 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001008 removeRequestMap(clientRequestId, transactionId, clientInfo);
1009 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001010 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001011 } else {
1012 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001013 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001014 }
1015 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001016 }
Paul Hub58deb72022-12-26 09:24:42 +00001017 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001018 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001019 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001020 if (DBG) Log.d(TAG, "Register a service callback");
1021 args = (ListenerArgs) msg.obj;
1022 clientInfo = mClients.get(args.connector);
1023 // If the binder death notification for a INsdManagerCallback was received
1024 // before any calls are received by NsdService, the clientInfo would be
1025 // cleared and cause NPE. Add a null check here to prevent this corner case.
1026 if (clientInfo == null) {
1027 Log.e(TAG, "Unknown connector in callback registration");
1028 break;
1029 }
1030
Paul Hu30bd70d2023-02-07 13:20:56 +00001031 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001032 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001033 final Pair<String, String> typeAndSubtype =
1034 parseTypeAndSubtype(info.getServiceType());
1035 final String serviceType = typeAndSubtype == null
1036 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001037 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001038 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001039 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001040 break;
1041 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001042 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001043
Paul Hu30bd70d2023-02-07 13:20:56 +00001044 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001045 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1046 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001047 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1048 .setNetwork(info.getNetwork())
1049 .setIsPassiveMode(true)
1050 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001051 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001052 .build();
1053 mMdnsDiscoveryManager.registerListener(
1054 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001055 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1056 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001057 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001058 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001059 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001060 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001061 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001062 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001063 if (DBG) Log.d(TAG, "Unregister a service callback");
1064 args = (ListenerArgs) msg.obj;
1065 clientInfo = mClients.get(args.connector);
1066 // If the binder death notification for a INsdManagerCallback was received
1067 // before any calls are received by NsdService, the clientInfo would be
1068 // cleared and cause NPE. Add a null check here to prevent this corner case.
1069 if (clientInfo == null) {
1070 Log.e(TAG, "Unknown connector in callback unregistration");
1071 break;
1072 }
1073
Paul Hud44e1b72023-06-16 02:07:42 +00001074 final ClientRequest request =
1075 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001076 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001077 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001078 break;
1079 }
Paul Hud44e1b72023-06-16 02:07:42 +00001080 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001081 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001082 stopDiscoveryManagerRequest(
1083 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001084 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001085 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001086 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001087 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001088 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001089 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001090 }
paulhu2b9ed952022-02-10 21:58:32 +08001091 case MDNS_SERVICE_EVENT:
1092 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001093 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001094 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001095 break;
Paul Hu019621e2023-01-13 23:26:49 +08001096 case MDNS_DISCOVERY_MANAGER_EVENT:
1097 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1098 return NOT_HANDLED;
1099 }
1100 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001101 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1102 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1103 // TODO: Limits the number of registrations created by a given class.
1104 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1105 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001106 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001107 break;
1108 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1109 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1110 break;
Paul Hu77c11182023-10-23 16:17:32 +08001111 case NsdManager.REGISTER_CLIENT:
1112 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1113 final INsdManagerCallback cb = arg.callback;
1114 try {
1115 cb.asBinder().linkToDeath(arg.connector, 0);
1116 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1117 final NetworkNsdReportedMetrics metrics =
1118 mDeps.makeNetworkNsdReportedMetrics(
1119 (int) mClock.elapsedRealtime());
1120 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1121 mServiceLogs.forSubComponent(tag), metrics);
1122 mClients.put(arg.connector, clientInfo);
1123 } catch (RemoteException e) {
1124 Log.w(TAG, "Client request id " + clientRequestId
1125 + " has already died");
1126 }
1127 break;
1128 case NsdManager.UNREGISTER_CLIENT:
1129 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1130 clientInfo = mClients.remove(connector);
1131 if (clientInfo != null) {
1132 clientInfo.expungeAllRequests();
1133 if (clientInfo.isPreSClient()) {
1134 mLegacyClientCount -= 1;
1135 }
1136 }
1137 maybeStopMonitoringSocketsIfNoActiveRequest();
1138 maybeScheduleStop();
1139 break;
1140 case NsdManager.DAEMON_CLEANUP:
1141 maybeStopDaemon();
1142 break;
1143 // This event should be only sent by the legacy (target SDK < S) clients.
1144 // Mark the sending client as legacy.
1145 case NsdManager.DAEMON_STARTUP:
1146 clientInfo = getClientInfoForReply(msg);
1147 if (clientInfo != null) {
1148 cancelStop();
1149 clientInfo.setPreSClient();
1150 mLegacyClientCount += 1;
1151 maybeStartDaemon();
1152 }
1153 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001154 default:
Paul Hu77c11182023-10-23 16:17:32 +08001155 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001156 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001157 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001158 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001159 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001160
Paul Hud44e1b72023-06-16 02:07:42 +00001161 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001162 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001163 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001164 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001165 Log.e(TAG, String.format(
1166 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001167 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001168 }
1169
1170 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001171 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1172 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001173 // This can happen because of race conditions. For example,
1174 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1175 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001176 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1177 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001178 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001179 }
Paul Hu812e9212023-06-20 06:24:53 +00001180 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1181 if (request == null) {
1182 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1183 return false;
1184 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001185 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001186 Log.d(TAG, String.format(
1187 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001188 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001189 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001190 case IMDnsEventListener.SERVICE_FOUND: {
1191 final DiscoveryInfo info = (DiscoveryInfo) obj;
1192 final String name = info.serviceName;
1193 final String type = info.registrationType;
1194 servInfo = new NsdServiceInfo(name, type);
1195 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001196 if (foundNetId == 0L) {
1197 // Ignore services that do not have a Network: they are not usable
1198 // by apps, as they would need privileged permissions to use
1199 // interfaces that do not have an associated Network.
1200 break;
1201 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001202 if (foundNetId == INetd.DUMMY_NET_ID) {
1203 // Ignore services on the dummy0 interface: they are only seen when
1204 // discovering locally advertised services, and are not reachable
1205 // through that interface.
1206 break;
1207 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001208 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001209
1210 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001211 break;
paulhu2b9ed952022-02-10 21:58:32 +08001212 }
1213 case IMDnsEventListener.SERVICE_LOST: {
1214 final DiscoveryInfo info = (DiscoveryInfo) obj;
1215 final String name = info.serviceName;
1216 final String type = info.registrationType;
1217 final int lostNetId = info.netId;
1218 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001219 // The network could be set to null (netId 0) if it was torn down when the
1220 // service is lost
1221 // TODO: avoid returning null in that case, possibly by remembering
1222 // found services on the same interface index and their network at the time
1223 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001224 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001225 break;
paulhu2b9ed952022-02-10 21:58:32 +08001226 }
1227 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001228 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001229 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1230 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001231 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001232 break;
paulhu2b9ed952022-02-10 21:58:32 +08001233 case IMDnsEventListener.SERVICE_REGISTERED: {
1234 final RegistrationInfo info = (RegistrationInfo) obj;
1235 final String name = info.serviceName;
1236 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001237 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001238 break;
paulhu2b9ed952022-02-10 21:58:32 +08001239 }
1240 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001241 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001242 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1243 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001244 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001245 break;
paulhu2b9ed952022-02-10 21:58:32 +08001246 case IMDnsEventListener.SERVICE_RESOLVED: {
1247 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001248 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001249 final String fullName = info.serviceFullName;
1250 while (index < fullName.length() && fullName.charAt(index) != '.') {
1251 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001252 ++index;
1253 }
1254 ++index;
1255 }
paulhu2b9ed952022-02-10 21:58:32 +08001256 if (index >= fullName.length()) {
1257 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001258 break;
1259 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001260
paulhube186602022-04-12 07:18:23 +00001261 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001262 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001263 String type = rest.replace(".local.", "");
1264
Paul Hu30bd70d2023-02-07 13:20:56 +00001265 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001266 serviceInfo.setServiceName(name);
1267 serviceInfo.setServiceType(type);
1268 serviceInfo.setPort(info.port);
1269 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001270 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001271
Paul Hud44e1b72023-06-16 02:07:42 +00001272 stopResolveService(transactionId);
1273 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001274
Paul Hud44e1b72023-06-16 02:07:42 +00001275 final int transactionId2 = getUniqueId();
1276 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1277 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001278 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001279 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001280 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001281 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1282 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001283 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001284 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001285 }
1286 break;
paulhu2b9ed952022-02-10 21:58:32 +08001287 }
1288 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001289 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001290 stopResolveService(transactionId);
1291 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001292 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001293 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1294 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001295 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001296 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001297 break;
paulhu2b9ed952022-02-10 21:58:32 +08001298 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001299 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001300 stopGetAddrInfo(transactionId);
1301 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001302 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001303 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1304 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001305 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001306 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001307 break;
paulhu2b9ed952022-02-10 21:58:32 +08001308 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001309 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001310 final GetAddressInfo info = (GetAddressInfo) obj;
1311 final String address = info.address;
1312 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001313 InetAddress serviceHost = null;
1314 try {
paulhu2b9ed952022-02-10 21:58:32 +08001315 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001316 } catch (UnknownHostException e) {
1317 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1318 }
1319
1320 // If the resolved service is on an interface without a network, consider it
1321 // as a failure: it would not be usable by apps as they would need
1322 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001323 if (netId != NETID_UNSET && serviceHost != null) {
1324 clientInfo.mResolvedService.setHost(serviceHost);
1325 setServiceNetworkForCallback(clientInfo.mResolvedService,
1326 netId, info.interfaceIdx);
1327 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001328 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001329 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001330 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001331 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1332 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001333 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001334 }
Paul Hud44e1b72023-06-16 02:07:42 +00001335 stopGetAddrInfo(transactionId);
1336 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001337 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001338 break;
paulhu2b9ed952022-02-10 21:58:32 +08001339 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001340 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001341 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001342 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001343 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001344 }
Paul Hu019621e2023-01-13 23:26:49 +08001345
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001346 @Nullable
1347 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1348 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001349 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001350 final String[] typeArray = serviceInfo.getServiceType();
1351 final String joinedType;
1352 if (typeArray.length == 0
1353 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1354 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1355 + Arrays.toString(typeArray));
1356 return null;
1357 } else {
1358 joinedType = TextUtils.join(".",
1359 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1360 }
1361 final String serviceType;
1362 switch (code) {
1363 case NsdManager.SERVICE_FOUND:
1364 case NsdManager.SERVICE_LOST:
1365 // For consistency with historical behavior, discovered service types have
1366 // a dot at the end.
1367 serviceType = joinedType + ".";
1368 break;
1369 case RESOLVE_SERVICE_SUCCEEDED:
1370 // For consistency with historical behavior, resolved service types have
1371 // a dot at the beginning.
1372 serviceType = "." + joinedType;
1373 break;
1374 default:
1375 serviceType = joinedType;
1376 break;
1377 }
Paul Hu019621e2023-01-13 23:26:49 +08001378 final String serviceName = serviceInfo.getServiceInstanceName();
1379 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1380 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001381 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1382 // network for Tethering interface. In other words, the network == null means the
1383 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001384 setServiceNetworkForCallback(
1385 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001386 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001387 serviceInfo.getInterfaceIndex());
1388 return servInfo;
1389 }
1390
1391 private boolean handleMdnsDiscoveryManagerEvent(
1392 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001393 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001394 if (clientInfo == null) {
1395 Log.e(TAG, String.format(
1396 "id %d for %d has no client mapping", transactionId, code));
1397 return false;
1398 }
1399
1400 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001401 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001402 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1403 if (request == null) {
1404 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1405 return false;
1406 }
1407
1408 // Deal with the discovery sent callback
1409 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1410 request.onQuerySent();
1411 return true;
1412 }
1413
1414 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001415 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1416 // Errors are already logged if null
1417 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001418 mServiceLogs.log(String.format(
1419 "MdnsDiscoveryManager event code=%s transactionId=%d",
1420 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001421 switch (code) {
1422 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001423 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001424 break;
1425 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001426 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001427 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001428 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1429 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001430 info.setPort(serviceInfo.getPort());
1431
1432 Map<String, String> attrs = serviceInfo.getAttributes();
1433 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1434 final String key = kv.getKey();
1435 try {
1436 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1437 } catch (IllegalArgumentException e) {
1438 Log.e(TAG, "Invalid attribute", e);
1439 }
1440 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001441 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001442 if (addresses.size() != 0) {
1443 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001444 request.setServiceFromCache(event.mIsServiceFromCache);
1445 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001446 } else {
1447 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001448 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001449 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1450 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001451 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001452 }
1453
1454 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001455 if (!(request instanceof DiscoveryManagerRequest)) {
1456 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1457 break;
1458 }
Paul Hud44e1b72023-06-16 02:07:42 +00001459 stopDiscoveryManagerRequest(
1460 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001461 break;
1462 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001463 case NsdManager.SERVICE_UPDATED: {
1464 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1465 info.setPort(serviceInfo.getPort());
1466
1467 Map<String, String> attrs = serviceInfo.getAttributes();
1468 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1469 final String key = kv.getKey();
1470 try {
1471 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1472 } catch (IllegalArgumentException e) {
1473 Log.e(TAG, "Invalid attribute", e);
1474 }
1475 }
1476
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001477 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001478 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001479 clientInfo.onServiceUpdated(clientRequestId, info, request);
1480 // Set the ServiceFromCache flag only if the service is actually being
1481 // retrieved from the cache. This flag should not be overridden by later
1482 // service updates, which may not be cached.
1483 if (event.mIsServiceFromCache) {
1484 request.setServiceFromCache(true);
1485 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001486 break;
1487 }
1488 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001489 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001490 break;
Paul Hu019621e2023-01-13 23:26:49 +08001491 default:
1492 return false;
1493 }
1494 return true;
1495 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001496 }
1497 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001498
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001499 @NonNull
1500 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1501 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1502 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1503 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1504 for (String ipv4Address : v4Addrs) {
1505 try {
1506 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1507 } catch (IllegalArgumentException e) {
1508 Log.wtf(TAG, "Invalid ipv4 address", e);
1509 }
1510 }
1511 for (String ipv6Address : v6Addrs) {
1512 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001513 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1514 ipv6Address);
1515 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1516 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001517 Log.wtf(TAG, "Invalid ipv6 address", e);
1518 }
1519 }
1520 return addresses;
1521 }
1522
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001523 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1524 switch (netId) {
1525 case NETID_UNSET:
1526 info.setNetwork(null);
1527 break;
1528 case INetd.LOCAL_NET_ID:
1529 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1530 // visible / usable for apps, so do not return it. Store the interface
1531 // index instead, so at least if the client tries to resolve the service
1532 // with that NsdServiceInfo, it will be done on the same interface.
1533 // If they recreate the NsdServiceInfo themselves, resolution would be
1534 // done on all interfaces as before T, which should also work.
1535 info.setNetwork(null);
1536 info.setInterfaceIndex(ifaceIdx);
1537 break;
1538 default:
1539 info.setNetwork(new Network(netId));
1540 }
1541 }
1542
paulhube186602022-04-12 07:18:23 +00001543 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1544 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1545 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1546 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1547 private String unescape(String s) {
1548 StringBuilder sb = new StringBuilder(s.length());
1549 for (int i = 0; i < s.length(); ++i) {
1550 char c = s.charAt(i);
1551 if (c == '\\') {
1552 if (++i >= s.length()) {
1553 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1554 break;
1555 }
1556 c = s.charAt(i);
1557 if (c != '.' && c != '\\') {
1558 if (i + 2 >= s.length()) {
1559 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1560 break;
1561 }
1562 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1563 + (s.charAt(i + 2) - '0'));
1564 i += 2;
1565 }
1566 }
1567 sb.append(c);
1568 }
1569 return sb.toString();
1570 }
1571
Paul Hu7445e3d2023-03-03 15:14:00 +08001572 /**
1573 * Check the given service type is valid and construct it to a service type
1574 * which can use for discovery / resolution service.
1575 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001576 * <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 +08001577 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1578 * underscore; they are alphanumerical characters or dashes or underscore, except the
1579 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1580 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001581 * <p>The subtype may also be specified with a comma after the service type, for example
1582 * _type._tcp,_subtype.
1583 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001584 * @param serviceType the request service type for discovery / resolution service
1585 * @return constructed service type or null if the given service type is invalid.
1586 */
1587 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001588 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001589 if (TextUtils.isEmpty(serviceType)) return null;
1590
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001591 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001592 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001593 // Optional leading subtype (_subtype._type._tcp)
1594 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1595 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1596 // Actual type (_type._tcp.local)
1597 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001598 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001599 // e.g. allow "_type._tcp.local."
1600 + "\\.?"
1601 // Optional subtype after comma, for "_type._tcp,_subtype" format
1602 + "(?:,(" + typeOrSubtypePattern + "))?"
1603 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001604 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1605 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001606 // Use the subtype either at the beginning or after the comma
1607 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1608 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001609 }
1610
Hugo Benichi803a2f02017-04-24 11:35:06 +09001611 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001612 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001613 this(ctx, handler, cleanupDelayMs, new Dependencies());
1614 }
1615
1616 @VisibleForTesting
1617 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001618 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001619 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001620 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001621 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001622 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1623 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001624 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001625
Paul Hu14667de2023-04-17 22:42:47 +08001626 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001627 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001628 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001629 // address events are received. When the netlink monitor starts, any IP addresses already
1630 // on the interfaces will not be seen. In practice, the network will not connect at boot
1631 // time As a result, all the netlink message should be observed if the netlink monitor
1632 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001633 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001634
1635 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1636 // startBootstrapServices).
1637 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1638 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1639 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1640 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1641 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1642 mRunningAppActiveImportanceCutoff);
1643
Paul Huf3fe3332023-10-16 17:13:25 +08001644 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1645 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1646 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1647 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1648 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001649 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1650 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001651 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1652 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001653 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001654 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001655 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001656 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001657 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001658 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001659 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1660 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001661 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001662 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001663 }
1664
1665 /**
1666 * Dependencies of NsdService, for injection in tests.
1667 */
1668 @VisibleForTesting
1669 public static class Dependencies {
1670 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001671 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001672 *
1673 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001674 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001675 */
1676 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001677 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001678 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001679 }
1680
1681 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001682 * Check whether the MdnsAdvertiser feature is enabled.
1683 *
1684 * @param context The global context information about an app environment.
1685 * @return true if the MdnsAdvertiser feature is enabled.
1686 */
1687 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001688 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001689 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001690 }
1691
1692 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001693 * Get the type allowlist flag value.
1694 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1695 */
1696 @Nullable
1697 public String getTypeAllowlistFlags() {
1698 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1699 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1700 }
1701
1702 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001703 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001704 */
1705 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001706 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001707 }
1708
1709 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001710 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1711 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001712 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1713 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001714 }
1715
1716 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001717 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1718 */
1719 public boolean isTrunkStableFeatureEnabled(String feature) {
1720 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1721 }
1722
1723 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001724 * @see MdnsDiscoveryManager
1725 */
1726 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001727 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001728 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1729 @NonNull MdnsFeatureFlags featureFlags) {
1730 return new MdnsDiscoveryManager(
1731 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001732 }
1733
1734 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001735 * @see MdnsAdvertiser
1736 */
1737 public MdnsAdvertiser makeMdnsAdvertiser(
1738 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001739 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1740 MdnsFeatureFlags featureFlags) {
1741 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001742 }
1743
1744 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001745 * @see MdnsSocketProvider
1746 */
Paul Hu14667de2023-04-17 22:42:47 +08001747 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001748 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1749 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1750 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1751 }
1752
1753 /**
1754 * @see DeviceConfig#getInt(String, String, int)
1755 */
1756 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1757 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1758 }
1759
1760 /**
1761 * @see Binder#getCallingUid()
1762 */
1763 public int getCallingUid() {
1764 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001765 }
Paul Hu777ed052023-06-19 13:35:15 +00001766
1767 /**
1768 * @see NetworkNsdReportedMetrics
1769 */
Paul Hu508a0122023-09-11 15:31:33 +08001770 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1771 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001772 }
1773
1774 /**
1775 * @see MdnsUtils.Clock
1776 */
1777 public Clock makeClock() {
1778 return new Clock();
1779 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001780 }
1781
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001782 /**
1783 * Return whether a type is allowlisted to use the Java backend.
1784 * @param type The service type
1785 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1786 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1787 */
1788 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1789 @NonNull String flagPrefix) {
1790 if (type == null) return false;
1791 final String typesConfig = mDeps.getTypeAllowlistFlags();
1792 if (TextUtils.isEmpty(typesConfig)) return false;
1793
1794 final String mappingPrefix = type + ":";
1795 String mappedFlag = null;
1796 for (String mapping : TextUtils.split(typesConfig, ",")) {
1797 if (mapping.startsWith(mappingPrefix)) {
1798 mappedFlag = mapping.substring(mappingPrefix.length());
1799 break;
1800 }
1801 }
1802
1803 if (mappedFlag == null) return false;
1804
1805 return mDeps.isFeatureEnabled(mContext,
1806 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1807 }
1808
1809 private boolean useDiscoveryManagerForType(@Nullable String type) {
1810 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1811 }
1812
1813 private boolean useAdvertiserForType(@Nullable String type) {
1814 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1815 }
1816
paulhu1b35e822022-04-08 14:48:41 +08001817 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001818 HandlerThread thread = new HandlerThread(TAG);
1819 thread.start();
1820 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001821 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001822 return service;
1823 }
1824
paulhu2b9ed952022-02-10 21:58:32 +08001825 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1826 private final StateMachine mStateMachine;
1827
1828 MDnsEventCallback(StateMachine sm) {
1829 mStateMachine = sm;
1830 }
1831
1832 @Override
1833 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1834 mStateMachine.sendMessage(
1835 MDNS_SERVICE_EVENT, status.result, status.id, status);
1836 }
1837
1838 @Override
1839 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1840 mStateMachine.sendMessage(
1841 MDNS_SERVICE_EVENT, status.result, status.id, status);
1842 }
1843
1844 @Override
1845 public void onServiceResolutionStatus(final ResolutionInfo status) {
1846 mStateMachine.sendMessage(
1847 MDNS_SERVICE_EVENT, status.result, status.id, status);
1848 }
1849
1850 @Override
1851 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1852 mStateMachine.sendMessage(
1853 MDNS_SERVICE_EVENT, status.result, status.id, status);
1854 }
1855
1856 @Override
1857 public int getInterfaceVersion() throws RemoteException {
1858 return this.VERSION;
1859 }
1860
1861 @Override
1862 public String getInterfaceHash() throws RemoteException {
1863 return this.HASH;
1864 }
1865 }
1866
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001867 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1868 final String targetInterface = offloadEngineInfo.mInterfaceName;
1869 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1870 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1871 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1872 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1873 try {
1874 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1875 } catch (RemoteException e) {
1876 // Can happen in regular cases, do not log a stacktrace
1877 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1878 }
1879 }
1880 }
1881
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001882 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1883 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1884 final int count = mOffloadEngines.beginBroadcast();
1885 try {
1886 for (int i = 0; i < count; i++) {
1887 final OffloadEngineInfo offloadEngineInfo =
1888 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1889 final String interfaceName = offloadEngineInfo.mInterfaceName;
1890 if (!targetInterfaceName.equals(interfaceName)
1891 || ((offloadEngineInfo.mOffloadType
1892 & offloadServiceInfo.getOffloadType()) == 0)) {
1893 continue;
1894 }
1895 try {
1896 if (isRemove) {
1897 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1898 offloadServiceInfo);
1899 } else {
1900 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1901 offloadServiceInfo);
1902 }
1903 } catch (RemoteException e) {
1904 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001905 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001906 }
1907 }
1908 } finally {
1909 mOffloadEngines.finishBroadcast();
1910 }
1911 }
1912
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001913 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001914 // TODO: add a callback to notify when a service is being added on each interface (as soon
1915 // as probing starts), and call mOffloadCallbacks. This callback is for
1916 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1917
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001918 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001919 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1920 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1921 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001922 if (clientInfo == null) return;
1923
Paul Hud44e1b72023-06-16 02:07:42 +00001924 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1925 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001926
1927 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1928 // historical behavior.
1929 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001930 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001931 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001932 }
1933
1934 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001935 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1936 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001937 if (clientInfo == null) return;
1938
Paul Hud44e1b72023-06-16 02:07:42 +00001939 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1940 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001941 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001942 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1943 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001944 }
1945
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001946 @Override
1947 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1948 @NonNull OffloadServiceInfo offloadServiceInfo) {
1949 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1950 }
1951
1952 @Override
1953 public void onOffloadStop(@NonNull String interfaceName,
1954 @NonNull OffloadServiceInfo offloadServiceInfo) {
1955 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1956 }
1957
Paul Hud44e1b72023-06-16 02:07:42 +00001958 private ClientInfo getClientInfoOrLog(int transactionId) {
1959 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001960 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001961 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001962 }
1963 return clientInfo;
1964 }
1965
Paul Hud44e1b72023-06-16 02:07:42 +00001966 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1967 final int clientRequestId = info.getClientRequestId(transactionId);
1968 if (clientRequestId < 0) {
1969 Log.e(TAG, String.format(
1970 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001971 }
Paul Hud44e1b72023-06-16 02:07:42 +00001972 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001973 }
1974 }
1975
Paul Hu2e0a88c2023-03-09 16:05:01 +08001976 private static class ConnectorArgs {
1977 @NonNull public final NsdServiceConnector connector;
1978 @NonNull public final INsdManagerCallback callback;
1979 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001980 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001981
1982 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001983 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001984 this.connector = connector;
1985 this.callback = callback;
1986 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001987 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001988 }
1989 }
1990
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001991 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001992 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001993 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001994 final int uid = mDeps.getCallingUid();
1995 if (cb == null) {
1996 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1997 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001998 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001999 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002000 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002001 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002002 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002003 }
2004
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002005 private static class ListenerArgs {
2006 public final NsdServiceConnector connector;
2007 public final NsdServiceInfo serviceInfo;
2008 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2009 this.connector = connector;
2010 this.serviceInfo = serviceInfo;
2011 }
2012 }
2013
2014 private class NsdServiceConnector extends INsdServiceConnector.Stub
2015 implements IBinder.DeathRecipient {
2016 @Override
2017 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2018 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2019 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2020 new ListenerArgs(this, serviceInfo)));
2021 }
2022
2023 @Override
2024 public void unregisterService(int listenerKey) {
2025 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2026 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2027 new ListenerArgs(this, null)));
2028 }
2029
2030 @Override
2031 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2032 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2033 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2034 new ListenerArgs(this, serviceInfo)));
2035 }
2036
2037 @Override
2038 public void stopDiscovery(int listenerKey) {
2039 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2040 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2041 }
2042
2043 @Override
2044 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2045 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2046 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2047 new ListenerArgs(this, serviceInfo)));
2048 }
2049
2050 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002051 public void stopResolution(int listenerKey) {
2052 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2053 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2054 }
2055
2056 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002057 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2058 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2059 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2060 new ListenerArgs(this, serviceInfo)));
2061 }
2062
2063 @Override
2064 public void unregisterServiceInfoCallback(int listenerKey) {
2065 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2066 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2067 new ListenerArgs(this, null)));
2068 }
2069
2070 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002071 public void startDaemon() {
2072 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2073 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2074 }
2075
2076 @Override
2077 public void binderDied() {
2078 mNsdStateMachine.sendMessage(
2079 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002080
2081 }
2082
2083 @Override
2084 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2085 @OffloadEngine.OffloadCapability long offloadCapabilities,
2086 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002087 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002088 Objects.requireNonNull(ifaceName);
2089 Objects.requireNonNull(cb);
2090 mNsdStateMachine.sendMessage(
2091 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2092 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2093 offloadTypes)));
2094 }
2095
2096 @Override
2097 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002098 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002099 Objects.requireNonNull(cb);
2100 mNsdStateMachine.sendMessage(
2101 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002102 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002103
2104 private static void checkOffloadEnginePermission(Context context) {
2105 if (!SdkLevel.isAtLeastT()) {
2106 throw new SecurityException("API is not available in before API level 33");
2107 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002108
2109 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2110 if (SdkLevel.isAtLeastV() && PermissionUtils.checkAnyPermissionOf(context,
2111 REGISTER_NSD_OFFLOAD_ENGINE)) {
2112 return;
2113 }
2114
2115 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2116 // permission instead.
2117 if (!SdkLevel.isAtLeastV() && SdkLevel.isAtLeastU()
2118 && PermissionUtils.checkAnyPermissionOf(context, DEVICE_POWER)) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002119 return;
2120 }
2121 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2122 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2123 return;
2124 }
2125 throw new SecurityException("Requires one of the following permissions: "
2126 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2127 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2128 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002129 }
2130
Hugo Benichi912db992017-04-24 16:41:03 +09002131 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002132 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002133 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002134 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2135 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002136 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002137 }
2138
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002139 private int getUniqueId() {
2140 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2141 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002142 }
2143
Paul Hud44e1b72023-06-16 02:07:42 +00002144 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002145 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002146 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002147 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002148 String name = service.getServiceName();
2149 String type = service.getServiceType();
2150 int port = service.getPort();
2151 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002152 final int registerInterface = getNetworkInterfaceIndex(service);
2153 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002154 Log.e(TAG, "Interface to register service on not found");
2155 return false;
2156 }
Paul Hud44e1b72023-06-16 02:07:42 +00002157 return mMDnsManager.registerService(
2158 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002159 }
2160
Paul Hud44e1b72023-06-16 02:07:42 +00002161 private boolean unregisterService(int transactionId) {
2162 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002163 }
2164
Paul Hud44e1b72023-06-16 02:07:42 +00002165 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002166 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002167 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2168 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002169 Log.e(TAG, "Interface to discover service on not found");
2170 return false;
2171 }
Paul Hud44e1b72023-06-16 02:07:42 +00002172 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002173 }
2174
Paul Hud44e1b72023-06-16 02:07:42 +00002175 private boolean stopServiceDiscovery(int transactionId) {
2176 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002177 }
2178
Paul Hud44e1b72023-06-16 02:07:42 +00002179 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002180 final String name = service.getServiceName();
2181 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002182 final int resolveInterface = getNetworkInterfaceIndex(service);
2183 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002184 Log.e(TAG, "Interface to resolve service on not found");
2185 return false;
2186 }
Paul Hud44e1b72023-06-16 02:07:42 +00002187 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002188 }
2189
2190 /**
2191 * Guess the interface to use to resolve or discover a service on a specific network.
2192 *
2193 * This is an imperfect guess, as for example the network may be gone or not yet fully
2194 * registered. This is fine as failing is correct if the network is gone, and a client
2195 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2196 * this is to support the legacy mdnsresponder implementation, which historically resolved
2197 * services on an unspecified network.
2198 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002199 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2200 final Network network = serviceInfo.getNetwork();
2201 if (network == null) {
2202 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2203 // provided by NsdService from discovery results, and the service was found on an
2204 // interface that has no app-usable Network).
2205 if (serviceInfo.getInterfaceIndex() != 0) {
2206 return serviceInfo.getInterfaceIndex();
2207 }
2208 return IFACE_IDX_ANY;
2209 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002210
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002211 String interfaceName = getNetworkInterfaceName(network);
2212 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002213 return IFACE_IDX_ANY;
2214 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002215 return getNetworkInterfaceIndexByName(interfaceName);
2216 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002217
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002218 private String getNetworkInterfaceName(@Nullable Network network) {
2219 if (network == null) {
2220 return null;
2221 }
2222 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2223 if (cm == null) {
2224 Log.wtf(TAG, "No ConnectivityManager");
2225 return null;
2226 }
2227 final LinkProperties lp = cm.getLinkProperties(network);
2228 if (lp == null) {
2229 return null;
2230 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002231 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002232 return lp.getInterfaceName();
2233 }
2234
2235 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002236 final NetworkInterface iface;
2237 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002238 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002239 } catch (SocketException e) {
2240 Log.e(TAG, "Error querying interface", e);
2241 return IFACE_IDX_ANY;
2242 }
2243
2244 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002245 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002246 return IFACE_IDX_ANY;
2247 }
2248
2249 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002250 }
2251
Paul Hud44e1b72023-06-16 02:07:42 +00002252 private boolean stopResolveService(int transactionId) {
2253 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002254 }
2255
Paul Hud44e1b72023-06-16 02:07:42 +00002256 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2257 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002258 }
2259
Paul Hud44e1b72023-06-16 02:07:42 +00002260 private boolean stopGetAddrInfo(int transactionId) {
2261 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002262 }
2263
2264 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002265 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2266 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002267
Paul Hub2e67d32023-04-18 05:50:14 +00002268 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2269 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002270 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002271
2272 // Dump service and clients logs
2273 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002274 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002275 pw.increaseIndent();
2276 mServiceLogs.reverseDump(pw);
2277 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002278 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002279
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002280 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002281 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002282 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002283 private int mFoundServiceCount = 0;
2284 private int mLostServiceCount = 0;
2285 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002286 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002287 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002288
Paul Hu812e9212023-06-20 06:24:53 +00002289 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002290 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002291 mStartTimeMs = startTimeMs;
2292 }
2293
Paul Hu812e9212023-06-20 06:24:53 +00002294 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002295 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002296 }
Paul Hu812e9212023-06-20 06:24:53 +00002297
2298 public void onServiceFound(String serviceName) {
2299 mFoundServiceCount++;
2300 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2301 mServices.add(serviceName);
2302 }
2303 }
2304
2305 public void onServiceLost() {
2306 mLostServiceCount++;
2307 }
2308
2309 public int getFoundServiceCount() {
2310 return mFoundServiceCount;
2311 }
2312
2313 public int getLostServiceCount() {
2314 return mLostServiceCount;
2315 }
2316
2317 public int getServicesCount() {
2318 return mServices.size();
2319 }
Paul Hua6bc4632023-06-26 01:18:29 +00002320
2321 public void setServiceFromCache(boolean isServiceFromCache) {
2322 mIsServiceFromCache = isServiceFromCache;
2323 }
2324
2325 public boolean isServiceFromCache() {
2326 return mIsServiceFromCache;
2327 }
Paul Hubad6fe92023-07-24 21:25:22 +08002328
2329 public void onQuerySent() {
2330 mSentQueryCount++;
2331 }
2332
2333 public int getSentQueryCount() {
2334 return mSentQueryCount;
2335 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002336 }
2337
2338 private static class LegacyClientRequest extends ClientRequest {
2339 private final int mRequestCode;
2340
Paul Hu812e9212023-06-20 06:24:53 +00002341 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2342 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002343 mRequestCode = requestCode;
2344 }
2345 }
2346
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002347 private abstract static class JavaBackendClientRequest extends ClientRequest {
2348 @Nullable
2349 private final Network mRequestedNetwork;
2350
Paul Hu777ed052023-06-19 13:35:15 +00002351 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002352 long startTimeMs) {
2353 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002354 mRequestedNetwork = requestedNetwork;
2355 }
2356
2357 @Nullable
2358 public Network getRequestedNetwork() {
2359 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002360 }
2361 }
2362
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002363 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002364 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002365 long startTimeMs) {
2366 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002367 }
2368 }
2369
2370 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002371 @NonNull
2372 private final MdnsListener mListener;
2373
Paul Hud44e1b72023-06-16 02:07:42 +00002374 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002375 @Nullable Network requestedNetwork, long startTimeMs) {
2376 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002377 mListener = listener;
2378 }
2379 }
2380
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002381 /* Information tracked per client */
2382 private class ClientInfo {
2383
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002384 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002385 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002386 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002387 private NsdServiceInfo mResolvedService;
2388
Paul Hud44e1b72023-06-16 02:07:42 +00002389 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002390 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002391
Luke Huangf7277ed2021-07-12 21:15:10 +08002392 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002393 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002394 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002395 // The flag of using java backend if the client's target SDK >= U
2396 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002397 // Store client logs
2398 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002399 // Report the nsd metrics data
2400 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002401
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002402 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002403 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002404 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002405 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002406 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002407 mClientLogs = sharedLog;
2408 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002409 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002410 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002411
2412 @Override
2413 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002414 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002415 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002416 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002417 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2418 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002419 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002420 int clientRequestId = mClientRequests.keyAt(i);
2421 sb.append("clientRequestId ")
2422 .append(clientRequestId)
2423 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002424 .append(" type ").append(
2425 mClientRequests.valueAt(i).getClass().getSimpleName())
2426 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002427 }
2428 return sb.toString();
2429 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002430
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002431 private boolean isPreSClient() {
2432 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002433 }
2434
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002435 private void setPreSClient() {
2436 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002437 }
2438
Paul Hu812e9212023-06-20 06:24:53 +00002439 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002440 final MdnsListener listener =
2441 ((DiscoveryManagerRequest) request).mListener;
2442 mMdnsDiscoveryManager.unregisterListener(
2443 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002444 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002445 }
2446
Dave Plattfeff2af2014-03-07 14:48:22 -08002447 // Remove any pending requests from the global map when we get rid of a client,
2448 // and send cancellations to the daemon.
2449 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002450 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002451 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002452 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002453 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002454 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002455 final int transactionId = request.mTransactionId;
2456 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002457 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002458 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2459 + " transactionId " + transactionId
2460 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002461 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002462
2463 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002464 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2465 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002466 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002467 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2468 request.getFoundServiceCount(),
2469 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002470 request.getServicesCount(),
2471 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002472 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002473 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002474 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002475 } else if (listener instanceof ServiceInfoListener) {
2476 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2477 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2478 request.getFoundServiceCount(),
2479 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002480 request.isServiceFromCache(),
2481 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002482 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 continue;
2484 }
2485
2486 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002487 final AdvertiserMetrics metrics =
2488 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002489 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002490 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002491 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2492 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2493 metrics.mConflictDuringProbingCount,
2494 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002495 continue;
2496 }
2497
2498 if (!(request instanceof LegacyClientRequest)) {
2499 throw new IllegalStateException("Unknown request type: " + request.getClass());
2500 }
2501
2502 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002503 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002504 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002505 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002506 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2507 request.getFoundServiceCount(),
2508 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002509 request.getServicesCount(),
2510 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002511 break;
2512 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002513 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002514 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002515 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002516 break;
2517 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002518 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002519 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002520 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2521 NO_PACKET /* repliedRequestsCount */,
2522 NO_PACKET /* sentPacketCount */,
2523 0 /* conflictDuringProbingCount */,
2524 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002525 break;
2526 default:
2527 break;
2528 }
2529 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002530 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002531 updateMulticastLock();
2532 }
2533
2534 /**
2535 * Returns true if this client has any Java backend request that requests one of the given
2536 * networks.
2537 */
2538 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2539 for (int i = 0; i < mClientRequests.size(); i++) {
2540 final ClientRequest req = mClientRequests.valueAt(i);
2541 if (!(req instanceof JavaBackendClientRequest)) {
2542 continue;
2543 }
2544 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2545 .getRequestedNetwork();
2546 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2547 return true;
2548 }
2549 }
2550 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002551 }
2552
Paul Hud44e1b72023-06-16 02:07:42 +00002553 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2554 // transaction id, return the corresponding client request id.
2555 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002556 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002557 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002558 return mClientRequests.keyAt(i);
2559 }
Christopher Lane74411222014-04-25 18:39:07 -07002560 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002561 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002562 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002563
Paul Hub2e67d32023-04-18 05:50:14 +00002564 private void log(String message) {
2565 mClientLogs.log(message);
2566 }
2567
Paul Hu508a0122023-09-11 15:31:33 +08002568 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2569 return !(request instanceof DiscoveryManagerRequest)
2570 && !(request instanceof AdvertiserClientRequest);
2571 }
2572
2573 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2574 ClientRequest request) {
2575 mMetrics.reportServiceDiscoveryStarted(
2576 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002577 try {
2578 mCb.onDiscoverServicesStarted(listenerKey, info);
2579 } catch (RemoteException e) {
2580 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2581 }
2582 }
Paul Hu508a0122023-09-11 15:31:33 +08002583 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2584 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2585 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002586 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002587
Paul Hu508a0122023-09-11 15:31:33 +08002588 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2589 int transactionId, long durationMs) {
2590 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002591 try {
2592 mCb.onDiscoverServicesFailed(listenerKey, error);
2593 } catch (RemoteException e) {
2594 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2595 }
2596 }
2597
Paul Hu812e9212023-06-20 06:24:53 +00002598 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2599 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002600 try {
2601 mCb.onServiceFound(listenerKey, info);
2602 } catch (RemoteException e) {
2603 Log.e(TAG, "Error calling onServiceFound(", e);
2604 }
2605 }
2606
Paul Hu812e9212023-06-20 06:24:53 +00002607 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2608 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002609 try {
2610 mCb.onServiceLost(listenerKey, info);
2611 } catch (RemoteException e) {
2612 Log.e(TAG, "Error calling onServiceLost(", e);
2613 }
2614 }
2615
2616 void onStopDiscoveryFailed(int listenerKey, int error) {
2617 try {
2618 mCb.onStopDiscoveryFailed(listenerKey, error);
2619 } catch (RemoteException e) {
2620 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2621 }
2622 }
2623
Paul Hu812e9212023-06-20 06:24:53 +00002624 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2625 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002626 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002627 request.mTransactionId,
2628 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2629 request.getFoundServiceCount(),
2630 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002631 request.getServicesCount(),
2632 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002633 try {
2634 mCb.onStopDiscoverySucceeded(listenerKey);
2635 } catch (RemoteException e) {
2636 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2637 }
2638 }
2639
Paul Hu508a0122023-09-11 15:31:33 +08002640 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2641 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2642 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002643 }
2644
Paul Hu508a0122023-09-11 15:31:33 +08002645 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2646 int transactionId, long durationMs) {
2647 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002648 try {
2649 mCb.onRegisterServiceFailed(listenerKey, error);
2650 } catch (RemoteException e) {
2651 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2652 }
2653 }
2654
Paul Hu508a0122023-09-11 15:31:33 +08002655 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2656 ClientRequest request) {
2657 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2658 request.mTransactionId,
2659 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002660 try {
2661 mCb.onRegisterServiceSucceeded(listenerKey, info);
2662 } catch (RemoteException e) {
2663 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2664 }
2665 }
2666
2667 void onUnregisterServiceFailed(int listenerKey, int error) {
2668 try {
2669 mCb.onUnregisterServiceFailed(listenerKey, error);
2670 } catch (RemoteException e) {
2671 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2672 }
2673 }
2674
Paul Hu508a0122023-09-11 15:31:33 +08002675 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002676 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002677 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2678 request.mTransactionId,
2679 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002680 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2681 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002682 try {
2683 mCb.onUnregisterServiceSucceeded(listenerKey);
2684 } catch (RemoteException e) {
2685 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2686 }
2687 }
2688
Paul Hu508a0122023-09-11 15:31:33 +08002689 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2690 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2691 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002692 }
2693
Paul Hu508a0122023-09-11 15:31:33 +08002694 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2695 int transactionId, long durationMs) {
2696 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002697 try {
2698 mCb.onResolveServiceFailed(listenerKey, error);
2699 } catch (RemoteException e) {
2700 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2701 }
2702 }
2703
Paul Hua6bc4632023-06-26 01:18:29 +00002704 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2705 ClientRequest request) {
2706 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002707 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002708 request.mTransactionId,
2709 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002710 request.isServiceFromCache(),
2711 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002712 try {
2713 mCb.onResolveServiceSucceeded(listenerKey, info);
2714 } catch (RemoteException e) {
2715 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2716 }
2717 }
Paul Hub58deb72022-12-26 09:24:42 +00002718
2719 void onStopResolutionFailed(int listenerKey, int error) {
2720 try {
2721 mCb.onStopResolutionFailed(listenerKey, error);
2722 } catch (RemoteException e) {
2723 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2724 }
2725 }
2726
Paul Hu60149052023-07-31 14:26:08 +08002727 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2728 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002729 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002730 request.mTransactionId,
2731 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002732 try {
2733 mCb.onStopResolutionSucceeded(listenerKey);
2734 } catch (RemoteException e) {
2735 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2736 }
2737 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002738
2739 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002740 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002741 try {
2742 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2743 } catch (RemoteException e) {
2744 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2745 }
2746 }
2747
Paul Huddce5912023-08-01 10:26:49 +08002748 void onServiceInfoCallbackRegistered(int transactionId) {
2749 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2750 }
2751
2752 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2753 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002754 try {
2755 mCb.onServiceUpdated(listenerKey, info);
2756 } catch (RemoteException e) {
2757 Log.e(TAG, "Error calling onServiceUpdated", e);
2758 }
2759 }
2760
Paul Huddce5912023-08-01 10:26:49 +08002761 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2762 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002763 try {
2764 mCb.onServiceUpdatedLost(listenerKey);
2765 } catch (RemoteException e) {
2766 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2767 }
2768 }
2769
Paul Huddce5912023-08-01 10:26:49 +08002770 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2771 mMetrics.reportServiceInfoCallbackUnregistered(
2772 request.mTransactionId,
2773 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2774 request.getFoundServiceCount(),
2775 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002776 request.isServiceFromCache(),
2777 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002778 try {
2779 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2780 } catch (RemoteException e) {
2781 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2782 }
2783 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002784 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002785}