blob: cfb1a33390a77655e50247f398868c177184cd99 [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;
Paul Hu55f943e2024-02-20 03:04:17 +000096import com.android.net.module.util.HandlerUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090097import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080098import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000099import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800100import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900101import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900102import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800103import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +0900104import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900105import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800106import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800107import com.android.server.connectivity.mdns.MdnsSearchOptions;
108import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
109import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800110import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900111import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800112
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700113import java.io.FileDescriptor;
114import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900115import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700116import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900117import java.net.NetworkInterface;
118import java.net.SocketException;
119import java.net.UnknownHostException;
Kangping Dongcd350182023-12-12 17:50:34 +0800120import java.time.Duration;
Paul Hu2b865912023-03-06 14:27:53 +0800121import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900122import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800123import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900124import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700125import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800126import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800127import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800128import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900129import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000130import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800131import java.util.regex.Matcher;
132import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700133
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700134/**
135 * Network Service Discovery Service handles remote service discovery operation requests by
136 * implementing the INsdManager interface.
137 *
138 * @hide
139 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900140@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700141public class NsdService extends INsdManager.Stub {
142 private static final String TAG = "NsdService";
143 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900144 /**
145 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
146 * implementation.
147 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800148 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800149 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700150
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900151 /**
152 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
153 * implementation.
154 */
155 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
156
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900157 /**
158 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
159 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
160 *
161 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
162 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
163 *
164 * In which case the flags:
165 * "mdns_discovery_manager_allowlist_mytype_version",
166 * "mdns_advertiser_allowlist_mytype_version",
167 * "mdns_discovery_manager_allowlist_othertype_version",
168 * "mdns_advertiser_allowlist_othertype_version"
169 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
170 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900171 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900172 *
173 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
174 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
175 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
176 */
177 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
178
179 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
180 "mdns_discovery_manager_allowlist_";
181 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
182 "mdns_advertiser_allowlist_";
183 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
184
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +0900185 private static final String FORCE_ENABLE_FLAG_FOR_TEST_PREFIX = "test_";
Kangping Dong5af24b62023-12-10 21:41:16 +0800186
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900187 @VisibleForTesting
188 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
189 "mdns_config_running_app_active_importance_cutoff";
190 @VisibleForTesting
191 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
192 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
193 private final int mRunningAppActiveImportanceCutoff;
194
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900195 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000196 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900197 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000198 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
199 @VisibleForTesting
200 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800201 private static final int NO_SENT_QUERY_COUNT = 0;
202 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800203 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800204 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700205
Hugo Benichi32be63d2017-04-05 14:06:11 +0900206 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900207 private final NsdStateMachine mNsdStateMachine;
Ken Chen80c9f6f2023-11-15 18:24:54 +0800208 // It can be null on V+ device since mdns native service provided by netd is removed.
209 private final @Nullable MDnsManager mMDnsManager;
paulhu2b9ed952022-02-10 21:58:32 +0800210 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900211 @NonNull
212 private final Dependencies mDeps;
213 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800214 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900215 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800216 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900217 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800218 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900219 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900220 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000221 @NonNull
222 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800223 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800224 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800225 // state machine thread. If change this outside state machine, it will need to introduce
226 // synchronization.
227 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800228 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700229
230 /**
231 * Clients receiving asynchronous messages
232 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900233 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700234
Paul Hud44e1b72023-06-16 02:07:42 +0000235 /* A map from transaction(unique) id to client info */
236 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700237
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900238 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
239 @Nullable
240 private WifiManager.MulticastLock mHeldMulticastLock;
241 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
242 // (non-null), value is the requested Network (nullable)
243 @NonNull
244 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
245 @NonNull
246 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
247
Luke Huang05298582021-06-13 16:52:05 +0000248 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700249
Hugo Benichi32be63d2017-04-05 14:06:11 +0900250 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700251 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800252 // The count of the connected legacy clients.
253 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000254 // The number of client that ever connected.
255 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700256
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900257 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
258 new RemoteCallbackList<>();
Paul Hu11a883d2023-12-14 07:36:44 +0000259 @NonNull
260 private final MdnsFeatureFlags mMdnsFeatureFlags;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900261
262 private static class OffloadEngineInfo {
263 @NonNull final String mInterfaceName;
264 final long mOffloadCapabilities;
265 final long mOffloadType;
266 @NonNull final IOffloadEngine mOffloadEngine;
267
268 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
269 @NonNull String interfaceName, long capabilities, long offloadType) {
270 this.mOffloadEngine = offloadEngine;
271 this.mInterfaceName = interfaceName;
272 this.mOffloadCapabilities = capabilities;
273 this.mOffloadType = offloadType;
274 }
275 }
276
Paul Hu812e9212023-06-20 06:24:53 +0000277 @VisibleForTesting
278 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000279 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800280 protected final int mTransactionId;
281 @NonNull
Paul Hu23fa2022023-01-13 22:57:24 +0800282 protected final String mListenedServiceType;
283
Kangping Dong97b2adc2024-01-11 16:00:37 +0800284 MdnsListener(int clientRequestId, int transactionId, @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000285 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800286 mTransactionId = transactionId;
Paul Hu23fa2022023-01-13 22:57:24 +0800287 mListenedServiceType = listenedServiceType;
288 }
289
290 @NonNull
291 public String getListenedServiceType() {
292 return mListenedServiceType;
293 }
294
295 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000296 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
297 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800298
299 @Override
300 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
301
302 @Override
303 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
304
305 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000306 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
307 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800308
309 @Override
310 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
311
312 @Override
313 public void onSearchStoppedWithError(int error) { }
314
315 @Override
316 public void onSearchFailedToStart() { }
317
318 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800319 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
320 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800321
322 @Override
323 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
324 }
325
326 private class DiscoveryListener extends MdnsListener {
327
Paul Hud44e1b72023-06-16 02:07:42 +0000328 DiscoveryListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800329 @NonNull String listenServiceType) {
330 super(clientRequestId, transactionId, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800331 }
332
333 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000334 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
335 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800336 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
337 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000338 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800339 }
340
341 @Override
342 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800343 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
344 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000345 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800346 }
Paul Hubad6fe92023-07-24 21:25:22 +0800347
348 @Override
349 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
350 int sentQueryTransactionId) {
351 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
352 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
353 }
Paul Hu23fa2022023-01-13 22:57:24 +0800354 }
355
Paul Hu75069ed2023-01-14 00:31:09 +0800356 private class ResolutionListener extends MdnsListener {
357
Paul Hud44e1b72023-06-16 02:07:42 +0000358 ResolutionListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800359 @NonNull String listenServiceType) {
360 super(clientRequestId, transactionId, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800361 }
362
363 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000364 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800365 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
366 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000367 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800368 }
Paul Hubad6fe92023-07-24 21:25:22 +0800369
370 @Override
371 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
372 int sentQueryTransactionId) {
373 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
374 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
375 }
Paul Hu75069ed2023-01-14 00:31:09 +0800376 }
377
Paul Hu30bd70d2023-02-07 13:20:56 +0000378 private class ServiceInfoListener extends MdnsListener {
379
Paul Hud44e1b72023-06-16 02:07:42 +0000380 ServiceInfoListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800381 @NonNull String listenServiceType) {
382 super(clientRequestId, transactionId, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
384
385 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000386 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
387 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000388 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
389 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000390 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000391 }
392
393 @Override
394 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
395 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
396 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000397 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000398 }
399
400 @Override
401 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
402 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
403 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000404 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000405 }
Paul Hubad6fe92023-07-24 21:25:22 +0800406
407 @Override
408 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
409 int sentQueryTransactionId) {
410 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
411 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
412 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000413 }
414
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900415 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
416 @Override
417 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
418 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
419 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
420 // filtering on such interfaces, so taking the multicast lock is not necessary to
421 // disable APF filtering of multicast.
422 if (socketNetwork == null
423 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
424 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
425 return;
426 }
427
428 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
429 updateMulticastLock();
430 }
431 }
432
433 @Override
434 public void onSocketDestroyed(@Nullable Network socketNetwork,
435 @NonNull MdnsInterfaceSocket socket) {
436 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
437 updateMulticastLock();
438 }
439 }
440 }
441
442 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
443 private final Handler mHandler;
444
445 private UidImportanceListener(Handler handler) {
446 mHandler = handler;
447 }
448
449 @Override
450 public void onUidImportance(int uid, int importance) {
451 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
452 }
453 }
454
455 private void handleUidImportanceChanged(int uid, int importance) {
456 // Lower importance values are more "important"
457 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
458 ? mRunningAppActiveUids.add(uid)
459 : mRunningAppActiveUids.remove(uid);
460 if (modified) {
461 updateMulticastLock();
462 }
463 }
464
465 /**
466 * Take or release the lock based on updated internal state.
467 *
468 * This determines whether the lock needs to be held based on
469 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
470 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
471 * updated.
472 */
473 private void updateMulticastLock() {
474 final int needsLockUid = getMulticastLockNeededUid();
475 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
476 final WifiManager wm = mContext.getSystemService(WifiManager.class);
477 if (wm == null) {
478 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
479 return;
480 }
481 mHeldMulticastLock = wm.createMulticastLock(TAG);
482 mHeldMulticastLock.acquire();
483 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
484 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
485 mHeldMulticastLock.release();
486 mHeldMulticastLock = null;
487 mServiceLogs.log("Released multicast lock");
488 }
489 }
490
491 /**
492 * @return The UID of an app requiring the multicast lock, or -1 if none.
493 */
494 private int getMulticastLockNeededUid() {
495 if (mWifiLockRequiredNetworks.size() == 0) {
496 // Return early if NSD is not active, or not on any relevant network
497 return -1;
498 }
Paul Hud44e1b72023-06-16 02:07:42 +0000499 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
500 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900501 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
502 // Ignore non-active UIDs
503 continue;
504 }
505
506 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
507 return clientInfo.mUid;
508 }
509 }
510 return -1;
511 }
512
Paul Hu019621e2023-01-13 23:26:49 +0800513 /**
514 * Data class of mdns service callback information.
515 */
516 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000517 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800518 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800519 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000520 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800521
Paul Hubad6fe92023-07-24 21:25:22 +0800522 MdnsEvent(int clientRequestId) {
523 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
524 }
525
526 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000527 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
528 }
529
Paul Hubad6fe92023-07-24 21:25:22 +0800530 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000531 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000532 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800533 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000534 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800535 }
536 }
537
Paul Hu77c11182023-10-23 16:17:32 +0800538 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700539 private class NsdStateMachine extends StateMachine {
540
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700541 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700542
543 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700544 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900545 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700546 }
547
Luke Huang92860f92021-06-23 06:29:30 +0000548 private void maybeStartDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000549 if (mIsDaemonStarted) {
550 if (DBG) Log.d(TAG, "Daemon is already started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800551 return;
552 }
553
Paul Hu4a87ed42024-01-10 08:58:30 +0000554 if (mMDnsManager == null) {
555 Log.wtf(TAG, "maybeStartDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800556 return;
557 }
558 mMDnsManager.registerEventListener(mMDnsEventCallback);
559 mMDnsManager.startDaemon();
560 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000561 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000562 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000563 }
564
paulhu2b9ed952022-02-10 21:58:32 +0800565 private void maybeStopDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000566 if (!mIsDaemonStarted) {
567 if (DBG) Log.d(TAG, "Daemon has not been started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800568 return;
569 }
570
Paul Hu4a87ed42024-01-10 08:58:30 +0000571 if (mMDnsManager == null) {
572 Log.wtf(TAG, "maybeStopDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800573 return;
574 }
575 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
576 mMDnsManager.stopDaemon();
577 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000578 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800579 }
580
Luke Huang92860f92021-06-23 06:29:30 +0000581 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000582 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000583 }
584
585 private void scheduleStop() {
586 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
587 }
588 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800589 // The native daemon should stay alive and can't be cleanup
590 // if any legacy client connected.
591 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000592 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000593 }
594 }
595
Luke Huang92860f92021-06-23 06:29:30 +0000596 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000597 this.removeMessages(NsdManager.DAEMON_CLEANUP);
598 }
599
Paul Hu23fa2022023-01-13 22:57:24 +0800600 private void maybeStartMonitoringSockets() {
601 if (mIsMonitoringSocketsStarted) {
602 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
603 return;
604 }
605
606 mMdnsSocketProvider.startMonitoringSockets();
607 mIsMonitoringSocketsStarted = true;
608 }
609
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900610 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
611 if (!mIsMonitoringSocketsStarted) return;
612 if (isAnyRequestActive()) return;
613
Paul Hu58f20602023-02-18 11:41:07 +0800614 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800615 mIsMonitoringSocketsStarted = false;
616 }
617
Hugo Benichi803a2f02017-04-24 11:35:06 +0900618 NsdStateMachine(String name, Handler handler) {
619 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800620 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800621 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900622 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700623 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700624 }
625
Irfan Sheriff75006652012-04-17 23:15:29 -0700626 class EnabledState extends State {
627 @Override
628 public void enter() {
629 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700630 }
631
632 @Override
633 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000634 // TODO: it is incorrect to stop the daemon without expunging all requests
635 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000636 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700637 }
638
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700639 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900640 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800641 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700642 return true;
643 }
644 return false;
645 }
646
Paul Hu508a0122023-09-11 15:31:33 +0800647 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000648 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800649 final LegacyClientRequest request =
650 new LegacyClientRequest(transactionId, what, startTimeMs);
651 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000652 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000653 // Remove the cleanup event because here comes a new request.
654 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800655 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700656 }
657
Paul Hud44e1b72023-06-16 02:07:42 +0000658 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900659 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000660 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000661 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000662 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900663 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800664 }
665
Paul Hud44e1b72023-06-16 02:07:42 +0000666 private void removeRequestMap(
667 int clientRequestId, int transactionId, ClientInfo clientInfo) {
668 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900669 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000670 clientInfo.mClientRequests.remove(clientRequestId);
671 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900672
673 if (existing instanceof LegacyClientRequest) {
674 maybeScheduleStop();
675 } else {
676 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900677 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900678 }
679 }
680
Paul Hu508a0122023-09-11 15:31:33 +0800681 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
682 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900683 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800684 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
685 listener, requestedNetwork, mClock.elapsedRealtime());
686 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000687 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900688 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800689 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800690 }
691
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900692 /**
693 * Truncate a service name to up to 63 UTF-8 bytes.
694 *
695 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
696 * names used in registerService follows historical behavior (see mdnsresponder
697 * handle_regservice_request).
698 */
699 @NonNull
700 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900701 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800702 }
703
Paul Hud44e1b72023-06-16 02:07:42 +0000704 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
705 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800706 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000707 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800708 }
709
Paul Hu77c11182023-10-23 16:17:32 +0800710 private ClientInfo getClientInfoForReply(Message msg) {
711 final ListenerArgs args = (ListenerArgs) msg.obj;
712 return mClients.get(args.connector);
713 }
714
Kangping Dong5af24b62023-12-10 21:41:16 +0800715 /**
716 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
717 * contains invalid subtype label.
718 */
719 private boolean checkSubtypeLabels(Set<String> subtypes) {
720 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
721 mServiceLogs.e(
722 "Too many subtypes: " + subtypes.size() + " (max = "
723 + MAX_SUBTYPE_COUNT + ")");
724 return false;
725 }
726
727 for (String subtype : subtypes) {
728 if (!checkSubtypeLabel(subtype)) {
729 mServiceLogs.e("Subtype " + subtype + " is invalid");
730 return false;
731 }
732 }
733 return true;
734 }
735
736 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
737 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
738 for (String subtype : subtypes) {
739 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
740 }
741 return new ArraySet<>(subtypeMap.values());
742 }
743
Kangping Dongcd350182023-12-12 17:50:34 +0800744 private boolean checkTtl(
745 @Nullable Duration ttl, @NonNull ClientInfo clientInfo) {
746 if (ttl == null) {
747 return true;
748 }
749
750 final long ttlSeconds = ttl.toSeconds();
751 final int uid = clientInfo.getUid();
752
753 // Allows Thread module in the system_server to register TTL that is smaller than
754 // 30 seconds
755 final long minTtlSeconds = uid == SYSTEM_UID ? 0 : NsdManager.TTL_SECONDS_MIN;
756
757 // Allows Thread module in the system_server to register TTL that is larger than
758 // 10 hours
759 final long maxTtlSeconds =
760 uid == SYSTEM_UID ? 0xffffffffL : NsdManager.TTL_SECONDS_MAX;
761
762 if (ttlSeconds < minTtlSeconds || ttlSeconds > maxTtlSeconds) {
763 mServiceLogs.e("ttlSeconds exceeds allowed range (value = "
764 + ttlSeconds + ", allowedRange = [" + minTtlSeconds
765 + ", " + maxTtlSeconds + " ])");
766 return false;
767 }
768 return true;
769 }
770
Irfan Sheriff75006652012-04-17 23:15:29 -0700771 @Override
772 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900773 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000774 final int transactionId;
775 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900776 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700777 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800778 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800779 if (DBG) Log.d(TAG, "Discover services");
Kangping Dong1f1a3792023-12-10 22:05:04 +0800780 final DiscoveryArgs discoveryArgs = (DiscoveryArgs) msg.obj;
781 clientInfo = mClients.get(discoveryArgs.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000782 // If the binder death notification for a INsdManagerCallback was received
783 // before any calls are received by NsdService, the clientInfo would be
784 // cleared and cause NPE. Add a null check here to prevent this corner case.
785 if (clientInfo == null) {
786 Log.e(TAG, "Unknown connector in discovery");
787 break;
788 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700789
790 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800791 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
792 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700793 break;
794 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700795
Kangping Dong1f1a3792023-12-10 22:05:04 +0800796 final DiscoveryRequest discoveryRequest = discoveryArgs.discoveryRequest;
Paul Hud44e1b72023-06-16 02:07:42 +0000797 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900798 final Pair<String, List<String>> typeAndSubtype =
Kangping Dong1f1a3792023-12-10 22:05:04 +0800799 parseTypeAndSubtype(discoveryRequest.getServiceType());
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900800 final String serviceType = typeAndSubtype == null
801 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800802 if (clientInfo.mUseJavaBackend
803 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900804 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900805 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800806 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
807 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800808 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700809 }
Paul Hu23fa2022023-01-13 22:57:24 +0800810
Kangping Dong1f1a3792023-12-10 22:05:04 +0800811 String subtype = discoveryRequest.getSubtype();
812 if (subtype == null && !typeAndSubtype.second.isEmpty()) {
813 subtype = typeAndSubtype.second.get(0);
814 }
815
816 if (subtype != null && !checkSubtypeLabel(subtype)) {
817 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
818 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
819 break;
820 }
821
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900822 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800823 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000824 final MdnsListener listener = new DiscoveryListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800825 transactionId, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900826 final MdnsSearchOptions.Builder optionsBuilder =
827 MdnsSearchOptions.newBuilder()
Kangping Dong1f1a3792023-12-10 22:05:04 +0800828 .setNetwork(discoveryRequest.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900829 .setRemoveExpiredService(true)
Paul Hu11a883d2023-12-14 07:36:44 +0000830 .setQueryMode(
831 mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
832 ? AGGRESSIVE_QUERY_MODE
833 : PASSIVE_QUERY_MODE);
Kangping Dong1f1a3792023-12-10 22:05:04 +0800834 if (subtype != null) {
835 // checkSubtypeLabels() ensures that subtypes start with '_' but
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900836 // MdnsSearchOptions expects the underscore to not be present.
Kangping Dong1f1a3792023-12-10 22:05:04 +0800837 optionsBuilder.addSubtype(subtype.substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900838 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900839 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900840 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800841 final ClientRequest request = storeDiscoveryManagerRequestMap(
842 clientRequestId, transactionId, listener, clientInfo,
Kangping Dong1f1a3792023-12-10 22:05:04 +0800843 discoveryRequest.getNetwork());
844 clientInfo.onDiscoverServicesStarted(
845 clientRequestId, discoveryRequest, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000846 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000847 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700848 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800849 maybeStartDaemon();
Kangping Dong1f1a3792023-12-10 22:05:04 +0800850 if (discoverServices(transactionId, discoveryRequest)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800851 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000852 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Kangping Dong1f1a3792023-12-10 22:05:04 +0800853 + discoveryRequest.getServiceType());
Paul Hu23fa2022023-01-13 22:57:24 +0800854 }
Paul Hu508a0122023-09-11 15:31:33 +0800855 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
856 transactionId, clientInfo, msg.what,
857 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000858 clientInfo.onDiscoverServicesStarted(
Kangping Dong1f1a3792023-12-10 22:05:04 +0800859 clientRequestId, discoveryRequest, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800860 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000861 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800862 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
863 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800864 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700865 }
866 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800867 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900868 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800869 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900870 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900871 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000872 // If the binder death notification for a INsdManagerCallback was received
873 // before any calls are received by NsdService, the clientInfo would be
874 // cleared and cause NPE. Add a null check here to prevent this corner case.
875 if (clientInfo == null) {
876 Log.e(TAG, "Unknown connector in stop discovery");
877 break;
878 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700879
Paul Hud44e1b72023-06-16 02:07:42 +0000880 final ClientRequest request =
881 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900882 if (request == null) {
883 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700884 break;
885 }
Paul Hud44e1b72023-06-16 02:07:42 +0000886 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900887 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
888 // point, so this needs to check the type of the original request to
889 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900890 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000891 stopDiscoveryManagerRequest(
892 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000893 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000894 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700895 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000896 removeRequestMap(clientRequestId, transactionId, clientInfo);
897 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000898 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800899 } else {
900 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000901 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800902 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700903 }
904 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900905 }
906 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800907 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900908 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900909 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000910 // If the binder death notification for a INsdManagerCallback was received
911 // before any calls are received by NsdService, the clientInfo would be
912 // cleared and cause NPE. Add a null check here to prevent this corner case.
913 if (clientInfo == null) {
914 Log.e(TAG, "Unknown connector in registration");
915 break;
916 }
917
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700918 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800919 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
920 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700921 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700922 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900923 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
924 if (advertisingRequest == null) {
925 Log.e(TAG, "Unknown advertisingRequest in registration");
926 break;
927 }
928 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900929 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900930 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
931 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900932 final String registerServiceType = typeSubtype == null
933 ? null : typeSubtype.first;
Handa Wang096e32e2024-01-14 08:21:28 +0000934 final String hostname = serviceInfo.getHostname();
935 // Keep compatible with the legacy behavior: It's allowed to set host
936 // addresses for a service registration although the host addresses
937 // won't be registered. To register the addresses for a host, the
938 // hostname must be specified.
939 if (hostname == null) {
940 serviceInfo.setHostAddresses(Collections.emptyList());
941 }
Paul Hu2e0a88c2023-03-09 16:05:01 +0800942 if (clientInfo.mUseJavaBackend
943 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900944 || useAdvertiserForType(registerServiceType)) {
Handa Wang096e32e2024-01-14 08:21:28 +0000945 if (serviceType != null && registerServiceType == null) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900946 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800947 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
948 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900949 break;
950 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900951 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
952 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
953 // If it is an update request, then reuse the old transactionId
954 if (isUpdateOnly) {
955 final ClientRequest existingClientRequest =
956 clientInfo.mClientRequests.get(clientRequestId);
957 if (existingClientRequest == null) {
958 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
959 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
960 NsdManager.FAILURE_INTERNAL_ERROR,
961 false /* isLegacy */);
962 break;
963 }
964 transactionId = existingClientRequest.mTransactionId;
965 } else {
966 transactionId = getUniqueId();
967 }
Handa Wang096e32e2024-01-14 08:21:28 +0000968
969 if (registerServiceType != null) {
970 serviceInfo.setServiceType(registerServiceType);
971 serviceInfo.setServiceName(
972 truncateServiceName(serviceInfo.getServiceName()));
973 }
974
975 if (!checkHostname(hostname)) {
976 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
977 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
978 break;
979 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900980
Kangping Dong5af24b62023-12-10 21:41:16 +0800981 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Handa Wang096e32e2024-01-14 08:21:28 +0000982 if (typeSubtype != null && typeSubtype.second != null) {
983 for (String subType : typeSubtype.second) {
984 if (!TextUtils.isEmpty(subType)) {
985 subtypes.add(subType);
986 }
Yuyang Huang170d42f2023-12-09 15:26:16 +0900987 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800988 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800989 subtypes = dedupSubtypeLabels(subtypes);
990
991 if (!checkSubtypeLabels(subtypes)) {
992 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
993 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
994 break;
995 }
996
Kangping Dongcd350182023-12-12 17:50:34 +0800997 if (!checkTtl(advertisingRequest.getTtl(), clientInfo)) {
998 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
999 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
1000 break;
1001 }
1002
Kangping Dong5af24b62023-12-10 21:41:16 +08001003 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001004 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +09001005 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
Kangping Dongcd350182023-12-12 17:50:34 +08001006 MdnsAdvertisingOptions.newBuilder()
1007 .setIsOnlyUpdate(isUpdateOnly)
1008 .setTtl(advertisingRequest.getTtl())
1009 .build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +09001010 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Handa Wang096e32e2024-01-14 08:21:28 +00001011 mdnsAdvertisingOptions, clientInfo.mUid);
Paul Hud44e1b72023-06-16 02:07:42 +00001012 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001013 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -07001014 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001015 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +09001016 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +00001017 if (registerService(transactionId, serviceInfo)) {
1018 if (DBG) {
1019 Log.d(TAG, "Register " + clientRequestId
1020 + " " + transactionId);
1021 }
Paul Hua6bc4632023-06-26 01:18:29 +00001022 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1023 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001024 // Return success after mDns reports success
1025 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001026 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001027 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
1028 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001029 }
1030
Irfan Sheriff75006652012-04-17 23:15:29 -07001031 }
1032 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001033 }
1034 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001035 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001036 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001037 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001038 // If the binder death notification for a INsdManagerCallback was received
1039 // before any calls are received by NsdService, the clientInfo would be
1040 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001041 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +08001042 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001043 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001044 }
Paul Hud44e1b72023-06-16 02:07:42 +00001045 final ClientRequest request =
1046 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001047 if (request == null) {
1048 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
1049 break;
1050 }
Paul Hud44e1b72023-06-16 02:07:42 +00001051 transactionId = request.mTransactionId;
1052 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001053
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001054 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
1055 // so this needs to check the type of the original request to unregister
1056 // instead of looking at the flag value.
1057 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001058 final AdvertiserMetrics metrics =
1059 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001060 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001061 clientInfo.onUnregisterServiceSucceeded(
1062 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001063 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001064 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001065 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001066 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1067 NO_PACKET /* sentPacketCount */,
1068 0 /* conflictDuringProbingCount */,
1069 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001070 } else {
1071 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001072 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001073 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001074 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001075 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001076 }
Paul Hu75069ed2023-01-14 00:31:09 +08001077 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001078 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001079 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001080 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001081 // If the binder death notification for a INsdManagerCallback was received
1082 // before any calls are received by NsdService, the clientInfo would be
1083 // cleared and cause NPE. Add a null check here to prevent this corner case.
1084 if (clientInfo == null) {
1085 Log.e(TAG, "Unknown connector in resolution");
1086 break;
1087 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001088
Paul Hu75069ed2023-01-14 00:31:09 +08001089 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001090 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001091 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001092 parseTypeAndSubtype(info.getServiceType());
1093 final String serviceType = typeSubtype == null
1094 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001095 if (clientInfo.mUseJavaBackend
1096 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001097 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001098 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001099 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1100 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001101 break;
1102 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001103 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001104
1105 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001106 final MdnsListener listener = new ResolutionListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001107 transactionId, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001108 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1109 .setNetwork(info.getNetwork())
Paul Hu11a883d2023-12-14 07:36:44 +00001110 .setQueryMode(mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
1111 ? AGGRESSIVE_QUERY_MODE
1112 : PASSIVE_QUERY_MODE)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001113 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001114 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001115 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001116 mMdnsDiscoveryManager.registerListener(
1117 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001118 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1119 listener, clientInfo, info.getNetwork());
1120 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001121 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001122 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001123 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001124 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1125 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001126 break;
1127 }
1128
1129 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001130 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001131 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001132 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1133 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001134 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001135 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1136 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001137 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001138 }
1139 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001140 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001141 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001142 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001143 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001144 clientInfo = mClients.get(args.connector);
1145 // If the binder death notification for a INsdManagerCallback was received
1146 // before any calls are received by NsdService, the clientInfo would be
1147 // cleared and cause NPE. Add a null check here to prevent this corner case.
1148 if (clientInfo == null) {
1149 Log.e(TAG, "Unknown connector in stop resolution");
1150 break;
1151 }
1152
Paul Hud44e1b72023-06-16 02:07:42 +00001153 final ClientRequest request =
1154 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001155 if (request == null) {
1156 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1157 break;
1158 }
Paul Hud44e1b72023-06-16 02:07:42 +00001159 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001160 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1161 // point, so this needs to check the type of the original request to
1162 // unregister instead of looking at the flag value.
1163 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001164 stopDiscoveryManagerRequest(
1165 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001166 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001167 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001168 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001169 removeRequestMap(clientRequestId, transactionId, clientInfo);
1170 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001171 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001172 } else {
1173 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001174 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001175 }
1176 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001177 }
Paul Hub58deb72022-12-26 09:24:42 +00001178 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001179 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001180 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001181 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001182 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001183 clientInfo = mClients.get(args.connector);
1184 // If the binder death notification for a INsdManagerCallback was received
1185 // before any calls are received by NsdService, the clientInfo would be
1186 // cleared and cause NPE. Add a null check here to prevent this corner case.
1187 if (clientInfo == null) {
1188 Log.e(TAG, "Unknown connector in callback registration");
1189 break;
1190 }
1191
Paul Hu30bd70d2023-02-07 13:20:56 +00001192 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001193 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001194 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001195 parseTypeAndSubtype(info.getServiceType());
1196 final String serviceType = typeAndSubtype == null
1197 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001198 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001199 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001200 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001201 break;
1202 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001203 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001204
Paul Hu30bd70d2023-02-07 13:20:56 +00001205 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001206 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001207 transactionId, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001208 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1209 .setNetwork(info.getNetwork())
Paul Hu11a883d2023-12-14 07:36:44 +00001210 .setQueryMode(mMdnsFeatureFlags.isAggressiveQueryModeEnabled()
1211 ? AGGRESSIVE_QUERY_MODE
1212 : PASSIVE_QUERY_MODE)
Paul Hu30bd70d2023-02-07 13:20:56 +00001213 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001214 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001215 .build();
1216 mMdnsDiscoveryManager.registerListener(
1217 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001218 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1219 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001220 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001221 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001222 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001223 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001224 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001225 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001226 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001227 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001228 clientInfo = mClients.get(args.connector);
1229 // If the binder death notification for a INsdManagerCallback was received
1230 // before any calls are received by NsdService, the clientInfo would be
1231 // cleared and cause NPE. Add a null check here to prevent this corner case.
1232 if (clientInfo == null) {
1233 Log.e(TAG, "Unknown connector in callback unregistration");
1234 break;
1235 }
1236
Paul Hud44e1b72023-06-16 02:07:42 +00001237 final ClientRequest request =
1238 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001239 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001240 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001241 break;
1242 }
Paul Hud44e1b72023-06-16 02:07:42 +00001243 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001244 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001245 stopDiscoveryManagerRequest(
1246 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001247 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001248 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001249 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001250 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001251 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001252 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001253 }
paulhu2b9ed952022-02-10 21:58:32 +08001254 case MDNS_SERVICE_EVENT:
1255 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001256 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001257 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001258 break;
Paul Hu019621e2023-01-13 23:26:49 +08001259 case MDNS_DISCOVERY_MANAGER_EVENT:
1260 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1261 return NOT_HANDLED;
1262 }
1263 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001264 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1265 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1266 // TODO: Limits the number of registrations created by a given class.
1267 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1268 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001269 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001270 break;
1271 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1272 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1273 break;
Paul Hu77c11182023-10-23 16:17:32 +08001274 case NsdManager.REGISTER_CLIENT:
1275 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1276 final INsdManagerCallback cb = arg.callback;
1277 try {
1278 cb.asBinder().linkToDeath(arg.connector, 0);
1279 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1280 final NetworkNsdReportedMetrics metrics =
1281 mDeps.makeNetworkNsdReportedMetrics(
1282 (int) mClock.elapsedRealtime());
1283 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1284 mServiceLogs.forSubComponent(tag), metrics);
1285 mClients.put(arg.connector, clientInfo);
1286 } catch (RemoteException e) {
1287 Log.w(TAG, "Client request id " + clientRequestId
1288 + " has already died");
1289 }
1290 break;
1291 case NsdManager.UNREGISTER_CLIENT:
1292 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1293 clientInfo = mClients.remove(connector);
1294 if (clientInfo != null) {
1295 clientInfo.expungeAllRequests();
1296 if (clientInfo.isPreSClient()) {
1297 mLegacyClientCount -= 1;
1298 }
1299 }
1300 maybeStopMonitoringSocketsIfNoActiveRequest();
1301 maybeScheduleStop();
1302 break;
1303 case NsdManager.DAEMON_CLEANUP:
1304 maybeStopDaemon();
1305 break;
1306 // This event should be only sent by the legacy (target SDK < S) clients.
1307 // Mark the sending client as legacy.
1308 case NsdManager.DAEMON_STARTUP:
1309 clientInfo = getClientInfoForReply(msg);
1310 if (clientInfo != null) {
1311 cancelStop();
1312 clientInfo.setPreSClient();
1313 mLegacyClientCount += 1;
1314 maybeStartDaemon();
1315 }
1316 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001317 default:
Paul Hu77c11182023-10-23 16:17:32 +08001318 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001319 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001320 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001321 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001322 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001323
Paul Hud44e1b72023-06-16 02:07:42 +00001324 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001325 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001326 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001327 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001328 Log.e(TAG, String.format(
1329 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001330 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001331 }
1332
1333 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001334 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1335 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001336 // This can happen because of race conditions. For example,
1337 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1338 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001339 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1340 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001341 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001342 }
Paul Hu812e9212023-06-20 06:24:53 +00001343 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1344 if (request == null) {
1345 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1346 return false;
1347 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001348 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001349 Log.d(TAG, String.format(
1350 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001351 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001352 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001353 case IMDnsEventListener.SERVICE_FOUND: {
1354 final DiscoveryInfo info = (DiscoveryInfo) obj;
1355 final String name = info.serviceName;
1356 final String type = info.registrationType;
1357 servInfo = new NsdServiceInfo(name, type);
1358 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001359 if (foundNetId == 0L) {
1360 // Ignore services that do not have a Network: they are not usable
1361 // by apps, as they would need privileged permissions to use
1362 // interfaces that do not have an associated Network.
1363 break;
1364 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001365 if (foundNetId == INetd.DUMMY_NET_ID) {
1366 // Ignore services on the dummy0 interface: they are only seen when
1367 // discovering locally advertised services, and are not reachable
1368 // through that interface.
1369 break;
1370 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001371 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001372
1373 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001374 break;
paulhu2b9ed952022-02-10 21:58:32 +08001375 }
1376 case IMDnsEventListener.SERVICE_LOST: {
1377 final DiscoveryInfo info = (DiscoveryInfo) obj;
1378 final String name = info.serviceName;
1379 final String type = info.registrationType;
1380 final int lostNetId = info.netId;
1381 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001382 // The network could be set to null (netId 0) if it was torn down when the
1383 // service is lost
1384 // TODO: avoid returning null in that case, possibly by remembering
1385 // found services on the same interface index and their network at the time
1386 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001387 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001388 break;
paulhu2b9ed952022-02-10 21:58:32 +08001389 }
1390 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001391 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001392 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1393 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001394 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001395 break;
paulhu2b9ed952022-02-10 21:58:32 +08001396 case IMDnsEventListener.SERVICE_REGISTERED: {
1397 final RegistrationInfo info = (RegistrationInfo) obj;
1398 final String name = info.serviceName;
1399 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001400 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001401 break;
paulhu2b9ed952022-02-10 21:58:32 +08001402 }
1403 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001404 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001405 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1406 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001407 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001408 break;
paulhu2b9ed952022-02-10 21:58:32 +08001409 case IMDnsEventListener.SERVICE_RESOLVED: {
1410 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001411 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001412 final String fullName = info.serviceFullName;
1413 while (index < fullName.length() && fullName.charAt(index) != '.') {
1414 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001415 ++index;
1416 }
1417 ++index;
1418 }
paulhu2b9ed952022-02-10 21:58:32 +08001419 if (index >= fullName.length()) {
1420 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001421 break;
1422 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001423
paulhube186602022-04-12 07:18:23 +00001424 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001425 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001426 String type = rest.replace(".local.", "");
1427
Paul Hu30bd70d2023-02-07 13:20:56 +00001428 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001429 serviceInfo.setServiceName(name);
1430 serviceInfo.setServiceType(type);
1431 serviceInfo.setPort(info.port);
1432 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001433 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001434
Paul Hud44e1b72023-06-16 02:07:42 +00001435 stopResolveService(transactionId);
1436 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001437
Paul Hud44e1b72023-06-16 02:07:42 +00001438 final int transactionId2 = getUniqueId();
1439 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1440 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001441 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001442 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001443 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001444 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1445 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001446 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001447 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001448 }
1449 break;
paulhu2b9ed952022-02-10 21:58:32 +08001450 }
1451 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001452 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001453 stopResolveService(transactionId);
1454 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001455 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001456 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1457 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001458 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001459 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001460 break;
paulhu2b9ed952022-02-10 21:58:32 +08001461 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001462 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001463 stopGetAddrInfo(transactionId);
1464 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001465 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001466 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1467 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001468 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001469 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001470 break;
paulhu2b9ed952022-02-10 21:58:32 +08001471 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001472 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001473 final GetAddressInfo info = (GetAddressInfo) obj;
1474 final String address = info.address;
1475 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001476 InetAddress serviceHost = null;
1477 try {
paulhu2b9ed952022-02-10 21:58:32 +08001478 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001479 } catch (UnknownHostException e) {
1480 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1481 }
1482
1483 // If the resolved service is on an interface without a network, consider it
1484 // as a failure: it would not be usable by apps as they would need
1485 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001486 if (netId != NETID_UNSET && serviceHost != null) {
1487 clientInfo.mResolvedService.setHost(serviceHost);
1488 setServiceNetworkForCallback(clientInfo.mResolvedService,
1489 netId, info.interfaceIdx);
1490 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001491 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001492 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001493 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001494 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1495 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001496 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001497 }
Paul Hud44e1b72023-06-16 02:07:42 +00001498 stopGetAddrInfo(transactionId);
1499 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001500 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001501 break;
paulhu2b9ed952022-02-10 21:58:32 +08001502 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001503 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001504 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001505 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001506 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001507 }
Paul Hu019621e2023-01-13 23:26:49 +08001508
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001509 @Nullable
1510 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1511 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001512 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001513 final String[] typeArray = serviceInfo.getServiceType();
1514 final String joinedType;
1515 if (typeArray.length == 0
1516 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1517 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1518 + Arrays.toString(typeArray));
1519 return null;
1520 } else {
1521 joinedType = TextUtils.join(".",
1522 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1523 }
1524 final String serviceType;
1525 switch (code) {
1526 case NsdManager.SERVICE_FOUND:
1527 case NsdManager.SERVICE_LOST:
1528 // For consistency with historical behavior, discovered service types have
1529 // a dot at the end.
1530 serviceType = joinedType + ".";
1531 break;
1532 case RESOLVE_SERVICE_SUCCEEDED:
1533 // For consistency with historical behavior, resolved service types have
1534 // a dot at the beginning.
1535 serviceType = "." + joinedType;
1536 break;
1537 default:
1538 serviceType = joinedType;
1539 break;
1540 }
Paul Hu019621e2023-01-13 23:26:49 +08001541 final String serviceName = serviceInfo.getServiceInstanceName();
1542 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1543 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001544 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1545 // network for Tethering interface. In other words, the network == null means the
1546 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001547 setServiceNetworkForCallback(
1548 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001549 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001550 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001551 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Kangping Dongcd350182023-12-12 17:50:34 +08001552 servInfo.setExpirationTime(serviceInfo.getExpirationTime());
Paul Hu019621e2023-01-13 23:26:49 +08001553 return servInfo;
1554 }
1555
1556 private boolean handleMdnsDiscoveryManagerEvent(
1557 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001558 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001559 if (clientInfo == null) {
1560 Log.e(TAG, String.format(
1561 "id %d for %d has no client mapping", transactionId, code));
1562 return false;
1563 }
1564
1565 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001566 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001567 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1568 if (request == null) {
1569 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1570 return false;
1571 }
1572
1573 // Deal with the discovery sent callback
1574 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1575 request.onQuerySent();
1576 return true;
1577 }
1578
1579 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001580 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1581 // Errors are already logged if null
1582 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001583 mServiceLogs.log(String.format(
1584 "MdnsDiscoveryManager event code=%s transactionId=%d",
1585 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001586 switch (code) {
1587 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001588 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001589 break;
1590 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001591 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001592 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001593 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1594 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001595 info.setPort(serviceInfo.getPort());
1596
1597 Map<String, String> attrs = serviceInfo.getAttributes();
1598 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1599 final String key = kv.getKey();
1600 try {
1601 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1602 } catch (IllegalArgumentException e) {
1603 Log.e(TAG, "Invalid attribute", e);
1604 }
1605 }
Handa Wang096e32e2024-01-14 08:21:28 +00001606 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001607 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001608 if (addresses.size() != 0) {
1609 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001610 request.setServiceFromCache(event.mIsServiceFromCache);
1611 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001612 } else {
1613 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001614 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001615 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1616 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001617 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001618 }
1619
1620 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001621 if (!(request instanceof DiscoveryManagerRequest)) {
1622 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1623 break;
1624 }
Paul Hud44e1b72023-06-16 02:07:42 +00001625 stopDiscoveryManagerRequest(
1626 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001627 break;
1628 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001629 case NsdManager.SERVICE_UPDATED: {
1630 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1631 info.setPort(serviceInfo.getPort());
1632
1633 Map<String, String> attrs = serviceInfo.getAttributes();
1634 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1635 final String key = kv.getKey();
1636 try {
1637 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1638 } catch (IllegalArgumentException e) {
1639 Log.e(TAG, "Invalid attribute", e);
1640 }
1641 }
1642
Handa Wang096e32e2024-01-14 08:21:28 +00001643 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001644 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001645 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001646 clientInfo.onServiceUpdated(clientRequestId, info, request);
1647 // Set the ServiceFromCache flag only if the service is actually being
1648 // retrieved from the cache. This flag should not be overridden by later
1649 // service updates, which may not be cached.
1650 if (event.mIsServiceFromCache) {
1651 request.setServiceFromCache(true);
1652 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001653 break;
1654 }
1655 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001656 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001657 break;
Paul Hu019621e2023-01-13 23:26:49 +08001658 default:
1659 return false;
1660 }
1661 return true;
1662 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001663 }
1664 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001665
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001666 @NonNull
1667 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1668 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1669 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1670 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1671 for (String ipv4Address : v4Addrs) {
1672 try {
1673 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1674 } catch (IllegalArgumentException e) {
1675 Log.wtf(TAG, "Invalid ipv4 address", e);
1676 }
1677 }
1678 for (String ipv6Address : v6Addrs) {
1679 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001680 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1681 ipv6Address);
1682 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1683 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001684 Log.wtf(TAG, "Invalid ipv6 address", e);
1685 }
1686 }
1687 return addresses;
1688 }
1689
Handa Wang096e32e2024-01-14 08:21:28 +00001690 @NonNull
1691 private static String getHostname(@NonNull MdnsServiceInfo serviceInfo) {
1692 String[] hostname = serviceInfo.getHostName();
1693 // Strip the "local" top-level domain.
1694 if (hostname.length >= 2 && hostname[hostname.length - 1].equals("local")) {
1695 hostname = Arrays.copyOf(hostname, hostname.length - 1);
1696 }
1697 return String.join(".", hostname);
1698 }
1699
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001700 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1701 switch (netId) {
1702 case NETID_UNSET:
1703 info.setNetwork(null);
1704 break;
1705 case INetd.LOCAL_NET_ID:
1706 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1707 // visible / usable for apps, so do not return it. Store the interface
1708 // index instead, so at least if the client tries to resolve the service
1709 // with that NsdServiceInfo, it will be done on the same interface.
1710 // If they recreate the NsdServiceInfo themselves, resolution would be
1711 // done on all interfaces as before T, which should also work.
1712 info.setNetwork(null);
1713 info.setInterfaceIndex(ifaceIdx);
1714 break;
1715 default:
1716 info.setNetwork(new Network(netId));
1717 }
1718 }
1719
paulhube186602022-04-12 07:18:23 +00001720 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1721 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1722 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1723 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1724 private String unescape(String s) {
1725 StringBuilder sb = new StringBuilder(s.length());
1726 for (int i = 0; i < s.length(); ++i) {
1727 char c = s.charAt(i);
1728 if (c == '\\') {
1729 if (++i >= s.length()) {
1730 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1731 break;
1732 }
1733 c = s.charAt(i);
1734 if (c != '.' && c != '\\') {
1735 if (i + 2 >= s.length()) {
1736 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1737 break;
1738 }
1739 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1740 + (s.charAt(i + 2) - '0'));
1741 i += 2;
1742 }
1743 }
1744 sb.append(c);
1745 }
1746 return sb.toString();
1747 }
1748
Paul Hu7445e3d2023-03-03 15:14:00 +08001749 /**
1750 * Check the given service type is valid and construct it to a service type
1751 * which can use for discovery / resolution service.
1752 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001753 * <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 +08001754 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1755 * underscore; they are alphanumerical characters or dashes or underscore, except the
1756 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1757 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001758 * <p>The subtypes may also be specified with a comma after the service type, for example
1759 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001760 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001761 * @param serviceType the request service type for discovery / resolution service
1762 * @return constructed service type or null if the given service type is invalid.
1763 */
1764 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001765 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001766 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001767 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001768 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1769 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001770 final String queryType = matcher.group(2);
1771 // Use the subtype at the beginning
1772 if (matcher.group(1) != null) {
1773 return new Pair<>(queryType, List.of(matcher.group(1)));
1774 }
1775 // Use the subtypes at the end
1776 final String subTypesStr = matcher.group(3);
1777 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1778 final String[] subTypes = subTypesStr.substring(1).split(",");
1779 return new Pair<>(queryType, List.of(subTypes));
1780 }
1781
1782 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001783 }
1784
Handa Wang096e32e2024-01-14 08:21:28 +00001785 /**
1786 * Checks if the hostname is valid.
1787 *
1788 * <p>For now NsdService only allows single-label hostnames conforming to RFC 1035. In other
1789 * words, the hostname should be at most 63 characters long and it only contains letters, digits
1790 * and hyphens.
1791 */
1792 public static boolean checkHostname(@Nullable String hostname) {
1793 if (hostname == null) {
1794 return true;
1795 }
1796 String HOSTNAME_REGEX = "^[a-zA-Z]([a-zA-Z0-9-_]{0,61}[a-zA-Z0-9])?$";
1797 return Pattern.compile(HOSTNAME_REGEX).matcher(hostname).matches();
1798 }
1799
Kangping Dong5af24b62023-12-10 21:41:16 +08001800 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1801 private static boolean checkSubtypeLabel(String subtype) {
Remi NGUYEN VAN629234c2024-02-08 18:27:45 +09001802 return Pattern.compile("^" + SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
Kangping Dong5af24b62023-12-10 21:41:16 +08001803 }
1804
Hugo Benichi803a2f02017-04-24 11:35:06 +09001805 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001806 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001807 this(ctx, handler, cleanupDelayMs, new Dependencies());
1808 }
1809
1810 @VisibleForTesting
1811 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001812 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001813 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001814 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001815 mNsdStateMachine.start();
Ken Chen80c9f6f2023-11-15 18:24:54 +08001816 // It can fail on V+ device since mdns native service provided by netd is removed.
1817 mMDnsManager = SdkLevel.isAtLeastV() ? null : ctx.getSystemService(MDnsManager.class);
paulhu2b9ed952022-02-10 21:58:32 +08001818 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001819 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001820
Paul Hu14667de2023-04-17 22:42:47 +08001821 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001822 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001823 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001824 // address events are received. When the netlink monitor starts, any IP addresses already
1825 // on the interfaces will not be seen. In practice, the network will not connect at boot
1826 // time As a result, all the netlink message should be observed if the netlink monitor
1827 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001828 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001829
1830 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1831 // startBootstrapServices).
1832 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1833 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1834 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1835 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1836 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1837 mRunningAppActiveImportanceCutoff);
1838
Paul Hu11a883d2023-12-14 07:36:44 +00001839 mMdnsFeatureFlags = new MdnsFeatureFlags.Builder()
Paul Huf3fe3332023-10-16 17:13:25 +08001840 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1841 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1842 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1843 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001844 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1845 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001846 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1847 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001848 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1849 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001850 .setIsUnicastReplyEnabled(mDeps.isFeatureEnabled(
1851 mContext, MdnsFeatureFlags.NSD_UNICAST_REPLY_ENABLED))
Paul Hu11a883d2023-12-14 07:36:44 +00001852 .setIsAggressiveQueryModeEnabled(mDeps.isFeatureEnabled(
1853 mContext, MdnsFeatureFlags.NSD_AGGRESSIVE_QUERY_MODE))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001854 .setOverrideProvider(flag -> mDeps.isFeatureEnabled(
1855 mContext, FORCE_ENABLE_FLAG_FOR_TEST_PREFIX + flag))
Paul Huf3fe3332023-10-16 17:13:25 +08001856 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001857 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001858 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hu11a883d2023-12-14 07:36:44 +00001859 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), mMdnsFeatureFlags);
Paul Hu14667de2023-04-17 22:42:47 +08001860 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Hu11a883d2023-12-14 07:36:44 +00001861 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"),
1862 mMdnsFeatureFlags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001863 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1864 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu11a883d2023-12-14 07:36:44 +00001865 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"),
1866 mMdnsFeatureFlags, mContext);
Paul Hu777ed052023-06-19 13:35:15 +00001867 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001868 }
1869
1870 /**
1871 * Dependencies of NsdService, for injection in tests.
1872 */
1873 @VisibleForTesting
1874 public static class Dependencies {
1875 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001876 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001877 *
1878 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001879 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001880 */
1881 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001882 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001883 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001884 }
1885
1886 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001887 * Check whether the MdnsAdvertiser feature is enabled.
1888 *
1889 * @param context The global context information about an app environment.
1890 * @return true if the MdnsAdvertiser feature is enabled.
1891 */
1892 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001893 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001894 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001895 }
1896
1897 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001898 * Get the type allowlist flag value.
1899 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1900 */
1901 @Nullable
1902 public String getTypeAllowlistFlags() {
1903 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1904 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1905 }
1906
1907 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001908 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001909 */
1910 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001911 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001912 }
1913
1914 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001915 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1916 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001917 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1918 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001919 }
1920
1921 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001922 * @see MdnsDiscoveryManager
1923 */
1924 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001925 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001926 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1927 @NonNull MdnsFeatureFlags featureFlags) {
1928 return new MdnsDiscoveryManager(
1929 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001930 }
1931
1932 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001933 * @see MdnsAdvertiser
1934 */
1935 public MdnsAdvertiser makeMdnsAdvertiser(
1936 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001937 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001938 MdnsFeatureFlags featureFlags, Context context) {
1939 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags, context);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001940 }
1941
1942 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001943 * @see MdnsSocketProvider
1944 */
Paul Hu14667de2023-04-17 22:42:47 +08001945 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001946 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1947 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1948 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1949 }
1950
1951 /**
1952 * @see DeviceConfig#getInt(String, String, int)
1953 */
1954 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1955 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1956 }
1957
1958 /**
1959 * @see Binder#getCallingUid()
1960 */
1961 public int getCallingUid() {
1962 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001963 }
Paul Hu777ed052023-06-19 13:35:15 +00001964
1965 /**
1966 * @see NetworkNsdReportedMetrics
1967 */
Paul Hu508a0122023-09-11 15:31:33 +08001968 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1969 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001970 }
1971
1972 /**
1973 * @see MdnsUtils.Clock
1974 */
1975 public Clock makeClock() {
1976 return new Clock();
1977 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001978 }
1979
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001980 /**
1981 * Return whether a type is allowlisted to use the Java backend.
1982 * @param type The service type
1983 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1984 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1985 */
1986 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1987 @NonNull String flagPrefix) {
1988 if (type == null) return false;
1989 final String typesConfig = mDeps.getTypeAllowlistFlags();
1990 if (TextUtils.isEmpty(typesConfig)) return false;
1991
1992 final String mappingPrefix = type + ":";
1993 String mappedFlag = null;
1994 for (String mapping : TextUtils.split(typesConfig, ",")) {
1995 if (mapping.startsWith(mappingPrefix)) {
1996 mappedFlag = mapping.substring(mappingPrefix.length());
1997 break;
1998 }
1999 }
2000
2001 if (mappedFlag == null) return false;
2002
2003 return mDeps.isFeatureEnabled(mContext,
2004 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
2005 }
2006
2007 private boolean useDiscoveryManagerForType(@Nullable String type) {
2008 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
2009 }
2010
2011 private boolean useAdvertiserForType(@Nullable String type) {
2012 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
2013 }
2014
paulhu1b35e822022-04-08 14:48:41 +08002015 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002016 HandlerThread thread = new HandlerThread(TAG);
2017 thread.start();
2018 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08002019 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002020 return service;
2021 }
2022
paulhu2b9ed952022-02-10 21:58:32 +08002023 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
2024 private final StateMachine mStateMachine;
2025
2026 MDnsEventCallback(StateMachine sm) {
2027 mStateMachine = sm;
2028 }
2029
2030 @Override
2031 public void onServiceRegistrationStatus(final RegistrationInfo status) {
2032 mStateMachine.sendMessage(
2033 MDNS_SERVICE_EVENT, status.result, status.id, status);
2034 }
2035
2036 @Override
2037 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
2038 mStateMachine.sendMessage(
2039 MDNS_SERVICE_EVENT, status.result, status.id, status);
2040 }
2041
2042 @Override
2043 public void onServiceResolutionStatus(final ResolutionInfo status) {
2044 mStateMachine.sendMessage(
2045 MDNS_SERVICE_EVENT, status.result, status.id, status);
2046 }
2047
2048 @Override
2049 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
2050 mStateMachine.sendMessage(
2051 MDNS_SERVICE_EVENT, status.result, status.id, status);
2052 }
2053
2054 @Override
2055 public int getInterfaceVersion() throws RemoteException {
2056 return this.VERSION;
2057 }
2058
2059 @Override
2060 public String getInterfaceHash() throws RemoteException {
2061 return this.HASH;
2062 }
2063 }
2064
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002065 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
2066 final String targetInterface = offloadEngineInfo.mInterfaceName;
2067 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
2068 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
2069 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
2070 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
2071 try {
2072 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
2073 } catch (RemoteException e) {
2074 // Can happen in regular cases, do not log a stacktrace
2075 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
2076 }
2077 }
2078 }
2079
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002080 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
2081 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
2082 final int count = mOffloadEngines.beginBroadcast();
2083 try {
2084 for (int i = 0; i < count; i++) {
2085 final OffloadEngineInfo offloadEngineInfo =
2086 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
2087 final String interfaceName = offloadEngineInfo.mInterfaceName;
2088 if (!targetInterfaceName.equals(interfaceName)
2089 || ((offloadEngineInfo.mOffloadType
2090 & offloadServiceInfo.getOffloadType()) == 0)) {
2091 continue;
2092 }
2093 try {
2094 if (isRemove) {
2095 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
2096 offloadServiceInfo);
2097 } else {
2098 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
2099 offloadServiceInfo);
2100 }
2101 } catch (RemoteException e) {
2102 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002103 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002104 }
2105 }
2106 } finally {
2107 mOffloadEngines.finishBroadcast();
2108 }
2109 }
2110
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002111 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002112 // TODO: add a callback to notify when a service is being added on each interface (as soon
2113 // as probing starts), and call mOffloadCallbacks. This callback is for
2114 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2115
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002116 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002117 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2118 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2119 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002120 if (clientInfo == null) return;
2121
Paul Hud44e1b72023-06-16 02:07:42 +00002122 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2123 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002124
Handa Wang096e32e2024-01-14 08:21:28 +00002125 // onRegisterServiceSucceeded only has the service name and hostname in its info. This
2126 // aligns with historical behavior.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002127 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Handa Wang096e32e2024-01-14 08:21:28 +00002128 cbInfo.setHostname(registeredInfo.getHostname());
Paul Hu777ed052023-06-19 13:35:15 +00002129 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002130 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002131 }
2132
2133 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002134 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2135 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002136 if (clientInfo == null) return;
2137
Paul Hud44e1b72023-06-16 02:07:42 +00002138 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2139 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002140 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002141 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2142 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002143 }
2144
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002145 @Override
2146 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2147 @NonNull OffloadServiceInfo offloadServiceInfo) {
2148 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2149 }
2150
2151 @Override
2152 public void onOffloadStop(@NonNull String interfaceName,
2153 @NonNull OffloadServiceInfo offloadServiceInfo) {
2154 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2155 }
2156
Paul Hud44e1b72023-06-16 02:07:42 +00002157 private ClientInfo getClientInfoOrLog(int transactionId) {
2158 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002159 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002160 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002161 }
2162 return clientInfo;
2163 }
2164
Paul Hud44e1b72023-06-16 02:07:42 +00002165 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2166 final int clientRequestId = info.getClientRequestId(transactionId);
2167 if (clientRequestId < 0) {
2168 Log.e(TAG, String.format(
2169 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002170 }
Paul Hud44e1b72023-06-16 02:07:42 +00002171 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002172 }
2173 }
2174
Paul Hu2e0a88c2023-03-09 16:05:01 +08002175 private static class ConnectorArgs {
2176 @NonNull public final NsdServiceConnector connector;
2177 @NonNull public final INsdManagerCallback callback;
2178 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002179 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002180
2181 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002182 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002183 this.connector = connector;
2184 this.callback = callback;
2185 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002186 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002187 }
2188 }
2189
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002190 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002191 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002192 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002193 final int uid = mDeps.getCallingUid();
2194 if (cb == null) {
2195 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2196 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002197 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002198 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002199 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002200 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002201 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002202 }
2203
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002204 private static class ListenerArgs {
2205 public final NsdServiceConnector connector;
2206 public final NsdServiceInfo serviceInfo;
2207 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2208 this.connector = connector;
2209 this.serviceInfo = serviceInfo;
2210 }
2211 }
2212
Yuyang Huang86d083f2023-12-12 19:56:41 +09002213 private static class AdvertisingArgs {
2214 public final NsdServiceConnector connector;
2215 public final AdvertisingRequest advertisingRequest;
2216
2217 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2218 this.connector = connector;
2219 this.advertisingRequest = advertisingRequest;
2220 }
2221 }
2222
Kangping Dong1f1a3792023-12-10 22:05:04 +08002223 private static final class DiscoveryArgs {
2224 public final NsdServiceConnector connector;
2225 public final DiscoveryRequest discoveryRequest;
2226 DiscoveryArgs(NsdServiceConnector connector, DiscoveryRequest discoveryRequest) {
2227 this.connector = connector;
2228 this.discoveryRequest = discoveryRequest;
2229 }
2230 }
2231
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002232 private class NsdServiceConnector extends INsdServiceConnector.Stub
2233 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002234
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002235 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002236 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2237 throws RemoteException {
Handa Wang096e32e2024-01-14 08:21:28 +00002238 NsdManager.checkServiceInfoForRegistration(advertisingRequest.getServiceInfo());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002239 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2240 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002241 new AdvertisingArgs(this, advertisingRequest)
2242 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002243 }
2244
2245 @Override
2246 public void unregisterService(int listenerKey) {
2247 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2248 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002249 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002250 }
2251
2252 @Override
Kangping Dong1f1a3792023-12-10 22:05:04 +08002253 public void discoverServices(int listenerKey, DiscoveryRequest discoveryRequest) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002254 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2255 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
Kangping Dong1f1a3792023-12-10 22:05:04 +08002256 new DiscoveryArgs(this, discoveryRequest)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002257 }
2258
2259 @Override
2260 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002261 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2262 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002263 }
2264
2265 @Override
2266 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2267 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2268 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2269 new ListenerArgs(this, serviceInfo)));
2270 }
2271
2272 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002273 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002274 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2275 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002276 }
2277
2278 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002279 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2280 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2281 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2282 new ListenerArgs(this, serviceInfo)));
2283 }
2284
2285 @Override
2286 public void unregisterServiceInfoCallback(int listenerKey) {
2287 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2288 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002289 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002290 }
2291
2292 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002293 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002294 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2295 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002296 }
2297
2298 @Override
2299 public void binderDied() {
2300 mNsdStateMachine.sendMessage(
2301 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002302
2303 }
2304
2305 @Override
2306 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2307 @OffloadEngine.OffloadCapability long offloadCapabilities,
2308 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002309 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002310 Objects.requireNonNull(ifaceName);
2311 Objects.requireNonNull(cb);
2312 mNsdStateMachine.sendMessage(
2313 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2314 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2315 offloadTypes)));
2316 }
2317
2318 @Override
2319 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002320 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002321 Objects.requireNonNull(cb);
2322 mNsdStateMachine.sendMessage(
2323 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002324 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002325
2326 private static void checkOffloadEnginePermission(Context context) {
2327 if (!SdkLevel.isAtLeastT()) {
2328 throw new SecurityException("API is not available in before API level 33");
2329 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002330
Ken Chena7bae552023-12-27 11:40:57 +08002331 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2332 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2333
2334 if (SdkLevel.isAtLeastV()) {
2335 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2336 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2337 } else if (SdkLevel.isAtLeastU()) {
2338 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2339 // permission instead.
2340 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002341 }
2342
Junyu Lai71b51532024-02-01 10:39:01 +08002343 if (PermissionUtils.hasAnyPermissionOf(context,
Ken Chena7bae552023-12-27 11:40:57 +08002344 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002345 return;
2346 }
2347 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002348 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002349 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002350 }
2351
Hugo Benichi912db992017-04-24 16:41:03 +09002352 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002353 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002354 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002355 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2356 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002357 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002358 }
2359
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002360 private int getUniqueId() {
2361 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2362 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002363 }
2364
Paul Hud44e1b72023-06-16 02:07:42 +00002365 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002366 if (mMDnsManager == null) {
2367 Log.wtf(TAG, "registerService: mMDnsManager is null");
2368 return false;
2369 }
2370
Hugo Benichi6d706442017-04-24 16:19:58 +09002371 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002372 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002373 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002374 String name = service.getServiceName();
2375 String type = service.getServiceType();
2376 int port = service.getPort();
2377 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002378 final int registerInterface = getNetworkInterfaceIndex(service);
2379 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002380 Log.e(TAG, "Interface to register service on not found");
2381 return false;
2382 }
Paul Hud44e1b72023-06-16 02:07:42 +00002383 return mMDnsManager.registerService(
2384 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002385 }
2386
Paul Hud44e1b72023-06-16 02:07:42 +00002387 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002388 if (mMDnsManager == null) {
2389 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2390 return false;
2391 }
Paul Hud44e1b72023-06-16 02:07:42 +00002392 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002393 }
2394
Kangping Dong1f1a3792023-12-10 22:05:04 +08002395 private boolean discoverServices(int transactionId, DiscoveryRequest discoveryRequest) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002396 if (mMDnsManager == null) {
2397 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2398 return false;
2399 }
2400
Kangping Dong1f1a3792023-12-10 22:05:04 +08002401 final String type = discoveryRequest.getServiceType();
2402 final int discoverInterface = getNetworkInterfaceIndex(discoveryRequest);
2403 if (discoveryRequest.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002404 Log.e(TAG, "Interface to discover service on not found");
2405 return false;
2406 }
Paul Hud44e1b72023-06-16 02:07:42 +00002407 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002408 }
2409
Paul Hud44e1b72023-06-16 02:07:42 +00002410 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002411 if (mMDnsManager == null) {
2412 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2413 return false;
2414 }
Paul Hud44e1b72023-06-16 02:07:42 +00002415 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002416 }
2417
Paul Hud44e1b72023-06-16 02:07:42 +00002418 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002419 if (mMDnsManager == null) {
2420 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2421 return false;
2422 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002423 final String name = service.getServiceName();
2424 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002425 final int resolveInterface = getNetworkInterfaceIndex(service);
2426 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002427 Log.e(TAG, "Interface to resolve service on not found");
2428 return false;
2429 }
Paul Hud44e1b72023-06-16 02:07:42 +00002430 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002431 }
2432
2433 /**
2434 * Guess the interface to use to resolve or discover a service on a specific network.
2435 *
2436 * This is an imperfect guess, as for example the network may be gone or not yet fully
2437 * registered. This is fine as failing is correct if the network is gone, and a client
2438 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2439 * this is to support the legacy mdnsresponder implementation, which historically resolved
2440 * services on an unspecified network.
2441 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002442 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2443 final Network network = serviceInfo.getNetwork();
2444 if (network == null) {
2445 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2446 // provided by NsdService from discovery results, and the service was found on an
2447 // interface that has no app-usable Network).
2448 if (serviceInfo.getInterfaceIndex() != 0) {
2449 return serviceInfo.getInterfaceIndex();
2450 }
2451 return IFACE_IDX_ANY;
2452 }
Kangping Dong1f1a3792023-12-10 22:05:04 +08002453 return getNetworkInterfaceIndex(network);
2454 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002455
Kangping Dong1f1a3792023-12-10 22:05:04 +08002456 /**
2457 * Returns the interface to use to discover a service on a specific network, or {@link
2458 * IFACE_IDX_ANY} if no network is specified.
2459 */
2460 private int getNetworkInterfaceIndex(DiscoveryRequest discoveryRequest) {
2461 final Network network = discoveryRequest.getNetwork();
2462 if (network == null) {
2463 return IFACE_IDX_ANY;
2464 }
2465 return getNetworkInterfaceIndex(network);
2466 }
2467
2468 /**
2469 * Returns the interface of a specific network, or {@link IFACE_IDX_ANY} if no interface is
2470 * associated with {@code network}.
2471 */
2472 private int getNetworkInterfaceIndex(@NonNull Network network) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002473 String interfaceName = getNetworkInterfaceName(network);
2474 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002475 return IFACE_IDX_ANY;
2476 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002477 return getNetworkInterfaceIndexByName(interfaceName);
2478 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002479
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002480 private String getNetworkInterfaceName(@Nullable Network network) {
2481 if (network == null) {
2482 return null;
2483 }
2484 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2485 if (cm == null) {
2486 Log.wtf(TAG, "No ConnectivityManager");
2487 return null;
2488 }
2489 final LinkProperties lp = cm.getLinkProperties(network);
2490 if (lp == null) {
2491 return null;
2492 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002493 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002494 return lp.getInterfaceName();
2495 }
2496
2497 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002498 final NetworkInterface iface;
2499 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002500 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002501 } catch (SocketException e) {
2502 Log.e(TAG, "Error querying interface", e);
2503 return IFACE_IDX_ANY;
2504 }
2505
2506 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002507 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002508 return IFACE_IDX_ANY;
2509 }
2510
2511 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002512 }
2513
Paul Hud44e1b72023-06-16 02:07:42 +00002514 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002515 if (mMDnsManager == null) {
2516 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2517 return false;
2518 }
Paul Hud44e1b72023-06-16 02:07:42 +00002519 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002520 }
2521
Paul Hud44e1b72023-06-16 02:07:42 +00002522 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002523 if (mMDnsManager == null) {
2524 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2525 return false;
2526 }
Paul Hud44e1b72023-06-16 02:07:42 +00002527 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002528 }
2529
Paul Hud44e1b72023-06-16 02:07:42 +00002530 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002531 if (mMDnsManager == null) {
2532 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2533 return false;
2534 }
Paul Hud44e1b72023-06-16 02:07:42 +00002535 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002536 }
2537
2538 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002539 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08002540 if (!PermissionUtils.hasDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002541
Paul Hub2e67d32023-04-18 05:50:14 +00002542 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2543 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002544 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002545
2546 // Dump service and clients logs
2547 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002548 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002549 pw.increaseIndent();
2550 mServiceLogs.reverseDump(pw);
2551 pw.decreaseIndent();
Paul Hu55f943e2024-02-20 03:04:17 +00002552
2553 //Dump DiscoveryManager
2554 pw.println();
2555 pw.println("DiscoveryManager:");
2556 pw.increaseIndent();
2557 HandlerUtils.runWithScissorsForDump(
2558 mNsdStateMachine.getHandler(), () -> mMdnsDiscoveryManager.dump(pw), 10_000);
2559 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002560 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002561
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002562 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002563 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002564 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002565 private int mFoundServiceCount = 0;
2566 private int mLostServiceCount = 0;
2567 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002568 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002569 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002570
Paul Hu812e9212023-06-20 06:24:53 +00002571 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002572 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002573 mStartTimeMs = startTimeMs;
2574 }
2575
Paul Hu812e9212023-06-20 06:24:53 +00002576 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002577 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002578 }
Paul Hu812e9212023-06-20 06:24:53 +00002579
2580 public void onServiceFound(String serviceName) {
2581 mFoundServiceCount++;
2582 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2583 mServices.add(serviceName);
2584 }
2585 }
2586
2587 public void onServiceLost() {
2588 mLostServiceCount++;
2589 }
2590
2591 public int getFoundServiceCount() {
2592 return mFoundServiceCount;
2593 }
2594
2595 public int getLostServiceCount() {
2596 return mLostServiceCount;
2597 }
2598
2599 public int getServicesCount() {
2600 return mServices.size();
2601 }
Paul Hua6bc4632023-06-26 01:18:29 +00002602
2603 public void setServiceFromCache(boolean isServiceFromCache) {
2604 mIsServiceFromCache = isServiceFromCache;
2605 }
2606
2607 public boolean isServiceFromCache() {
2608 return mIsServiceFromCache;
2609 }
Paul Hubad6fe92023-07-24 21:25:22 +08002610
2611 public void onQuerySent() {
2612 mSentQueryCount++;
2613 }
2614
2615 public int getSentQueryCount() {
2616 return mSentQueryCount;
2617 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002618 }
2619
2620 private static class LegacyClientRequest extends ClientRequest {
2621 private final int mRequestCode;
2622
Paul Hu812e9212023-06-20 06:24:53 +00002623 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2624 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002625 mRequestCode = requestCode;
2626 }
2627 }
2628
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002629 private abstract static class JavaBackendClientRequest extends ClientRequest {
2630 @Nullable
2631 private final Network mRequestedNetwork;
2632
Paul Hu777ed052023-06-19 13:35:15 +00002633 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002634 long startTimeMs) {
2635 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002636 mRequestedNetwork = requestedNetwork;
2637 }
2638
2639 @Nullable
2640 public Network getRequestedNetwork() {
2641 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002642 }
2643 }
2644
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002645 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002646 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002647 long startTimeMs) {
2648 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002649 }
2650 }
2651
2652 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002653 @NonNull
2654 private final MdnsListener mListener;
2655
Paul Hud44e1b72023-06-16 02:07:42 +00002656 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002657 @Nullable Network requestedNetwork, long startTimeMs) {
2658 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002659 mListener = listener;
2660 }
2661 }
2662
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002663 /* Information tracked per client */
2664 private class ClientInfo {
2665
Remi NGUYEN VAN12a0c6a2024-02-09 18:24:29 +09002666 /**
2667 * Maximum number of requests (callbacks) for a client.
2668 *
2669 * 200 listeners should be more than enough for most use-cases: even if a client tries to
2670 * file callbacks for every service on a local network, there are generally much less than
2671 * 200 devices on a local network (a /24 only allows 255 IPv4 devices), and while some
2672 * devices may have multiple services, many devices do not advertise any.
2673 */
2674 private static final int MAX_LIMIT = 200;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002675 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002676 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002677 private NsdServiceInfo mResolvedService;
2678
Paul Hud44e1b72023-06-16 02:07:42 +00002679 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002680 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002681
Luke Huangf7277ed2021-07-12 21:15:10 +08002682 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002683 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002684 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002685 // The flag of using java backend if the client's target SDK >= U
2686 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002687 // Store client logs
2688 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002689 // Report the nsd metrics data
2690 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002691
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002692 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002693 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002694 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002695 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002696 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002697 mClientLogs = sharedLog;
2698 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002699 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002700 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002701
2702 @Override
2703 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002704 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002705 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002706 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002707 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2708 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002709 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002710 int clientRequestId = mClientRequests.keyAt(i);
2711 sb.append("clientRequestId ")
2712 .append(clientRequestId)
2713 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002714 .append(" type ").append(
2715 mClientRequests.valueAt(i).getClass().getSimpleName())
2716 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002717 }
2718 return sb.toString();
2719 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002720
Kangping Dongcd350182023-12-12 17:50:34 +08002721 public int getUid() {
2722 return mUid;
2723 }
2724
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002725 private boolean isPreSClient() {
2726 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002727 }
2728
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002729 private void setPreSClient() {
2730 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002731 }
2732
Paul Hu812e9212023-06-20 06:24:53 +00002733 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002734 final MdnsListener listener =
2735 ((DiscoveryManagerRequest) request).mListener;
2736 mMdnsDiscoveryManager.unregisterListener(
2737 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002738 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002739 }
2740
Dave Plattfeff2af2014-03-07 14:48:22 -08002741 // Remove any pending requests from the global map when we get rid of a client,
2742 // and send cancellations to the daemon.
2743 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002744 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002745 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002746 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002747 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002748 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002749 final int transactionId = request.mTransactionId;
2750 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002751 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002752 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2753 + " transactionId " + transactionId
2754 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002755 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002756
2757 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002758 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2759 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002760 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002761 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2762 request.getFoundServiceCount(),
2763 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002764 request.getServicesCount(),
2765 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002766 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002767 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002768 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002769 } else if (listener instanceof ServiceInfoListener) {
2770 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2771 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2772 request.getFoundServiceCount(),
2773 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002774 request.isServiceFromCache(),
2775 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002776 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002777 continue;
2778 }
2779
2780 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002781 final AdvertiserMetrics metrics =
2782 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002783 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002784 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002785 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2786 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2787 metrics.mConflictDuringProbingCount,
2788 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002789 continue;
2790 }
2791
2792 if (!(request instanceof LegacyClientRequest)) {
2793 throw new IllegalStateException("Unknown request type: " + request.getClass());
2794 }
2795
2796 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002797 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002798 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002799 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002800 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2801 request.getFoundServiceCount(),
2802 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002803 request.getServicesCount(),
2804 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002805 break;
2806 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002807 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002808 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002809 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002810 break;
2811 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002812 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002813 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002814 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2815 NO_PACKET /* repliedRequestsCount */,
2816 NO_PACKET /* sentPacketCount */,
2817 0 /* conflictDuringProbingCount */,
2818 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002819 break;
2820 default:
2821 break;
2822 }
2823 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002824 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002825 updateMulticastLock();
2826 }
2827
2828 /**
2829 * Returns true if this client has any Java backend request that requests one of the given
2830 * networks.
2831 */
2832 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2833 for (int i = 0; i < mClientRequests.size(); i++) {
2834 final ClientRequest req = mClientRequests.valueAt(i);
2835 if (!(req instanceof JavaBackendClientRequest)) {
2836 continue;
2837 }
2838 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2839 .getRequestedNetwork();
2840 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2841 return true;
2842 }
2843 }
2844 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002845 }
2846
Paul Hud44e1b72023-06-16 02:07:42 +00002847 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2848 // transaction id, return the corresponding client request id.
2849 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002850 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002851 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002852 return mClientRequests.keyAt(i);
2853 }
Christopher Lane74411222014-04-25 18:39:07 -07002854 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002855 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002856 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002857
Paul Hub2e67d32023-04-18 05:50:14 +00002858 private void log(String message) {
2859 mClientLogs.log(message);
2860 }
2861
Paul Hu508a0122023-09-11 15:31:33 +08002862 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2863 return !(request instanceof DiscoveryManagerRequest)
2864 && !(request instanceof AdvertiserClientRequest);
2865 }
2866
Kangping Dong1f1a3792023-12-10 22:05:04 +08002867 void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest,
Paul Hu508a0122023-09-11 15:31:33 +08002868 ClientRequest request) {
2869 mMetrics.reportServiceDiscoveryStarted(
2870 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002871 try {
Kangping Dong1f1a3792023-12-10 22:05:04 +08002872 mCb.onDiscoverServicesStarted(listenerKey, discoveryRequest);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002873 } catch (RemoteException e) {
2874 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2875 }
2876 }
Paul Hu508a0122023-09-11 15:31:33 +08002877 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2878 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2879 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002880 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002881
Paul Hu508a0122023-09-11 15:31:33 +08002882 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2883 int transactionId, long durationMs) {
2884 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002885 try {
2886 mCb.onDiscoverServicesFailed(listenerKey, error);
2887 } catch (RemoteException e) {
2888 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2889 }
2890 }
2891
Paul Hu812e9212023-06-20 06:24:53 +00002892 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2893 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002894 try {
2895 mCb.onServiceFound(listenerKey, info);
2896 } catch (RemoteException e) {
2897 Log.e(TAG, "Error calling onServiceFound(", e);
2898 }
2899 }
2900
Paul Hu812e9212023-06-20 06:24:53 +00002901 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2902 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002903 try {
2904 mCb.onServiceLost(listenerKey, info);
2905 } catch (RemoteException e) {
2906 Log.e(TAG, "Error calling onServiceLost(", e);
2907 }
2908 }
2909
2910 void onStopDiscoveryFailed(int listenerKey, int error) {
2911 try {
2912 mCb.onStopDiscoveryFailed(listenerKey, error);
2913 } catch (RemoteException e) {
2914 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2915 }
2916 }
2917
Paul Hu812e9212023-06-20 06:24:53 +00002918 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2919 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002920 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002921 request.mTransactionId,
2922 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2923 request.getFoundServiceCount(),
2924 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002925 request.getServicesCount(),
2926 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002927 try {
2928 mCb.onStopDiscoverySucceeded(listenerKey);
2929 } catch (RemoteException e) {
2930 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2931 }
2932 }
2933
Paul Hu508a0122023-09-11 15:31:33 +08002934 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2935 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2936 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002937 }
2938
Paul Hu508a0122023-09-11 15:31:33 +08002939 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2940 int transactionId, long durationMs) {
2941 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002942 try {
2943 mCb.onRegisterServiceFailed(listenerKey, error);
2944 } catch (RemoteException e) {
2945 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2946 }
2947 }
2948
Paul Hu508a0122023-09-11 15:31:33 +08002949 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2950 ClientRequest request) {
2951 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2952 request.mTransactionId,
2953 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002954 try {
2955 mCb.onRegisterServiceSucceeded(listenerKey, info);
2956 } catch (RemoteException e) {
2957 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2958 }
2959 }
2960
2961 void onUnregisterServiceFailed(int listenerKey, int error) {
2962 try {
2963 mCb.onUnregisterServiceFailed(listenerKey, error);
2964 } catch (RemoteException e) {
2965 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2966 }
2967 }
2968
Paul Hu508a0122023-09-11 15:31:33 +08002969 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002970 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002971 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2972 request.mTransactionId,
2973 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002974 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2975 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002976 try {
2977 mCb.onUnregisterServiceSucceeded(listenerKey);
2978 } catch (RemoteException e) {
2979 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2980 }
2981 }
2982
Paul Hu508a0122023-09-11 15:31:33 +08002983 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2984 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2985 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002986 }
2987
Paul Hu508a0122023-09-11 15:31:33 +08002988 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2989 int transactionId, long durationMs) {
2990 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002991 try {
2992 mCb.onResolveServiceFailed(listenerKey, error);
2993 } catch (RemoteException e) {
2994 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2995 }
2996 }
2997
Paul Hua6bc4632023-06-26 01:18:29 +00002998 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2999 ClientRequest request) {
3000 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08003001 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00003002 request.mTransactionId,
3003 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08003004 request.isServiceFromCache(),
3005 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09003006 try {
3007 mCb.onResolveServiceSucceeded(listenerKey, info);
3008 } catch (RemoteException e) {
3009 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
3010 }
3011 }
Paul Hub58deb72022-12-26 09:24:42 +00003012
3013 void onStopResolutionFailed(int listenerKey, int error) {
3014 try {
3015 mCb.onStopResolutionFailed(listenerKey, error);
3016 } catch (RemoteException e) {
3017 Log.e(TAG, "Error calling onStopResolutionFailed", e);
3018 }
3019 }
3020
Paul Hu60149052023-07-31 14:26:08 +08003021 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
3022 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08003023 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08003024 request.mTransactionId,
3025 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00003026 try {
3027 mCb.onStopResolutionSucceeded(listenerKey);
3028 } catch (RemoteException e) {
3029 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
3030 }
3031 }
Paul Hu18aeccc2022-12-27 08:48:48 +00003032
3033 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08003034 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00003035 try {
3036 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
3037 } catch (RemoteException e) {
3038 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
3039 }
3040 }
3041
Paul Huddce5912023-08-01 10:26:49 +08003042 void onServiceInfoCallbackRegistered(int transactionId) {
3043 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
3044 }
3045
3046 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
3047 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00003048 try {
3049 mCb.onServiceUpdated(listenerKey, info);
3050 } catch (RemoteException e) {
3051 Log.e(TAG, "Error calling onServiceUpdated", e);
3052 }
3053 }
3054
Paul Huddce5912023-08-01 10:26:49 +08003055 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
3056 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00003057 try {
3058 mCb.onServiceUpdatedLost(listenerKey);
3059 } catch (RemoteException e) {
3060 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
3061 }
3062 }
3063
Paul Huddce5912023-08-01 10:26:49 +08003064 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
3065 mMetrics.reportServiceInfoCallbackUnregistered(
3066 request.mTransactionId,
3067 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
3068 request.getFoundServiceCount(),
3069 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08003070 request.isServiceFromCache(),
3071 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00003072 try {
3073 mCb.onServiceInfoCallbackUnregistered(listenerKey);
3074 } catch (RemoteException e) {
3075 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
3076 }
3077 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07003078 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003079}