blob: e8f48a38b1d97e65329bdb8e543f280bf0b7d9e8 [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 VAN629234c2024-02-08 18:27:45 +090029import static android.net.nsd.NsdManager.SUBTYPE_LABEL_REGEX;
Yuyang Huang86d083f2023-12-12 19:56:41 +090030import static android.net.nsd.NsdManager.TYPE_REGEX;
Kangping Dongcd350182023-12-12 17:50:34 +080031import static android.os.Process.SYSTEM_UID;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090032import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090033
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090034import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090035import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080036import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
37import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090038import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hu11a883d2023-12-14 07:36:44 +000039import static com.android.server.connectivity.mdns.MdnsSearchOptions.AGGRESSIVE_QUERY_MODE;
Paul Hu05086bd2024-01-26 03:48:51 +000040import static com.android.server.connectivity.mdns.MdnsSearchOptions.PASSIVE_QUERY_MODE;
Paul Hucdef3532023-06-18 14:47:35 +000041import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090042
Paul Hu23fa2022023-01-13 22:57:24 +080043import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080044import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090045import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090046import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080047import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070048import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090049import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090050import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080051import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090052import android.net.LinkProperties;
53import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080054import android.net.mdns.aidl.DiscoveryInfo;
55import android.net.mdns.aidl.GetAddressInfo;
56import android.net.mdns.aidl.IMDnsEventListener;
57import android.net.mdns.aidl.RegistrationInfo;
58import android.net.mdns.aidl.ResolutionInfo;
Yuyang Huang86d083f2023-12-12 19:56:41 +090059import android.net.nsd.AdvertisingRequest;
Kangping Dong1f1a3792023-12-10 22:05:04 +080060import android.net.nsd.DiscoveryRequest;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070061import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090062import android.net.nsd.INsdManagerCallback;
63import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090064import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080065import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070066import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080067import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090068import android.net.nsd.OffloadEngine;
69import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090070import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000071import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090072import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090073import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080074import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090075import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080076import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070077import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090078import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090079import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070080import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090081import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080082import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090083import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090084import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090085import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070086import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070087
paulhua262cc12019-08-12 16:25:11 +080088import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000089import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080090import com.android.internal.util.State;
91import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000092import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090093import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090094import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090096import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080097import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000098import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080099import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900100import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900101import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +0900103import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900104import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800105import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800106import com.android.server.connectivity.mdns.MdnsSearchOptions;
107import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
108import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800109import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900110import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800111
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700112import java.io.FileDescriptor;
113import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900114import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700115import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900116import java.net.NetworkInterface;
117import java.net.SocketException;
118import java.net.UnknownHostException;
Kangping Dongcd350182023-12-12 17:50:34 +0800119import java.time.Duration;
Paul Hu2b865912023-03-06 14:27:53 +0800120import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900121import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800122import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900123import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700124import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800125import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800126import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800127import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900128import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000129import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800130import java.util.regex.Matcher;
131import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700132
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700133/**
134 * Network Service Discovery Service handles remote service discovery operation requests by
135 * implementing the INsdManager interface.
136 *
137 * @hide
138 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900139@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700140public class NsdService extends INsdManager.Stub {
141 private static final String TAG = "NsdService";
142 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900143 /**
144 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
145 * implementation.
146 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800147 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800148 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700149
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900150 /**
151 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
152 * implementation.
153 */
154 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
155
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900156 /**
157 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
158 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
159 *
160 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
161 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
162 *
163 * In which case the flags:
164 * "mdns_discovery_manager_allowlist_mytype_version",
165 * "mdns_advertiser_allowlist_mytype_version",
166 * "mdns_discovery_manager_allowlist_othertype_version",
167 * "mdns_advertiser_allowlist_othertype_version"
168 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
169 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900170 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900171 *
172 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
173 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
174 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
175 */
176 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
177
178 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
179 "mdns_discovery_manager_allowlist_";
180 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
181 "mdns_advertiser_allowlist_";
182 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
183
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +0900184 private static final String FORCE_ENABLE_FLAG_FOR_TEST_PREFIX = "test_";
Kangping Dong5af24b62023-12-10 21:41:16 +0800185
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900186 @VisibleForTesting
187 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
188 "mdns_config_running_app_active_importance_cutoff";
189 @VisibleForTesting
190 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
191 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
192 private final int mRunningAppActiveImportanceCutoff;
193
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900194 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000195 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900196 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000197 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
198 @VisibleForTesting
199 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800200 private static final int NO_SENT_QUERY_COUNT = 0;
201 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800202 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800203 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700204
Hugo Benichi32be63d2017-04-05 14:06:11 +0900205 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900206 private final NsdStateMachine mNsdStateMachine;
Ken Chen80c9f6f2023-11-15 18:24:54 +0800207 // It can be null on V+ device since mdns native service provided by netd is removed.
208 private final @Nullable MDnsManager mMDnsManager;
paulhu2b9ed952022-02-10 21:58:32 +0800209 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900210 @NonNull
211 private final Dependencies mDeps;
212 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800213 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900214 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800215 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900216 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800217 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900218 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900219 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000220 @NonNull
221 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800222 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800223 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800224 // state machine thread. If change this outside state machine, it will need to introduce
225 // synchronization.
226 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800227 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700228
229 /**
230 * Clients receiving asynchronous messages
231 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900232 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700233
Paul Hud44e1b72023-06-16 02:07:42 +0000234 /* A map from transaction(unique) id to client info */
235 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700236
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900237 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
238 @Nullable
239 private WifiManager.MulticastLock mHeldMulticastLock;
240 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
241 // (non-null), value is the requested Network (nullable)
242 @NonNull
243 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
244 @NonNull
245 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
246
Luke Huang05298582021-06-13 16:52:05 +0000247 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700248
Hugo Benichi32be63d2017-04-05 14:06:11 +0900249 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700250 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800251 // The count of the connected legacy clients.
252 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000253 // The number of client that ever connected.
254 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700255
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900256 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
257 new RemoteCallbackList<>();
Paul Hu11a883d2023-12-14 07:36:44 +0000258 @NonNull
259 private final MdnsFeatureFlags mMdnsFeatureFlags;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900260
261 private static class OffloadEngineInfo {
262 @NonNull final String mInterfaceName;
263 final long mOffloadCapabilities;
264 final long mOffloadType;
265 @NonNull final IOffloadEngine mOffloadEngine;
266
267 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
268 @NonNull String interfaceName, long capabilities, long offloadType) {
269 this.mOffloadEngine = offloadEngine;
270 this.mInterfaceName = interfaceName;
271 this.mOffloadCapabilities = capabilities;
272 this.mOffloadType = offloadType;
273 }
274 }
275
Paul Hu812e9212023-06-20 06:24:53 +0000276 @VisibleForTesting
277 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000278 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800279 protected final int mTransactionId;
280 @NonNull
Paul Hu23fa2022023-01-13 22:57:24 +0800281 protected final String mListenedServiceType;
282
Kangping Dong97b2adc2024-01-11 16:00:37 +0800283 MdnsListener(int clientRequestId, int transactionId, @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000284 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800285 mTransactionId = transactionId;
Paul Hu23fa2022023-01-13 22:57:24 +0800286 mListenedServiceType = listenedServiceType;
287 }
288
289 @NonNull
290 public String getListenedServiceType() {
291 return mListenedServiceType;
292 }
293
294 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000295 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
296 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800297
298 @Override
299 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
300
301 @Override
302 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
303
304 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000305 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
306 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800307
308 @Override
309 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
310
311 @Override
312 public void onSearchStoppedWithError(int error) { }
313
314 @Override
315 public void onSearchFailedToStart() { }
316
317 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800318 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
319 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800320
321 @Override
322 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
323 }
324
325 private class DiscoveryListener extends MdnsListener {
326
Paul Hud44e1b72023-06-16 02:07:42 +0000327 DiscoveryListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800328 @NonNull String listenServiceType) {
329 super(clientRequestId, transactionId, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800330 }
331
332 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000333 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
334 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800335 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
336 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000337 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800338 }
339
340 @Override
341 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800342 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
343 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000344 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800345 }
Paul Hubad6fe92023-07-24 21:25:22 +0800346
347 @Override
348 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
349 int sentQueryTransactionId) {
350 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
351 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
352 }
Paul Hu23fa2022023-01-13 22:57:24 +0800353 }
354
Paul Hu75069ed2023-01-14 00:31:09 +0800355 private class ResolutionListener extends MdnsListener {
356
Paul Hud44e1b72023-06-16 02:07:42 +0000357 ResolutionListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800358 @NonNull String listenServiceType) {
359 super(clientRequestId, transactionId, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800360 }
361
362 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000363 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800364 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
365 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000366 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800367 }
Paul Hubad6fe92023-07-24 21:25:22 +0800368
369 @Override
370 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
371 int sentQueryTransactionId) {
372 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
373 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
374 }
Paul Hu75069ed2023-01-14 00:31:09 +0800375 }
376
Paul Hu30bd70d2023-02-07 13:20:56 +0000377 private class ServiceInfoListener extends MdnsListener {
378
Paul Hud44e1b72023-06-16 02:07:42 +0000379 ServiceInfoListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800380 @NonNull String listenServiceType) {
381 super(clientRequestId, transactionId, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000382 }
383
384 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000385 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
386 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000387 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
388 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000389 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000390 }
391
392 @Override
393 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
394 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
395 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000396 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000397 }
398
399 @Override
400 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
401 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
402 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000403 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000404 }
Paul Hubad6fe92023-07-24 21:25:22 +0800405
406 @Override
407 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
408 int sentQueryTransactionId) {
409 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
410 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
411 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000412 }
413
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900414 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
415 @Override
416 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
417 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
418 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
419 // filtering on such interfaces, so taking the multicast lock is not necessary to
420 // disable APF filtering of multicast.
421 if (socketNetwork == null
422 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
423 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
424 return;
425 }
426
427 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
428 updateMulticastLock();
429 }
430 }
431
432 @Override
433 public void onSocketDestroyed(@Nullable Network socketNetwork,
434 @NonNull MdnsInterfaceSocket socket) {
435 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
436 updateMulticastLock();
437 }
438 }
439 }
440
441 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
442 private final Handler mHandler;
443
444 private UidImportanceListener(Handler handler) {
445 mHandler = handler;
446 }
447
448 @Override
449 public void onUidImportance(int uid, int importance) {
450 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
451 }
452 }
453
454 private void handleUidImportanceChanged(int uid, int importance) {
455 // Lower importance values are more "important"
456 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
457 ? mRunningAppActiveUids.add(uid)
458 : mRunningAppActiveUids.remove(uid);
459 if (modified) {
460 updateMulticastLock();
461 }
462 }
463
464 /**
465 * Take or release the lock based on updated internal state.
466 *
467 * This determines whether the lock needs to be held based on
468 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
469 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
470 * updated.
471 */
472 private void updateMulticastLock() {
473 final int needsLockUid = getMulticastLockNeededUid();
474 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
475 final WifiManager wm = mContext.getSystemService(WifiManager.class);
476 if (wm == null) {
477 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
478 return;
479 }
480 mHeldMulticastLock = wm.createMulticastLock(TAG);
481 mHeldMulticastLock.acquire();
482 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
483 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
484 mHeldMulticastLock.release();
485 mHeldMulticastLock = null;
486 mServiceLogs.log("Released multicast lock");
487 }
488 }
489
490 /**
491 * @return The UID of an app requiring the multicast lock, or -1 if none.
492 */
493 private int getMulticastLockNeededUid() {
494 if (mWifiLockRequiredNetworks.size() == 0) {
495 // Return early if NSD is not active, or not on any relevant network
496 return -1;
497 }
Paul Hud44e1b72023-06-16 02:07:42 +0000498 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
499 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900500 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
501 // Ignore non-active UIDs
502 continue;
503 }
504
505 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
506 return clientInfo.mUid;
507 }
508 }
509 return -1;
510 }
511
Paul Hu019621e2023-01-13 23:26:49 +0800512 /**
513 * Data class of mdns service callback information.
514 */
515 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000516 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800517 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800518 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000519 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800520
Paul Hubad6fe92023-07-24 21:25:22 +0800521 MdnsEvent(int clientRequestId) {
522 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
523 }
524
525 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000526 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
527 }
528
Paul Hubad6fe92023-07-24 21:25:22 +0800529 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000530 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000531 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800532 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000533 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800534 }
535 }
536
Paul Hu77c11182023-10-23 16:17:32 +0800537 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700538 private class NsdStateMachine extends StateMachine {
539
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700540 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700541
542 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700543 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900544 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700545 }
546
Luke Huang92860f92021-06-23 06:29:30 +0000547 private void maybeStartDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000548 if (mIsDaemonStarted) {
549 if (DBG) Log.d(TAG, "Daemon is already started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800550 return;
551 }
552
Paul Hu4a87ed42024-01-10 08:58:30 +0000553 if (mMDnsManager == null) {
554 Log.wtf(TAG, "maybeStartDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800555 return;
556 }
557 mMDnsManager.registerEventListener(mMDnsEventCallback);
558 mMDnsManager.startDaemon();
559 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000560 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000561 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000562 }
563
paulhu2b9ed952022-02-10 21:58:32 +0800564 private void maybeStopDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000565 if (!mIsDaemonStarted) {
566 if (DBG) Log.d(TAG, "Daemon has not been started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800567 return;
568 }
569
Paul Hu4a87ed42024-01-10 08:58:30 +0000570 if (mMDnsManager == null) {
571 Log.wtf(TAG, "maybeStopDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800572 return;
573 }
574 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
575 mMDnsManager.stopDaemon();
576 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000577 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800578 }
579
Luke Huang92860f92021-06-23 06:29:30 +0000580 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000581 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000582 }
583
584 private void scheduleStop() {
585 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
586 }
587 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800588 // The native daemon should stay alive and can't be cleanup
589 // if any legacy client connected.
590 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000591 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000592 }
593 }
594
Luke Huang92860f92021-06-23 06:29:30 +0000595 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000596 this.removeMessages(NsdManager.DAEMON_CLEANUP);
597 }
598
Paul Hu23fa2022023-01-13 22:57:24 +0800599 private void maybeStartMonitoringSockets() {
600 if (mIsMonitoringSocketsStarted) {
601 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
602 return;
603 }
604
605 mMdnsSocketProvider.startMonitoringSockets();
606 mIsMonitoringSocketsStarted = true;
607 }
608
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900609 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
610 if (!mIsMonitoringSocketsStarted) return;
611 if (isAnyRequestActive()) return;
612
Paul Hu58f20602023-02-18 11:41:07 +0800613 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800614 mIsMonitoringSocketsStarted = false;
615 }
616
Hugo Benichi803a2f02017-04-24 11:35:06 +0900617 NsdStateMachine(String name, Handler handler) {
618 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800619 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800620 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900621 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700622 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700623 }
624
Irfan Sheriff75006652012-04-17 23:15:29 -0700625 class EnabledState extends State {
626 @Override
627 public void enter() {
628 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 }
630
631 @Override
632 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000633 // TODO: it is incorrect to stop the daemon without expunging all requests
634 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000635 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700636 }
637
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700638 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900639 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800640 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700641 return true;
642 }
643 return false;
644 }
645
Paul Hu508a0122023-09-11 15:31:33 +0800646 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000647 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800648 final LegacyClientRequest request =
649 new LegacyClientRequest(transactionId, what, startTimeMs);
650 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000651 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000652 // Remove the cleanup event because here comes a new request.
653 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800654 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700655 }
656
Paul Hud44e1b72023-06-16 02:07:42 +0000657 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900658 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000659 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000660 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000661 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900662 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800663 }
664
Paul Hud44e1b72023-06-16 02:07:42 +0000665 private void removeRequestMap(
666 int clientRequestId, int transactionId, ClientInfo clientInfo) {
667 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900668 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000669 clientInfo.mClientRequests.remove(clientRequestId);
670 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900671
672 if (existing instanceof LegacyClientRequest) {
673 maybeScheduleStop();
674 } else {
675 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900676 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900677 }
678 }
679
Paul Hu508a0122023-09-11 15:31:33 +0800680 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
681 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900682 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800683 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
684 listener, requestedNetwork, mClock.elapsedRealtime());
685 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000686 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900687 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800688 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800689 }
690
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900691 /**
692 * Truncate a service name to up to 63 UTF-8 bytes.
693 *
694 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
695 * names used in registerService follows historical behavior (see mdnsresponder
696 * handle_regservice_request).
697 */
698 @NonNull
699 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900700 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800701 }
702
Paul Hud44e1b72023-06-16 02:07:42 +0000703 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
704 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800705 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000706 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800707 }
708
Paul Hu77c11182023-10-23 16:17:32 +0800709 private ClientInfo getClientInfoForReply(Message msg) {
710 final ListenerArgs args = (ListenerArgs) msg.obj;
711 return mClients.get(args.connector);
712 }
713
Kangping Dong5af24b62023-12-10 21:41:16 +0800714 /**
715 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
716 * contains invalid subtype label.
717 */
718 private boolean checkSubtypeLabels(Set<String> subtypes) {
719 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
720 mServiceLogs.e(
721 "Too many subtypes: " + subtypes.size() + " (max = "
722 + MAX_SUBTYPE_COUNT + ")");
723 return false;
724 }
725
726 for (String subtype : subtypes) {
727 if (!checkSubtypeLabel(subtype)) {
728 mServiceLogs.e("Subtype " + subtype + " is invalid");
729 return false;
730 }
731 }
732 return true;
733 }
734
735 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
736 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
737 for (String subtype : subtypes) {
738 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
739 }
740 return new ArraySet<>(subtypeMap.values());
741 }
742
Kangping Dongcd350182023-12-12 17:50:34 +0800743 private boolean checkTtl(
744 @Nullable Duration ttl, @NonNull ClientInfo clientInfo) {
745 if (ttl == null) {
746 return true;
747 }
748
749 final long ttlSeconds = ttl.toSeconds();
750 final int uid = clientInfo.getUid();
751
752 // Allows Thread module in the system_server to register TTL that is smaller than
753 // 30 seconds
754 final long minTtlSeconds = uid == SYSTEM_UID ? 0 : NsdManager.TTL_SECONDS_MIN;
755
756 // Allows Thread module in the system_server to register TTL that is larger than
757 // 10 hours
758 final long maxTtlSeconds =
759 uid == SYSTEM_UID ? 0xffffffffL : NsdManager.TTL_SECONDS_MAX;
760
761 if (ttlSeconds < minTtlSeconds || ttlSeconds > maxTtlSeconds) {
762 mServiceLogs.e("ttlSeconds exceeds allowed range (value = "
763 + ttlSeconds + ", allowedRange = [" + minTtlSeconds
764 + ", " + maxTtlSeconds + " ])");
765 return false;
766 }
767 return true;
768 }
769
Irfan Sheriff75006652012-04-17 23:15:29 -0700770 @Override
771 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900772 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000773 final int transactionId;
774 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900775 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700776 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800777 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800778 if (DBG) Log.d(TAG, "Discover services");
Kangping Dong1f1a3792023-12-10 22:05:04 +0800779 final DiscoveryArgs discoveryArgs = (DiscoveryArgs) msg.obj;
780 clientInfo = mClients.get(discoveryArgs.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000781 // If the binder death notification for a INsdManagerCallback was received
782 // before any calls are received by NsdService, the clientInfo would be
783 // cleared and cause NPE. Add a null check here to prevent this corner case.
784 if (clientInfo == null) {
785 Log.e(TAG, "Unknown connector in discovery");
786 break;
787 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700788
789 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800790 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
791 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700792 break;
793 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700794
Kangping Dong1f1a3792023-12-10 22:05:04 +0800795 final DiscoveryRequest discoveryRequest = discoveryArgs.discoveryRequest;
Paul Hud44e1b72023-06-16 02:07:42 +0000796 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900797 final Pair<String, List<String>> typeAndSubtype =
Kangping Dong1f1a3792023-12-10 22:05:04 +0800798 parseTypeAndSubtype(discoveryRequest.getServiceType());
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900799 final String serviceType = typeAndSubtype == null
800 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800801 if (clientInfo.mUseJavaBackend
802 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900803 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900804 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800805 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
806 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800807 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700808 }
Paul Hu23fa2022023-01-13 22:57:24 +0800809
Kangping Dong1f1a3792023-12-10 22:05:04 +0800810 String subtype = discoveryRequest.getSubtype();
811 if (subtype == null && !typeAndSubtype.second.isEmpty()) {
812 subtype = typeAndSubtype.second.get(0);
813 }
814
815 if (subtype != null && !checkSubtypeLabel(subtype)) {
816 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
817 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
818 break;
819 }
820
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900821 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800822 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000823 final MdnsListener listener = new DiscoveryListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800824 transactionId, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900825 final MdnsSearchOptions.Builder optionsBuilder =
826 MdnsSearchOptions.newBuilder()
Kangping Dong1f1a3792023-12-10 22:05:04 +0800827 .setNetwork(discoveryRequest.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900828 .setRemoveExpiredService(true)
Paul Hu11a883d2023-12-14 07:36:44 +0000829 .setQueryMode(
830 mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
831 ? AGGRESSIVE_QUERY_MODE
832 : PASSIVE_QUERY_MODE);
Kangping Dong1f1a3792023-12-10 22:05:04 +0800833 if (subtype != null) {
834 // checkSubtypeLabels() ensures that subtypes start with '_' but
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900835 // MdnsSearchOptions expects the underscore to not be present.
Kangping Dong1f1a3792023-12-10 22:05:04 +0800836 optionsBuilder.addSubtype(subtype.substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900837 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900838 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900839 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800840 final ClientRequest request = storeDiscoveryManagerRequestMap(
841 clientRequestId, transactionId, listener, clientInfo,
Kangping Dong1f1a3792023-12-10 22:05:04 +0800842 discoveryRequest.getNetwork());
843 clientInfo.onDiscoverServicesStarted(
844 clientRequestId, discoveryRequest, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000845 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000846 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700847 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800848 maybeStartDaemon();
Kangping Dong1f1a3792023-12-10 22:05:04 +0800849 if (discoverServices(transactionId, discoveryRequest)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800850 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000851 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Kangping Dong1f1a3792023-12-10 22:05:04 +0800852 + discoveryRequest.getServiceType());
Paul Hu23fa2022023-01-13 22:57:24 +0800853 }
Paul Hu508a0122023-09-11 15:31:33 +0800854 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
855 transactionId, clientInfo, msg.what,
856 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000857 clientInfo.onDiscoverServicesStarted(
Kangping Dong1f1a3792023-12-10 22:05:04 +0800858 clientRequestId, discoveryRequest, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800859 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000860 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800861 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
862 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800863 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700864 }
865 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800866 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900867 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800868 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900869 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900870 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000871 // If the binder death notification for a INsdManagerCallback was received
872 // before any calls are received by NsdService, the clientInfo would be
873 // cleared and cause NPE. Add a null check here to prevent this corner case.
874 if (clientInfo == null) {
875 Log.e(TAG, "Unknown connector in stop discovery");
876 break;
877 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700878
Paul Hud44e1b72023-06-16 02:07:42 +0000879 final ClientRequest request =
880 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900881 if (request == null) {
882 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700883 break;
884 }
Paul Hud44e1b72023-06-16 02:07:42 +0000885 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900886 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
887 // point, so this needs to check the type of the original request to
888 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900889 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000890 stopDiscoveryManagerRequest(
891 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000892 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000893 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700894 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000895 removeRequestMap(clientRequestId, transactionId, clientInfo);
896 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000897 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800898 } else {
899 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000900 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800901 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700902 }
903 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900904 }
905 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800906 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900907 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900908 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000909 // If the binder death notification for a INsdManagerCallback was received
910 // before any calls are received by NsdService, the clientInfo would be
911 // cleared and cause NPE. Add a null check here to prevent this corner case.
912 if (clientInfo == null) {
913 Log.e(TAG, "Unknown connector in registration");
914 break;
915 }
916
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700917 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800918 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
919 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700920 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700921 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900922 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
923 if (advertisingRequest == null) {
924 Log.e(TAG, "Unknown advertisingRequest in registration");
925 break;
926 }
927 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900928 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900929 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
930 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900931 final String registerServiceType = typeSubtype == null
932 ? null : typeSubtype.first;
Handa Wang096e32e2024-01-14 08:21:28 +0000933 final String hostname = serviceInfo.getHostname();
934 // Keep compatible with the legacy behavior: It's allowed to set host
935 // addresses for a service registration although the host addresses
936 // won't be registered. To register the addresses for a host, the
937 // hostname must be specified.
938 if (hostname == null) {
939 serviceInfo.setHostAddresses(Collections.emptyList());
940 }
Paul Hu2e0a88c2023-03-09 16:05:01 +0800941 if (clientInfo.mUseJavaBackend
942 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900943 || useAdvertiserForType(registerServiceType)) {
Handa Wang096e32e2024-01-14 08:21:28 +0000944 if (serviceType != null && registerServiceType == null) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900945 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800946 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
947 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900948 break;
949 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900950 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
951 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
952 // If it is an update request, then reuse the old transactionId
953 if (isUpdateOnly) {
954 final ClientRequest existingClientRequest =
955 clientInfo.mClientRequests.get(clientRequestId);
956 if (existingClientRequest == null) {
957 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
958 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
959 NsdManager.FAILURE_INTERNAL_ERROR,
960 false /* isLegacy */);
961 break;
962 }
963 transactionId = existingClientRequest.mTransactionId;
964 } else {
965 transactionId = getUniqueId();
966 }
Handa Wang096e32e2024-01-14 08:21:28 +0000967
968 if (registerServiceType != null) {
969 serviceInfo.setServiceType(registerServiceType);
970 serviceInfo.setServiceName(
971 truncateServiceName(serviceInfo.getServiceName()));
972 }
973
974 if (!checkHostname(hostname)) {
975 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
976 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
977 break;
978 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900979
Kangping Dong5af24b62023-12-10 21:41:16 +0800980 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Handa Wang096e32e2024-01-14 08:21:28 +0000981 if (typeSubtype != null && typeSubtype.second != null) {
982 for (String subType : typeSubtype.second) {
983 if (!TextUtils.isEmpty(subType)) {
984 subtypes.add(subType);
985 }
Yuyang Huang170d42f2023-12-09 15:26:16 +0900986 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800987 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800988 subtypes = dedupSubtypeLabels(subtypes);
989
990 if (!checkSubtypeLabels(subtypes)) {
991 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
992 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
993 break;
994 }
995
Kangping Dongcd350182023-12-12 17:50:34 +0800996 if (!checkTtl(advertisingRequest.getTtl(), clientInfo)) {
997 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
998 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
999 break;
1000 }
1001
Kangping Dong5af24b62023-12-10 21:41:16 +08001002 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001003 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +09001004 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
Kangping Dongcd350182023-12-12 17:50:34 +08001005 MdnsAdvertisingOptions.newBuilder()
1006 .setIsOnlyUpdate(isUpdateOnly)
1007 .setTtl(advertisingRequest.getTtl())
1008 .build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +09001009 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Handa Wang096e32e2024-01-14 08:21:28 +00001010 mdnsAdvertisingOptions, clientInfo.mUid);
Paul Hud44e1b72023-06-16 02:07:42 +00001011 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001012 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -07001013 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001014 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +09001015 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +00001016 if (registerService(transactionId, serviceInfo)) {
1017 if (DBG) {
1018 Log.d(TAG, "Register " + clientRequestId
1019 + " " + transactionId);
1020 }
Paul Hua6bc4632023-06-26 01:18:29 +00001021 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1022 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001023 // Return success after mDns reports success
1024 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001025 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001026 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
1027 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001028 }
1029
Irfan Sheriff75006652012-04-17 23:15:29 -07001030 }
1031 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001032 }
1033 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001034 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001035 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001036 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001037 // If the binder death notification for a INsdManagerCallback was received
1038 // before any calls are received by NsdService, the clientInfo would be
1039 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001040 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +08001041 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001042 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001043 }
Paul Hud44e1b72023-06-16 02:07:42 +00001044 final ClientRequest request =
1045 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001046 if (request == null) {
1047 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
1048 break;
1049 }
Paul Hud44e1b72023-06-16 02:07:42 +00001050 transactionId = request.mTransactionId;
1051 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001052
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001053 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
1054 // so this needs to check the type of the original request to unregister
1055 // instead of looking at the flag value.
1056 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001057 final AdvertiserMetrics metrics =
1058 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001059 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001060 clientInfo.onUnregisterServiceSucceeded(
1061 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001062 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001063 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001064 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001065 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1066 NO_PACKET /* sentPacketCount */,
1067 0 /* conflictDuringProbingCount */,
1068 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001069 } else {
1070 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001071 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001072 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001073 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001074 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001075 }
Paul Hu75069ed2023-01-14 00:31:09 +08001076 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001077 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001078 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001079 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001080 // If the binder death notification for a INsdManagerCallback was received
1081 // before any calls are received by NsdService, the clientInfo would be
1082 // cleared and cause NPE. Add a null check here to prevent this corner case.
1083 if (clientInfo == null) {
1084 Log.e(TAG, "Unknown connector in resolution");
1085 break;
1086 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001087
Paul Hu75069ed2023-01-14 00:31:09 +08001088 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001089 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001090 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001091 parseTypeAndSubtype(info.getServiceType());
1092 final String serviceType = typeSubtype == null
1093 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001094 if (clientInfo.mUseJavaBackend
1095 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001096 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001097 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001098 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1099 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001100 break;
1101 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001102 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001103
1104 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001105 final MdnsListener listener = new ResolutionListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001106 transactionId, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001107 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1108 .setNetwork(info.getNetwork())
Paul Hu11a883d2023-12-14 07:36:44 +00001109 .setQueryMode(mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
1110 ? AGGRESSIVE_QUERY_MODE
1111 : PASSIVE_QUERY_MODE)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001112 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001113 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001114 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001115 mMdnsDiscoveryManager.registerListener(
1116 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001117 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1118 listener, clientInfo, info.getNetwork());
1119 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001120 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001121 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001122 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001123 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1124 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001125 break;
1126 }
1127
1128 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001129 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001130 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001131 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1132 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001133 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001134 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1135 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001136 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001137 }
1138 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001139 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001140 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001141 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001142 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001143 clientInfo = mClients.get(args.connector);
1144 // If the binder death notification for a INsdManagerCallback was received
1145 // before any calls are received by NsdService, the clientInfo would be
1146 // cleared and cause NPE. Add a null check here to prevent this corner case.
1147 if (clientInfo == null) {
1148 Log.e(TAG, "Unknown connector in stop resolution");
1149 break;
1150 }
1151
Paul Hud44e1b72023-06-16 02:07:42 +00001152 final ClientRequest request =
1153 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001154 if (request == null) {
1155 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1156 break;
1157 }
Paul Hud44e1b72023-06-16 02:07:42 +00001158 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001159 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1160 // point, so this needs to check the type of the original request to
1161 // unregister instead of looking at the flag value.
1162 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001163 stopDiscoveryManagerRequest(
1164 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001165 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001166 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001167 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001168 removeRequestMap(clientRequestId, transactionId, clientInfo);
1169 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001170 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001171 } else {
1172 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001173 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001174 }
1175 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001176 }
Paul Hub58deb72022-12-26 09:24:42 +00001177 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001178 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001179 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001180 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001181 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001182 clientInfo = mClients.get(args.connector);
1183 // If the binder death notification for a INsdManagerCallback was received
1184 // before any calls are received by NsdService, the clientInfo would be
1185 // cleared and cause NPE. Add a null check here to prevent this corner case.
1186 if (clientInfo == null) {
1187 Log.e(TAG, "Unknown connector in callback registration");
1188 break;
1189 }
1190
Paul Hu30bd70d2023-02-07 13:20:56 +00001191 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001192 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001193 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001194 parseTypeAndSubtype(info.getServiceType());
1195 final String serviceType = typeAndSubtype == null
1196 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001197 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001198 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001199 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001200 break;
1201 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001202 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001203
Paul Hu30bd70d2023-02-07 13:20:56 +00001204 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001205 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001206 transactionId, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001207 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1208 .setNetwork(info.getNetwork())
Paul Hu11a883d2023-12-14 07:36:44 +00001209 .setQueryMode(mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
1210 ? AGGRESSIVE_QUERY_MODE
1211 : PASSIVE_QUERY_MODE)
Paul Hu30bd70d2023-02-07 13:20:56 +00001212 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001213 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001214 .build();
1215 mMdnsDiscoveryManager.registerListener(
1216 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001217 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1218 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001219 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001220 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001221 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001222 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001223 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001224 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001225 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001226 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001227 clientInfo = mClients.get(args.connector);
1228 // If the binder death notification for a INsdManagerCallback was received
1229 // before any calls are received by NsdService, the clientInfo would be
1230 // cleared and cause NPE. Add a null check here to prevent this corner case.
1231 if (clientInfo == null) {
1232 Log.e(TAG, "Unknown connector in callback unregistration");
1233 break;
1234 }
1235
Paul Hud44e1b72023-06-16 02:07:42 +00001236 final ClientRequest request =
1237 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001238 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001239 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001240 break;
1241 }
Paul Hud44e1b72023-06-16 02:07:42 +00001242 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001243 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001244 stopDiscoveryManagerRequest(
1245 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001246 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001247 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001248 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001249 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001250 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001251 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001252 }
paulhu2b9ed952022-02-10 21:58:32 +08001253 case MDNS_SERVICE_EVENT:
1254 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001255 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001256 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001257 break;
Paul Hu019621e2023-01-13 23:26:49 +08001258 case MDNS_DISCOVERY_MANAGER_EVENT:
1259 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1260 return NOT_HANDLED;
1261 }
1262 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001263 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1264 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1265 // TODO: Limits the number of registrations created by a given class.
1266 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1267 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001268 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001269 break;
1270 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1271 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1272 break;
Paul Hu77c11182023-10-23 16:17:32 +08001273 case NsdManager.REGISTER_CLIENT:
1274 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1275 final INsdManagerCallback cb = arg.callback;
1276 try {
1277 cb.asBinder().linkToDeath(arg.connector, 0);
1278 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1279 final NetworkNsdReportedMetrics metrics =
1280 mDeps.makeNetworkNsdReportedMetrics(
1281 (int) mClock.elapsedRealtime());
1282 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1283 mServiceLogs.forSubComponent(tag), metrics);
1284 mClients.put(arg.connector, clientInfo);
1285 } catch (RemoteException e) {
1286 Log.w(TAG, "Client request id " + clientRequestId
1287 + " has already died");
1288 }
1289 break;
1290 case NsdManager.UNREGISTER_CLIENT:
1291 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1292 clientInfo = mClients.remove(connector);
1293 if (clientInfo != null) {
1294 clientInfo.expungeAllRequests();
1295 if (clientInfo.isPreSClient()) {
1296 mLegacyClientCount -= 1;
1297 }
1298 }
1299 maybeStopMonitoringSocketsIfNoActiveRequest();
1300 maybeScheduleStop();
1301 break;
1302 case NsdManager.DAEMON_CLEANUP:
1303 maybeStopDaemon();
1304 break;
1305 // This event should be only sent by the legacy (target SDK < S) clients.
1306 // Mark the sending client as legacy.
1307 case NsdManager.DAEMON_STARTUP:
1308 clientInfo = getClientInfoForReply(msg);
1309 if (clientInfo != null) {
1310 cancelStop();
1311 clientInfo.setPreSClient();
1312 mLegacyClientCount += 1;
1313 maybeStartDaemon();
1314 }
1315 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001316 default:
Paul Hu77c11182023-10-23 16:17:32 +08001317 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001318 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001319 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001320 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001321 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001322
Paul Hud44e1b72023-06-16 02:07:42 +00001323 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001324 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001325 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001326 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001327 Log.e(TAG, String.format(
1328 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001329 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001330 }
1331
1332 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001333 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1334 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001335 // This can happen because of race conditions. For example,
1336 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1337 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001338 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1339 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001340 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 }
Paul Hu812e9212023-06-20 06:24:53 +00001342 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1343 if (request == null) {
1344 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1345 return false;
1346 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001347 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001348 Log.d(TAG, String.format(
1349 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001350 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001351 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001352 case IMDnsEventListener.SERVICE_FOUND: {
1353 final DiscoveryInfo info = (DiscoveryInfo) obj;
1354 final String name = info.serviceName;
1355 final String type = info.registrationType;
1356 servInfo = new NsdServiceInfo(name, type);
1357 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001358 if (foundNetId == 0L) {
1359 // Ignore services that do not have a Network: they are not usable
1360 // by apps, as they would need privileged permissions to use
1361 // interfaces that do not have an associated Network.
1362 break;
1363 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001364 if (foundNetId == INetd.DUMMY_NET_ID) {
1365 // Ignore services on the dummy0 interface: they are only seen when
1366 // discovering locally advertised services, and are not reachable
1367 // through that interface.
1368 break;
1369 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001370 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001371
1372 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001373 break;
paulhu2b9ed952022-02-10 21:58:32 +08001374 }
1375 case IMDnsEventListener.SERVICE_LOST: {
1376 final DiscoveryInfo info = (DiscoveryInfo) obj;
1377 final String name = info.serviceName;
1378 final String type = info.registrationType;
1379 final int lostNetId = info.netId;
1380 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001381 // The network could be set to null (netId 0) if it was torn down when the
1382 // service is lost
1383 // TODO: avoid returning null in that case, possibly by remembering
1384 // found services on the same interface index and their network at the time
1385 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001386 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001387 break;
paulhu2b9ed952022-02-10 21:58:32 +08001388 }
1389 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001390 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001391 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1392 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001393 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001394 break;
paulhu2b9ed952022-02-10 21:58:32 +08001395 case IMDnsEventListener.SERVICE_REGISTERED: {
1396 final RegistrationInfo info = (RegistrationInfo) obj;
1397 final String name = info.serviceName;
1398 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001399 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001400 break;
paulhu2b9ed952022-02-10 21:58:32 +08001401 }
1402 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001403 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001404 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1405 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001406 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001407 break;
paulhu2b9ed952022-02-10 21:58:32 +08001408 case IMDnsEventListener.SERVICE_RESOLVED: {
1409 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001410 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001411 final String fullName = info.serviceFullName;
1412 while (index < fullName.length() && fullName.charAt(index) != '.') {
1413 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001414 ++index;
1415 }
1416 ++index;
1417 }
paulhu2b9ed952022-02-10 21:58:32 +08001418 if (index >= fullName.length()) {
1419 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001420 break;
1421 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001422
paulhube186602022-04-12 07:18:23 +00001423 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001424 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001425 String type = rest.replace(".local.", "");
1426
Paul Hu30bd70d2023-02-07 13:20:56 +00001427 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001428 serviceInfo.setServiceName(name);
1429 serviceInfo.setServiceType(type);
1430 serviceInfo.setPort(info.port);
1431 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001432 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001433
Paul Hud44e1b72023-06-16 02:07:42 +00001434 stopResolveService(transactionId);
1435 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001436
Paul Hud44e1b72023-06-16 02:07:42 +00001437 final int transactionId2 = getUniqueId();
1438 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1439 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001440 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001441 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001442 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001443 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1444 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001445 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001446 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001447 }
1448 break;
paulhu2b9ed952022-02-10 21:58:32 +08001449 }
1450 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001451 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001452 stopResolveService(transactionId);
1453 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001454 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001455 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1456 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001457 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001458 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001459 break;
paulhu2b9ed952022-02-10 21:58:32 +08001460 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001461 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001462 stopGetAddrInfo(transactionId);
1463 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001464 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001465 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1466 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001467 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001468 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001469 break;
paulhu2b9ed952022-02-10 21:58:32 +08001470 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001471 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001472 final GetAddressInfo info = (GetAddressInfo) obj;
1473 final String address = info.address;
1474 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001475 InetAddress serviceHost = null;
1476 try {
paulhu2b9ed952022-02-10 21:58:32 +08001477 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001478 } catch (UnknownHostException e) {
1479 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1480 }
1481
1482 // If the resolved service is on an interface without a network, consider it
1483 // as a failure: it would not be usable by apps as they would need
1484 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001485 if (netId != NETID_UNSET && serviceHost != null) {
1486 clientInfo.mResolvedService.setHost(serviceHost);
1487 setServiceNetworkForCallback(clientInfo.mResolvedService,
1488 netId, info.interfaceIdx);
1489 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001490 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001491 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001492 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001493 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1494 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001495 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001496 }
Paul Hud44e1b72023-06-16 02:07:42 +00001497 stopGetAddrInfo(transactionId);
1498 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001499 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001500 break;
paulhu2b9ed952022-02-10 21:58:32 +08001501 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001502 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001503 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001504 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001505 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001506 }
Paul Hu019621e2023-01-13 23:26:49 +08001507
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001508 @Nullable
1509 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1510 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001511 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001512 final String[] typeArray = serviceInfo.getServiceType();
1513 final String joinedType;
1514 if (typeArray.length == 0
1515 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1516 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1517 + Arrays.toString(typeArray));
1518 return null;
1519 } else {
1520 joinedType = TextUtils.join(".",
1521 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1522 }
1523 final String serviceType;
1524 switch (code) {
1525 case NsdManager.SERVICE_FOUND:
1526 case NsdManager.SERVICE_LOST:
1527 // For consistency with historical behavior, discovered service types have
1528 // a dot at the end.
1529 serviceType = joinedType + ".";
1530 break;
1531 case RESOLVE_SERVICE_SUCCEEDED:
1532 // For consistency with historical behavior, resolved service types have
1533 // a dot at the beginning.
1534 serviceType = "." + joinedType;
1535 break;
1536 default:
1537 serviceType = joinedType;
1538 break;
1539 }
Paul Hu019621e2023-01-13 23:26:49 +08001540 final String serviceName = serviceInfo.getServiceInstanceName();
1541 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1542 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001543 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1544 // network for Tethering interface. In other words, the network == null means the
1545 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001546 setServiceNetworkForCallback(
1547 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001548 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001549 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001550 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Kangping Dongcd350182023-12-12 17:50:34 +08001551 servInfo.setExpirationTime(serviceInfo.getExpirationTime());
Paul Hu019621e2023-01-13 23:26:49 +08001552 return servInfo;
1553 }
1554
1555 private boolean handleMdnsDiscoveryManagerEvent(
1556 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001557 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001558 if (clientInfo == null) {
1559 Log.e(TAG, String.format(
1560 "id %d for %d has no client mapping", transactionId, code));
1561 return false;
1562 }
1563
1564 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001565 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001566 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1567 if (request == null) {
1568 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1569 return false;
1570 }
1571
1572 // Deal with the discovery sent callback
1573 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1574 request.onQuerySent();
1575 return true;
1576 }
1577
1578 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001579 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1580 // Errors are already logged if null
1581 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001582 mServiceLogs.log(String.format(
1583 "MdnsDiscoveryManager event code=%s transactionId=%d",
1584 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001585 switch (code) {
1586 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001587 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001588 break;
1589 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001590 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001591 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001592 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1593 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001594 info.setPort(serviceInfo.getPort());
1595
1596 Map<String, String> attrs = serviceInfo.getAttributes();
1597 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1598 final String key = kv.getKey();
1599 try {
1600 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1601 } catch (IllegalArgumentException e) {
1602 Log.e(TAG, "Invalid attribute", e);
1603 }
1604 }
Handa Wang096e32e2024-01-14 08:21:28 +00001605 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001606 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001607 if (addresses.size() != 0) {
1608 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001609 request.setServiceFromCache(event.mIsServiceFromCache);
1610 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001611 } else {
1612 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001613 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001614 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1615 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001616 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001617 }
1618
1619 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001620 if (!(request instanceof DiscoveryManagerRequest)) {
1621 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1622 break;
1623 }
Paul Hud44e1b72023-06-16 02:07:42 +00001624 stopDiscoveryManagerRequest(
1625 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001626 break;
1627 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001628 case NsdManager.SERVICE_UPDATED: {
1629 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1630 info.setPort(serviceInfo.getPort());
1631
1632 Map<String, String> attrs = serviceInfo.getAttributes();
1633 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1634 final String key = kv.getKey();
1635 try {
1636 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1637 } catch (IllegalArgumentException e) {
1638 Log.e(TAG, "Invalid attribute", e);
1639 }
1640 }
1641
Handa Wang096e32e2024-01-14 08:21:28 +00001642 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001643 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001644 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001645 clientInfo.onServiceUpdated(clientRequestId, info, request);
1646 // Set the ServiceFromCache flag only if the service is actually being
1647 // retrieved from the cache. This flag should not be overridden by later
1648 // service updates, which may not be cached.
1649 if (event.mIsServiceFromCache) {
1650 request.setServiceFromCache(true);
1651 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001652 break;
1653 }
1654 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001655 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001656 break;
Paul Hu019621e2023-01-13 23:26:49 +08001657 default:
1658 return false;
1659 }
1660 return true;
1661 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001662 }
1663 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001664
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001665 @NonNull
1666 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1667 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1668 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1669 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1670 for (String ipv4Address : v4Addrs) {
1671 try {
1672 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1673 } catch (IllegalArgumentException e) {
1674 Log.wtf(TAG, "Invalid ipv4 address", e);
1675 }
1676 }
1677 for (String ipv6Address : v6Addrs) {
1678 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001679 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1680 ipv6Address);
1681 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1682 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001683 Log.wtf(TAG, "Invalid ipv6 address", e);
1684 }
1685 }
1686 return addresses;
1687 }
1688
Handa Wang096e32e2024-01-14 08:21:28 +00001689 @NonNull
1690 private static String getHostname(@NonNull MdnsServiceInfo serviceInfo) {
1691 String[] hostname = serviceInfo.getHostName();
1692 // Strip the "local" top-level domain.
1693 if (hostname.length >= 2 && hostname[hostname.length - 1].equals("local")) {
1694 hostname = Arrays.copyOf(hostname, hostname.length - 1);
1695 }
1696 return String.join(".", hostname);
1697 }
1698
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001699 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1700 switch (netId) {
1701 case NETID_UNSET:
1702 info.setNetwork(null);
1703 break;
1704 case INetd.LOCAL_NET_ID:
1705 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1706 // visible / usable for apps, so do not return it. Store the interface
1707 // index instead, so at least if the client tries to resolve the service
1708 // with that NsdServiceInfo, it will be done on the same interface.
1709 // If they recreate the NsdServiceInfo themselves, resolution would be
1710 // done on all interfaces as before T, which should also work.
1711 info.setNetwork(null);
1712 info.setInterfaceIndex(ifaceIdx);
1713 break;
1714 default:
1715 info.setNetwork(new Network(netId));
1716 }
1717 }
1718
paulhube186602022-04-12 07:18:23 +00001719 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1720 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1721 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1722 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1723 private String unescape(String s) {
1724 StringBuilder sb = new StringBuilder(s.length());
1725 for (int i = 0; i < s.length(); ++i) {
1726 char c = s.charAt(i);
1727 if (c == '\\') {
1728 if (++i >= s.length()) {
1729 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1730 break;
1731 }
1732 c = s.charAt(i);
1733 if (c != '.' && c != '\\') {
1734 if (i + 2 >= s.length()) {
1735 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1736 break;
1737 }
1738 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1739 + (s.charAt(i + 2) - '0'));
1740 i += 2;
1741 }
1742 }
1743 sb.append(c);
1744 }
1745 return sb.toString();
1746 }
1747
Paul Hu7445e3d2023-03-03 15:14:00 +08001748 /**
1749 * Check the given service type is valid and construct it to a service type
1750 * which can use for discovery / resolution service.
1751 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001752 * <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 +08001753 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1754 * underscore; they are alphanumerical characters or dashes or underscore, except the
1755 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1756 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001757 * <p>The subtypes may also be specified with a comma after the service type, for example
1758 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001759 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001760 * @param serviceType the request service type for discovery / resolution service
1761 * @return constructed service type or null if the given service type is invalid.
1762 */
1763 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001764 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001765 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001766 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001767 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1768 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001769 final String queryType = matcher.group(2);
1770 // Use the subtype at the beginning
1771 if (matcher.group(1) != null) {
1772 return new Pair<>(queryType, List.of(matcher.group(1)));
1773 }
1774 // Use the subtypes at the end
1775 final String subTypesStr = matcher.group(3);
1776 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1777 final String[] subTypes = subTypesStr.substring(1).split(",");
1778 return new Pair<>(queryType, List.of(subTypes));
1779 }
1780
1781 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001782 }
1783
Handa Wang096e32e2024-01-14 08:21:28 +00001784 /**
1785 * Checks if the hostname is valid.
1786 *
1787 * <p>For now NsdService only allows single-label hostnames conforming to RFC 1035. In other
1788 * words, the hostname should be at most 63 characters long and it only contains letters, digits
1789 * and hyphens.
1790 */
1791 public static boolean checkHostname(@Nullable String hostname) {
1792 if (hostname == null) {
1793 return true;
1794 }
1795 String HOSTNAME_REGEX = "^[a-zA-Z]([a-zA-Z0-9-_]{0,61}[a-zA-Z0-9])?$";
1796 return Pattern.compile(HOSTNAME_REGEX).matcher(hostname).matches();
1797 }
1798
Kangping Dong5af24b62023-12-10 21:41:16 +08001799 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1800 private static boolean checkSubtypeLabel(String subtype) {
Remi NGUYEN VAN629234c2024-02-08 18:27:45 +09001801 return Pattern.compile("^" + SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
Kangping Dong5af24b62023-12-10 21:41:16 +08001802 }
1803
Hugo Benichi803a2f02017-04-24 11:35:06 +09001804 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001805 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001806 this(ctx, handler, cleanupDelayMs, new Dependencies());
1807 }
1808
1809 @VisibleForTesting
1810 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001811 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001812 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001813 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001814 mNsdStateMachine.start();
Ken Chen80c9f6f2023-11-15 18:24:54 +08001815 // It can fail on V+ device since mdns native service provided by netd is removed.
1816 mMDnsManager = SdkLevel.isAtLeastV() ? null : ctx.getSystemService(MDnsManager.class);
paulhu2b9ed952022-02-10 21:58:32 +08001817 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001818 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001819
Paul Hu14667de2023-04-17 22:42:47 +08001820 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001821 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001822 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001823 // address events are received. When the netlink monitor starts, any IP addresses already
1824 // on the interfaces will not be seen. In practice, the network will not connect at boot
1825 // time As a result, all the netlink message should be observed if the netlink monitor
1826 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001827 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001828
1829 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1830 // startBootstrapServices).
1831 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1832 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1833 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1834 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1835 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1836 mRunningAppActiveImportanceCutoff);
1837
Paul Hu11a883d2023-12-14 07:36:44 +00001838 mMdnsFeatureFlags = new MdnsFeatureFlags.Builder()
Paul Huf3fe3332023-10-16 17:13:25 +08001839 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1840 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1841 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1842 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001843 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1844 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001845 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1846 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001847 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1848 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001849 .setIsUnicastReplyEnabled(mDeps.isFeatureEnabled(
1850 mContext, MdnsFeatureFlags.NSD_UNICAST_REPLY_ENABLED))
Paul Hu11a883d2023-12-14 07:36:44 +00001851 .setIsAggressiveQueryModeEnabled(mDeps.isFeatureEnabled(
1852 mContext, MdnsFeatureFlags.NSD_AGGRESSIVE_QUERY_MODE))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001853 .setOverrideProvider(flag -> mDeps.isFeatureEnabled(
1854 mContext, FORCE_ENABLE_FLAG_FOR_TEST_PREFIX + flag))
Paul Huf3fe3332023-10-16 17:13:25 +08001855 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001856 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001857 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hu11a883d2023-12-14 07:36:44 +00001858 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), mMdnsFeatureFlags);
Paul Hu14667de2023-04-17 22:42:47 +08001859 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Hu11a883d2023-12-14 07:36:44 +00001860 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"),
1861 mMdnsFeatureFlags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001862 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1863 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu11a883d2023-12-14 07:36:44 +00001864 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"),
1865 mMdnsFeatureFlags, mContext);
Paul Hu777ed052023-06-19 13:35:15 +00001866 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001867 }
1868
1869 /**
1870 * Dependencies of NsdService, for injection in tests.
1871 */
1872 @VisibleForTesting
1873 public static class Dependencies {
1874 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001875 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001876 *
1877 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001878 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001879 */
1880 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001881 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001882 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001883 }
1884
1885 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001886 * Check whether the MdnsAdvertiser feature is enabled.
1887 *
1888 * @param context The global context information about an app environment.
1889 * @return true if the MdnsAdvertiser feature is enabled.
1890 */
1891 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001892 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001893 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001894 }
1895
1896 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001897 * Get the type allowlist flag value.
1898 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1899 */
1900 @Nullable
1901 public String getTypeAllowlistFlags() {
1902 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1903 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1904 }
1905
1906 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001907 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001908 */
1909 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001910 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001911 }
1912
1913 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001914 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1915 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001916 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1917 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001918 }
1919
1920 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001921 * @see MdnsDiscoveryManager
1922 */
1923 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001924 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001925 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1926 @NonNull MdnsFeatureFlags featureFlags) {
1927 return new MdnsDiscoveryManager(
1928 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001929 }
1930
1931 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001932 * @see MdnsAdvertiser
1933 */
1934 public MdnsAdvertiser makeMdnsAdvertiser(
1935 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001936 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001937 MdnsFeatureFlags featureFlags, Context context) {
1938 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags, context);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001939 }
1940
1941 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001942 * @see MdnsSocketProvider
1943 */
Paul Hu14667de2023-04-17 22:42:47 +08001944 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001945 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1946 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1947 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1948 }
1949
1950 /**
1951 * @see DeviceConfig#getInt(String, String, int)
1952 */
1953 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1954 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1955 }
1956
1957 /**
1958 * @see Binder#getCallingUid()
1959 */
1960 public int getCallingUid() {
1961 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001962 }
Paul Hu777ed052023-06-19 13:35:15 +00001963
1964 /**
1965 * @see NetworkNsdReportedMetrics
1966 */
Paul Hu508a0122023-09-11 15:31:33 +08001967 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1968 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001969 }
1970
1971 /**
1972 * @see MdnsUtils.Clock
1973 */
1974 public Clock makeClock() {
1975 return new Clock();
1976 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001977 }
1978
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001979 /**
1980 * Return whether a type is allowlisted to use the Java backend.
1981 * @param type The service type
1982 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1983 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1984 */
1985 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1986 @NonNull String flagPrefix) {
1987 if (type == null) return false;
1988 final String typesConfig = mDeps.getTypeAllowlistFlags();
1989 if (TextUtils.isEmpty(typesConfig)) return false;
1990
1991 final String mappingPrefix = type + ":";
1992 String mappedFlag = null;
1993 for (String mapping : TextUtils.split(typesConfig, ",")) {
1994 if (mapping.startsWith(mappingPrefix)) {
1995 mappedFlag = mapping.substring(mappingPrefix.length());
1996 break;
1997 }
1998 }
1999
2000 if (mappedFlag == null) return false;
2001
2002 return mDeps.isFeatureEnabled(mContext,
2003 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
2004 }
2005
2006 private boolean useDiscoveryManagerForType(@Nullable String type) {
2007 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
2008 }
2009
2010 private boolean useAdvertiserForType(@Nullable String type) {
2011 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
2012 }
2013
paulhu1b35e822022-04-08 14:48:41 +08002014 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002015 HandlerThread thread = new HandlerThread(TAG);
2016 thread.start();
2017 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08002018 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002019 return service;
2020 }
2021
paulhu2b9ed952022-02-10 21:58:32 +08002022 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
2023 private final StateMachine mStateMachine;
2024
2025 MDnsEventCallback(StateMachine sm) {
2026 mStateMachine = sm;
2027 }
2028
2029 @Override
2030 public void onServiceRegistrationStatus(final RegistrationInfo status) {
2031 mStateMachine.sendMessage(
2032 MDNS_SERVICE_EVENT, status.result, status.id, status);
2033 }
2034
2035 @Override
2036 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
2037 mStateMachine.sendMessage(
2038 MDNS_SERVICE_EVENT, status.result, status.id, status);
2039 }
2040
2041 @Override
2042 public void onServiceResolutionStatus(final ResolutionInfo status) {
2043 mStateMachine.sendMessage(
2044 MDNS_SERVICE_EVENT, status.result, status.id, status);
2045 }
2046
2047 @Override
2048 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
2049 mStateMachine.sendMessage(
2050 MDNS_SERVICE_EVENT, status.result, status.id, status);
2051 }
2052
2053 @Override
2054 public int getInterfaceVersion() throws RemoteException {
2055 return this.VERSION;
2056 }
2057
2058 @Override
2059 public String getInterfaceHash() throws RemoteException {
2060 return this.HASH;
2061 }
2062 }
2063
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002064 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
2065 final String targetInterface = offloadEngineInfo.mInterfaceName;
2066 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
2067 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
2068 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
2069 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
2070 try {
2071 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
2072 } catch (RemoteException e) {
2073 // Can happen in regular cases, do not log a stacktrace
2074 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
2075 }
2076 }
2077 }
2078
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002079 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
2080 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
2081 final int count = mOffloadEngines.beginBroadcast();
2082 try {
2083 for (int i = 0; i < count; i++) {
2084 final OffloadEngineInfo offloadEngineInfo =
2085 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
2086 final String interfaceName = offloadEngineInfo.mInterfaceName;
2087 if (!targetInterfaceName.equals(interfaceName)
2088 || ((offloadEngineInfo.mOffloadType
2089 & offloadServiceInfo.getOffloadType()) == 0)) {
2090 continue;
2091 }
2092 try {
2093 if (isRemove) {
2094 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
2095 offloadServiceInfo);
2096 } else {
2097 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
2098 offloadServiceInfo);
2099 }
2100 } catch (RemoteException e) {
2101 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002102 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002103 }
2104 }
2105 } finally {
2106 mOffloadEngines.finishBroadcast();
2107 }
2108 }
2109
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002110 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002111 // TODO: add a callback to notify when a service is being added on each interface (as soon
2112 // as probing starts), and call mOffloadCallbacks. This callback is for
2113 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2114
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002115 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002116 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2117 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2118 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002119 if (clientInfo == null) return;
2120
Paul Hud44e1b72023-06-16 02:07:42 +00002121 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2122 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002123
Handa Wang096e32e2024-01-14 08:21:28 +00002124 // onRegisterServiceSucceeded only has the service name and hostname in its info. This
2125 // aligns with historical behavior.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002126 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Handa Wang096e32e2024-01-14 08:21:28 +00002127 cbInfo.setHostname(registeredInfo.getHostname());
Paul Hu777ed052023-06-19 13:35:15 +00002128 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002129 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002130 }
2131
2132 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002133 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2134 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002135 if (clientInfo == null) return;
2136
Paul Hud44e1b72023-06-16 02:07:42 +00002137 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2138 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002139 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002140 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2141 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002142 }
2143
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002144 @Override
2145 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2146 @NonNull OffloadServiceInfo offloadServiceInfo) {
2147 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2148 }
2149
2150 @Override
2151 public void onOffloadStop(@NonNull String interfaceName,
2152 @NonNull OffloadServiceInfo offloadServiceInfo) {
2153 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2154 }
2155
Paul Hud44e1b72023-06-16 02:07:42 +00002156 private ClientInfo getClientInfoOrLog(int transactionId) {
2157 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002158 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002159 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002160 }
2161 return clientInfo;
2162 }
2163
Paul Hud44e1b72023-06-16 02:07:42 +00002164 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2165 final int clientRequestId = info.getClientRequestId(transactionId);
2166 if (clientRequestId < 0) {
2167 Log.e(TAG, String.format(
2168 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002169 }
Paul Hud44e1b72023-06-16 02:07:42 +00002170 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002171 }
2172 }
2173
Paul Hu2e0a88c2023-03-09 16:05:01 +08002174 private static class ConnectorArgs {
2175 @NonNull public final NsdServiceConnector connector;
2176 @NonNull public final INsdManagerCallback callback;
2177 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002178 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002179
2180 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002181 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002182 this.connector = connector;
2183 this.callback = callback;
2184 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002185 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002186 }
2187 }
2188
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002189 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002190 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002191 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002192 final int uid = mDeps.getCallingUid();
2193 if (cb == null) {
2194 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2195 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002196 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002197 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002198 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002199 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002200 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002201 }
2202
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002203 private static class ListenerArgs {
2204 public final NsdServiceConnector connector;
2205 public final NsdServiceInfo serviceInfo;
2206 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2207 this.connector = connector;
2208 this.serviceInfo = serviceInfo;
2209 }
2210 }
2211
Yuyang Huang86d083f2023-12-12 19:56:41 +09002212 private static class AdvertisingArgs {
2213 public final NsdServiceConnector connector;
2214 public final AdvertisingRequest advertisingRequest;
2215
2216 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2217 this.connector = connector;
2218 this.advertisingRequest = advertisingRequest;
2219 }
2220 }
2221
Kangping Dong1f1a3792023-12-10 22:05:04 +08002222 private static final class DiscoveryArgs {
2223 public final NsdServiceConnector connector;
2224 public final DiscoveryRequest discoveryRequest;
2225 DiscoveryArgs(NsdServiceConnector connector, DiscoveryRequest discoveryRequest) {
2226 this.connector = connector;
2227 this.discoveryRequest = discoveryRequest;
2228 }
2229 }
2230
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002231 private class NsdServiceConnector extends INsdServiceConnector.Stub
2232 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002233
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002234 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002235 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2236 throws RemoteException {
Handa Wang096e32e2024-01-14 08:21:28 +00002237 NsdManager.checkServiceInfoForRegistration(advertisingRequest.getServiceInfo());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002238 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2239 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002240 new AdvertisingArgs(this, advertisingRequest)
2241 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002242 }
2243
2244 @Override
2245 public void unregisterService(int listenerKey) {
2246 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2247 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002248 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002249 }
2250
2251 @Override
Kangping Dong1f1a3792023-12-10 22:05:04 +08002252 public void discoverServices(int listenerKey, DiscoveryRequest discoveryRequest) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002253 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2254 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
Kangping Dong1f1a3792023-12-10 22:05:04 +08002255 new DiscoveryArgs(this, discoveryRequest)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002256 }
2257
2258 @Override
2259 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002260 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2261 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002262 }
2263
2264 @Override
2265 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2266 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2267 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2268 new ListenerArgs(this, serviceInfo)));
2269 }
2270
2271 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002272 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002273 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2274 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002275 }
2276
2277 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002278 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2279 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2280 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2281 new ListenerArgs(this, serviceInfo)));
2282 }
2283
2284 @Override
2285 public void unregisterServiceInfoCallback(int listenerKey) {
2286 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2287 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002288 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002289 }
2290
2291 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002292 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002293 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2294 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002295 }
2296
2297 @Override
2298 public void binderDied() {
2299 mNsdStateMachine.sendMessage(
2300 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002301
2302 }
2303
2304 @Override
2305 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2306 @OffloadEngine.OffloadCapability long offloadCapabilities,
2307 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002308 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002309 Objects.requireNonNull(ifaceName);
2310 Objects.requireNonNull(cb);
2311 mNsdStateMachine.sendMessage(
2312 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2313 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2314 offloadTypes)));
2315 }
2316
2317 @Override
2318 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002319 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002320 Objects.requireNonNull(cb);
2321 mNsdStateMachine.sendMessage(
2322 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002323 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002324
2325 private static void checkOffloadEnginePermission(Context context) {
2326 if (!SdkLevel.isAtLeastT()) {
2327 throw new SecurityException("API is not available in before API level 33");
2328 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002329
Ken Chena7bae552023-12-27 11:40:57 +08002330 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2331 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2332
2333 if (SdkLevel.isAtLeastV()) {
2334 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2335 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2336 } else if (SdkLevel.isAtLeastU()) {
2337 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2338 // permission instead.
2339 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002340 }
2341
Junyu Lai71b51532024-02-01 10:39:01 +08002342 if (PermissionUtils.hasAnyPermissionOf(context,
Ken Chena7bae552023-12-27 11:40:57 +08002343 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002344 return;
2345 }
2346 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002347 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002348 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002349 }
2350
Hugo Benichi912db992017-04-24 16:41:03 +09002351 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002352 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002353 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002354 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2355 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002356 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002357 }
2358
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002359 private int getUniqueId() {
2360 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2361 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002362 }
2363
Paul Hud44e1b72023-06-16 02:07:42 +00002364 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002365 if (mMDnsManager == null) {
2366 Log.wtf(TAG, "registerService: mMDnsManager is null");
2367 return false;
2368 }
2369
Hugo Benichi6d706442017-04-24 16:19:58 +09002370 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002371 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002372 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002373 String name = service.getServiceName();
2374 String type = service.getServiceType();
2375 int port = service.getPort();
2376 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002377 final int registerInterface = getNetworkInterfaceIndex(service);
2378 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002379 Log.e(TAG, "Interface to register service on not found");
2380 return false;
2381 }
Paul Hud44e1b72023-06-16 02:07:42 +00002382 return mMDnsManager.registerService(
2383 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002384 }
2385
Paul Hud44e1b72023-06-16 02:07:42 +00002386 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002387 if (mMDnsManager == null) {
2388 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2389 return false;
2390 }
Paul Hud44e1b72023-06-16 02:07:42 +00002391 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002392 }
2393
Kangping Dong1f1a3792023-12-10 22:05:04 +08002394 private boolean discoverServices(int transactionId, DiscoveryRequest discoveryRequest) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002395 if (mMDnsManager == null) {
2396 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2397 return false;
2398 }
2399
Kangping Dong1f1a3792023-12-10 22:05:04 +08002400 final String type = discoveryRequest.getServiceType();
2401 final int discoverInterface = getNetworkInterfaceIndex(discoveryRequest);
2402 if (discoveryRequest.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002403 Log.e(TAG, "Interface to discover service on not found");
2404 return false;
2405 }
Paul Hud44e1b72023-06-16 02:07:42 +00002406 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002407 }
2408
Paul Hud44e1b72023-06-16 02:07:42 +00002409 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002410 if (mMDnsManager == null) {
2411 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2412 return false;
2413 }
Paul Hud44e1b72023-06-16 02:07:42 +00002414 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002415 }
2416
Paul Hud44e1b72023-06-16 02:07:42 +00002417 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002418 if (mMDnsManager == null) {
2419 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2420 return false;
2421 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002422 final String name = service.getServiceName();
2423 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002424 final int resolveInterface = getNetworkInterfaceIndex(service);
2425 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002426 Log.e(TAG, "Interface to resolve service on not found");
2427 return false;
2428 }
Paul Hud44e1b72023-06-16 02:07:42 +00002429 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002430 }
2431
2432 /**
2433 * Guess the interface to use to resolve or discover a service on a specific network.
2434 *
2435 * This is an imperfect guess, as for example the network may be gone or not yet fully
2436 * registered. This is fine as failing is correct if the network is gone, and a client
2437 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2438 * this is to support the legacy mdnsresponder implementation, which historically resolved
2439 * services on an unspecified network.
2440 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002441 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2442 final Network network = serviceInfo.getNetwork();
2443 if (network == null) {
2444 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2445 // provided by NsdService from discovery results, and the service was found on an
2446 // interface that has no app-usable Network).
2447 if (serviceInfo.getInterfaceIndex() != 0) {
2448 return serviceInfo.getInterfaceIndex();
2449 }
2450 return IFACE_IDX_ANY;
2451 }
Kangping Dong1f1a3792023-12-10 22:05:04 +08002452 return getNetworkInterfaceIndex(network);
2453 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002454
Kangping Dong1f1a3792023-12-10 22:05:04 +08002455 /**
2456 * Returns the interface to use to discover a service on a specific network, or {@link
2457 * IFACE_IDX_ANY} if no network is specified.
2458 */
2459 private int getNetworkInterfaceIndex(DiscoveryRequest discoveryRequest) {
2460 final Network network = discoveryRequest.getNetwork();
2461 if (network == null) {
2462 return IFACE_IDX_ANY;
2463 }
2464 return getNetworkInterfaceIndex(network);
2465 }
2466
2467 /**
2468 * Returns the interface of a specific network, or {@link IFACE_IDX_ANY} if no interface is
2469 * associated with {@code network}.
2470 */
2471 private int getNetworkInterfaceIndex(@NonNull Network network) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002472 String interfaceName = getNetworkInterfaceName(network);
2473 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002474 return IFACE_IDX_ANY;
2475 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002476 return getNetworkInterfaceIndexByName(interfaceName);
2477 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002478
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002479 private String getNetworkInterfaceName(@Nullable Network network) {
2480 if (network == null) {
2481 return null;
2482 }
2483 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2484 if (cm == null) {
2485 Log.wtf(TAG, "No ConnectivityManager");
2486 return null;
2487 }
2488 final LinkProperties lp = cm.getLinkProperties(network);
2489 if (lp == null) {
2490 return null;
2491 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002492 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002493 return lp.getInterfaceName();
2494 }
2495
2496 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002497 final NetworkInterface iface;
2498 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002499 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002500 } catch (SocketException e) {
2501 Log.e(TAG, "Error querying interface", e);
2502 return IFACE_IDX_ANY;
2503 }
2504
2505 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002506 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002507 return IFACE_IDX_ANY;
2508 }
2509
2510 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002511 }
2512
Paul Hud44e1b72023-06-16 02:07:42 +00002513 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002514 if (mMDnsManager == null) {
2515 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2516 return false;
2517 }
Paul Hud44e1b72023-06-16 02:07:42 +00002518 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002519 }
2520
Paul Hud44e1b72023-06-16 02:07:42 +00002521 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002522 if (mMDnsManager == null) {
2523 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2524 return false;
2525 }
Paul Hud44e1b72023-06-16 02:07:42 +00002526 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002527 }
2528
Paul Hud44e1b72023-06-16 02:07:42 +00002529 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002530 if (mMDnsManager == null) {
2531 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2532 return false;
2533 }
Paul Hud44e1b72023-06-16 02:07:42 +00002534 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002535 }
2536
2537 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002538 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08002539 if (!PermissionUtils.hasDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002540
Paul Hub2e67d32023-04-18 05:50:14 +00002541 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2542 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002543 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002544
2545 // Dump service and clients logs
2546 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002547 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002548 pw.increaseIndent();
2549 mServiceLogs.reverseDump(pw);
2550 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002551 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002552
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002553 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002554 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002555 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002556 private int mFoundServiceCount = 0;
2557 private int mLostServiceCount = 0;
2558 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002559 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002560 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002561
Paul Hu812e9212023-06-20 06:24:53 +00002562 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002563 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002564 mStartTimeMs = startTimeMs;
2565 }
2566
Paul Hu812e9212023-06-20 06:24:53 +00002567 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002568 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002569 }
Paul Hu812e9212023-06-20 06:24:53 +00002570
2571 public void onServiceFound(String serviceName) {
2572 mFoundServiceCount++;
2573 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2574 mServices.add(serviceName);
2575 }
2576 }
2577
2578 public void onServiceLost() {
2579 mLostServiceCount++;
2580 }
2581
2582 public int getFoundServiceCount() {
2583 return mFoundServiceCount;
2584 }
2585
2586 public int getLostServiceCount() {
2587 return mLostServiceCount;
2588 }
2589
2590 public int getServicesCount() {
2591 return mServices.size();
2592 }
Paul Hua6bc4632023-06-26 01:18:29 +00002593
2594 public void setServiceFromCache(boolean isServiceFromCache) {
2595 mIsServiceFromCache = isServiceFromCache;
2596 }
2597
2598 public boolean isServiceFromCache() {
2599 return mIsServiceFromCache;
2600 }
Paul Hubad6fe92023-07-24 21:25:22 +08002601
2602 public void onQuerySent() {
2603 mSentQueryCount++;
2604 }
2605
2606 public int getSentQueryCount() {
2607 return mSentQueryCount;
2608 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002609 }
2610
2611 private static class LegacyClientRequest extends ClientRequest {
2612 private final int mRequestCode;
2613
Paul Hu812e9212023-06-20 06:24:53 +00002614 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2615 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002616 mRequestCode = requestCode;
2617 }
2618 }
2619
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002620 private abstract static class JavaBackendClientRequest extends ClientRequest {
2621 @Nullable
2622 private final Network mRequestedNetwork;
2623
Paul Hu777ed052023-06-19 13:35:15 +00002624 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002625 long startTimeMs) {
2626 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002627 mRequestedNetwork = requestedNetwork;
2628 }
2629
2630 @Nullable
2631 public Network getRequestedNetwork() {
2632 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002633 }
2634 }
2635
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002636 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002637 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002638 long startTimeMs) {
2639 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002640 }
2641 }
2642
2643 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002644 @NonNull
2645 private final MdnsListener mListener;
2646
Paul Hud44e1b72023-06-16 02:07:42 +00002647 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002648 @Nullable Network requestedNetwork, long startTimeMs) {
2649 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002650 mListener = listener;
2651 }
2652 }
2653
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002654 /* Information tracked per client */
2655 private class ClientInfo {
2656
Remi NGUYEN VAN12a0c6a2024-02-09 18:24:29 +09002657 /**
2658 * Maximum number of requests (callbacks) for a client.
2659 *
2660 * 200 listeners should be more than enough for most use-cases: even if a client tries to
2661 * file callbacks for every service on a local network, there are generally much less than
2662 * 200 devices on a local network (a /24 only allows 255 IPv4 devices), and while some
2663 * devices may have multiple services, many devices do not advertise any.
2664 */
2665 private static final int MAX_LIMIT = 200;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002666 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002667 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002668 private NsdServiceInfo mResolvedService;
2669
Paul Hud44e1b72023-06-16 02:07:42 +00002670 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002671 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002672
Luke Huangf7277ed2021-07-12 21:15:10 +08002673 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002674 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002675 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002676 // The flag of using java backend if the client's target SDK >= U
2677 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002678 // Store client logs
2679 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002680 // Report the nsd metrics data
2681 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002682
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002683 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002684 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002685 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002686 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002687 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002688 mClientLogs = sharedLog;
2689 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002690 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002691 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002692
2693 @Override
2694 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002695 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002696 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002697 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002698 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2699 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002700 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002701 int clientRequestId = mClientRequests.keyAt(i);
2702 sb.append("clientRequestId ")
2703 .append(clientRequestId)
2704 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002705 .append(" type ").append(
2706 mClientRequests.valueAt(i).getClass().getSimpleName())
2707 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002708 }
2709 return sb.toString();
2710 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002711
Kangping Dongcd350182023-12-12 17:50:34 +08002712 public int getUid() {
2713 return mUid;
2714 }
2715
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002716 private boolean isPreSClient() {
2717 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002718 }
2719
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002720 private void setPreSClient() {
2721 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002722 }
2723
Paul Hu812e9212023-06-20 06:24:53 +00002724 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002725 final MdnsListener listener =
2726 ((DiscoveryManagerRequest) request).mListener;
2727 mMdnsDiscoveryManager.unregisterListener(
2728 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002729 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002730 }
2731
Dave Plattfeff2af2014-03-07 14:48:22 -08002732 // Remove any pending requests from the global map when we get rid of a client,
2733 // and send cancellations to the daemon.
2734 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002735 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002736 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002737 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002738 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002739 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002740 final int transactionId = request.mTransactionId;
2741 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002742 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002743 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2744 + " transactionId " + transactionId
2745 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002746 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002747
2748 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002749 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2750 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002751 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002752 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2753 request.getFoundServiceCount(),
2754 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002755 request.getServicesCount(),
2756 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002757 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002758 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002759 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002760 } else if (listener instanceof ServiceInfoListener) {
2761 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2762 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2763 request.getFoundServiceCount(),
2764 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002765 request.isServiceFromCache(),
2766 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002767 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002768 continue;
2769 }
2770
2771 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002772 final AdvertiserMetrics metrics =
2773 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002774 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002775 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002776 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2777 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2778 metrics.mConflictDuringProbingCount,
2779 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002780 continue;
2781 }
2782
2783 if (!(request instanceof LegacyClientRequest)) {
2784 throw new IllegalStateException("Unknown request type: " + request.getClass());
2785 }
2786
2787 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002788 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002789 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002790 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002791 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2792 request.getFoundServiceCount(),
2793 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002794 request.getServicesCount(),
2795 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002796 break;
2797 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002798 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002799 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002800 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002801 break;
2802 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002803 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002804 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002805 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2806 NO_PACKET /* repliedRequestsCount */,
2807 NO_PACKET /* sentPacketCount */,
2808 0 /* conflictDuringProbingCount */,
2809 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002810 break;
2811 default:
2812 break;
2813 }
2814 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002815 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002816 updateMulticastLock();
2817 }
2818
2819 /**
2820 * Returns true if this client has any Java backend request that requests one of the given
2821 * networks.
2822 */
2823 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2824 for (int i = 0; i < mClientRequests.size(); i++) {
2825 final ClientRequest req = mClientRequests.valueAt(i);
2826 if (!(req instanceof JavaBackendClientRequest)) {
2827 continue;
2828 }
2829 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2830 .getRequestedNetwork();
2831 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2832 return true;
2833 }
2834 }
2835 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002836 }
2837
Paul Hud44e1b72023-06-16 02:07:42 +00002838 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2839 // transaction id, return the corresponding client request id.
2840 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002841 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002842 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002843 return mClientRequests.keyAt(i);
2844 }
Christopher Lane74411222014-04-25 18:39:07 -07002845 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002846 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002847 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002848
Paul Hub2e67d32023-04-18 05:50:14 +00002849 private void log(String message) {
2850 mClientLogs.log(message);
2851 }
2852
Paul Hu508a0122023-09-11 15:31:33 +08002853 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2854 return !(request instanceof DiscoveryManagerRequest)
2855 && !(request instanceof AdvertiserClientRequest);
2856 }
2857
Kangping Dong1f1a3792023-12-10 22:05:04 +08002858 void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest,
Paul Hu508a0122023-09-11 15:31:33 +08002859 ClientRequest request) {
2860 mMetrics.reportServiceDiscoveryStarted(
2861 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002862 try {
Kangping Dong1f1a3792023-12-10 22:05:04 +08002863 mCb.onDiscoverServicesStarted(listenerKey, discoveryRequest);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002864 } catch (RemoteException e) {
2865 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2866 }
2867 }
Paul Hu508a0122023-09-11 15:31:33 +08002868 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2869 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2870 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002871 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002872
Paul Hu508a0122023-09-11 15:31:33 +08002873 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2874 int transactionId, long durationMs) {
2875 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002876 try {
2877 mCb.onDiscoverServicesFailed(listenerKey, error);
2878 } catch (RemoteException e) {
2879 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2880 }
2881 }
2882
Paul Hu812e9212023-06-20 06:24:53 +00002883 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2884 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002885 try {
2886 mCb.onServiceFound(listenerKey, info);
2887 } catch (RemoteException e) {
2888 Log.e(TAG, "Error calling onServiceFound(", e);
2889 }
2890 }
2891
Paul Hu812e9212023-06-20 06:24:53 +00002892 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2893 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002894 try {
2895 mCb.onServiceLost(listenerKey, info);
2896 } catch (RemoteException e) {
2897 Log.e(TAG, "Error calling onServiceLost(", e);
2898 }
2899 }
2900
2901 void onStopDiscoveryFailed(int listenerKey, int error) {
2902 try {
2903 mCb.onStopDiscoveryFailed(listenerKey, error);
2904 } catch (RemoteException e) {
2905 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2906 }
2907 }
2908
Paul Hu812e9212023-06-20 06:24:53 +00002909 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2910 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002911 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002912 request.mTransactionId,
2913 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2914 request.getFoundServiceCount(),
2915 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002916 request.getServicesCount(),
2917 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002918 try {
2919 mCb.onStopDiscoverySucceeded(listenerKey);
2920 } catch (RemoteException e) {
2921 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2922 }
2923 }
2924
Paul Hu508a0122023-09-11 15:31:33 +08002925 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2926 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2927 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002928 }
2929
Paul Hu508a0122023-09-11 15:31:33 +08002930 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2931 int transactionId, long durationMs) {
2932 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002933 try {
2934 mCb.onRegisterServiceFailed(listenerKey, error);
2935 } catch (RemoteException e) {
2936 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2937 }
2938 }
2939
Paul Hu508a0122023-09-11 15:31:33 +08002940 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2941 ClientRequest request) {
2942 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2943 request.mTransactionId,
2944 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002945 try {
2946 mCb.onRegisterServiceSucceeded(listenerKey, info);
2947 } catch (RemoteException e) {
2948 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2949 }
2950 }
2951
2952 void onUnregisterServiceFailed(int listenerKey, int error) {
2953 try {
2954 mCb.onUnregisterServiceFailed(listenerKey, error);
2955 } catch (RemoteException e) {
2956 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2957 }
2958 }
2959
Paul Hu508a0122023-09-11 15:31:33 +08002960 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002961 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002962 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2963 request.mTransactionId,
2964 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002965 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2966 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002967 try {
2968 mCb.onUnregisterServiceSucceeded(listenerKey);
2969 } catch (RemoteException e) {
2970 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2971 }
2972 }
2973
Paul Hu508a0122023-09-11 15:31:33 +08002974 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2975 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2976 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002977 }
2978
Paul Hu508a0122023-09-11 15:31:33 +08002979 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2980 int transactionId, long durationMs) {
2981 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002982 try {
2983 mCb.onResolveServiceFailed(listenerKey, error);
2984 } catch (RemoteException e) {
2985 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2986 }
2987 }
2988
Paul Hua6bc4632023-06-26 01:18:29 +00002989 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2990 ClientRequest request) {
2991 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002992 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002993 request.mTransactionId,
2994 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002995 request.isServiceFromCache(),
2996 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002997 try {
2998 mCb.onResolveServiceSucceeded(listenerKey, info);
2999 } catch (RemoteException e) {
3000 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
3001 }
3002 }
Paul Hub58deb72022-12-26 09:24:42 +00003003
3004 void onStopResolutionFailed(int listenerKey, int error) {
3005 try {
3006 mCb.onStopResolutionFailed(listenerKey, error);
3007 } catch (RemoteException e) {
3008 Log.e(TAG, "Error calling onStopResolutionFailed", e);
3009 }
3010 }
3011
Paul Hu60149052023-07-31 14:26:08 +08003012 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
3013 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08003014 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08003015 request.mTransactionId,
3016 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00003017 try {
3018 mCb.onStopResolutionSucceeded(listenerKey);
3019 } catch (RemoteException e) {
3020 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
3021 }
3022 }
Paul Hu18aeccc2022-12-27 08:48:48 +00003023
3024 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08003025 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00003026 try {
3027 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
3028 } catch (RemoteException e) {
3029 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
3030 }
3031 }
3032
Paul Huddce5912023-08-01 10:26:49 +08003033 void onServiceInfoCallbackRegistered(int transactionId) {
3034 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
3035 }
3036
3037 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
3038 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00003039 try {
3040 mCb.onServiceUpdated(listenerKey, info);
3041 } catch (RemoteException e) {
3042 Log.e(TAG, "Error calling onServiceUpdated", e);
3043 }
3044 }
3045
Paul Huddce5912023-08-01 10:26:49 +08003046 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
3047 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00003048 try {
3049 mCb.onServiceUpdatedLost(listenerKey);
3050 } catch (RemoteException e) {
3051 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
3052 }
3053 }
3054
Paul Huddce5912023-08-01 10:26:49 +08003055 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
3056 mMetrics.reportServiceInfoCallbackUnregistered(
3057 request.mTransactionId,
3058 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
3059 request.getFoundServiceCount(),
3060 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08003061 request.isServiceFromCache(),
3062 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00003063 try {
3064 mCb.onServiceInfoCallbackUnregistered(listenerKey);
3065 } catch (RemoteException e) {
3066 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
3067 }
3068 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07003069 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003070}