blob: 397e5a63d75131739208584b91f9fee5327f920e [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;
Yuyang Huang86d083f2023-12-12 19:56:41 +090029import static android.net.nsd.NsdManager.TYPE_REGEX;
30import static android.net.nsd.NsdManager.TYPE_SUBTYPE_LABEL_REGEX;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090031import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090032
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090033import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090034import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080035import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
36import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090037import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hu05086bd2024-01-26 03:48:51 +000038import static com.android.server.connectivity.mdns.MdnsSearchOptions.PASSIVE_QUERY_MODE;
Paul Hucdef3532023-06-18 14:47:35 +000039import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090040
Paul Hu23fa2022023-01-13 22:57:24 +080041import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080042import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090043import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090044import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080045import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070046import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090047import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090048import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080049import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090050import android.net.LinkProperties;
51import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080052import android.net.mdns.aidl.DiscoveryInfo;
53import android.net.mdns.aidl.GetAddressInfo;
54import android.net.mdns.aidl.IMDnsEventListener;
55import android.net.mdns.aidl.RegistrationInfo;
56import android.net.mdns.aidl.ResolutionInfo;
Yuyang Huang86d083f2023-12-12 19:56:41 +090057import android.net.nsd.AdvertisingRequest;
Kangping Dong1f1a3792023-12-10 22:05:04 +080058import android.net.nsd.DiscoveryRequest;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090060import android.net.nsd.INsdManagerCallback;
61import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090062import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080063import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070064import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080065import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090066import android.net.nsd.OffloadEngine;
67import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090068import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000069import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090070import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090071import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080072import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090073import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080074import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070075import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090076import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090077import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070078import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090079import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080080import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090081import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090082import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090083import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070084import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070085
paulhua262cc12019-08-12 16:25:11 +080086import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000087import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080088import com.android.internal.util.State;
89import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000090import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090091import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090092import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080093import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090094import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080095import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000096import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080097import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090098import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090099import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800100import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +0900101import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900102import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800103import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800104import com.android.server.connectivity.mdns.MdnsSearchOptions;
105import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
106import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800107import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900108import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800109
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700110import java.io.FileDescriptor;
111import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900112import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700113import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900114import java.net.NetworkInterface;
115import java.net.SocketException;
116import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800117import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900118import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800119import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900120import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700121import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800122import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800123import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800124import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900125import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000126import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800127import java.util.regex.Matcher;
128import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700129
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700130/**
131 * Network Service Discovery Service handles remote service discovery operation requests by
132 * implementing the INsdManager interface.
133 *
134 * @hide
135 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900136@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700137public class NsdService extends INsdManager.Stub {
138 private static final String TAG = "NsdService";
139 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900140 /**
141 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
142 * implementation.
143 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800144 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800145 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900147 /**
148 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
149 * implementation.
150 */
151 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
152
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900153 /**
154 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
155 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
156 *
157 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
158 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
159 *
160 * In which case the flags:
161 * "mdns_discovery_manager_allowlist_mytype_version",
162 * "mdns_advertiser_allowlist_mytype_version",
163 * "mdns_discovery_manager_allowlist_othertype_version",
164 * "mdns_advertiser_allowlist_othertype_version"
165 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
166 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900167 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900168 *
169 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
170 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
171 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
172 */
173 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
174
175 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
176 "mdns_discovery_manager_allowlist_";
177 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
178 "mdns_advertiser_allowlist_";
179 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
180
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +0900181 private static final String FORCE_ENABLE_FLAG_FOR_TEST_PREFIX = "test_";
Kangping Dong5af24b62023-12-10 21:41:16 +0800182
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900183 @VisibleForTesting
184 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
185 "mdns_config_running_app_active_importance_cutoff";
186 @VisibleForTesting
187 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
188 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
189 private final int mRunningAppActiveImportanceCutoff;
190
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900191 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000192 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900193 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000194 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
195 @VisibleForTesting
196 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800197 private static final int NO_SENT_QUERY_COUNT = 0;
198 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800199 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800200 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700201
Hugo Benichi32be63d2017-04-05 14:06:11 +0900202 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900203 private final NsdStateMachine mNsdStateMachine;
Ken Chen80c9f6f2023-11-15 18:24:54 +0800204 // It can be null on V+ device since mdns native service provided by netd is removed.
205 private final @Nullable MDnsManager mMDnsManager;
paulhu2b9ed952022-02-10 21:58:32 +0800206 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900207 @NonNull
208 private final Dependencies mDeps;
209 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800210 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900211 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800212 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900213 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800214 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900215 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900216 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000217 @NonNull
218 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800219 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800220 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800221 // state machine thread. If change this outside state machine, it will need to introduce
222 // synchronization.
223 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800224 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700225
226 /**
227 * Clients receiving asynchronous messages
228 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900229 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700230
Paul Hud44e1b72023-06-16 02:07:42 +0000231 /* A map from transaction(unique) id to client info */
232 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700233
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900234 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
235 @Nullable
236 private WifiManager.MulticastLock mHeldMulticastLock;
237 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
238 // (non-null), value is the requested Network (nullable)
239 @NonNull
240 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
241 @NonNull
242 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
243
Luke Huang05298582021-06-13 16:52:05 +0000244 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700245
Hugo Benichi32be63d2017-04-05 14:06:11 +0900246 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700247 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800248 // The count of the connected legacy clients.
249 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000250 // The number of client that ever connected.
251 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700252
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900253 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
254 new RemoteCallbackList<>();
255
256 private static class OffloadEngineInfo {
257 @NonNull final String mInterfaceName;
258 final long mOffloadCapabilities;
259 final long mOffloadType;
260 @NonNull final IOffloadEngine mOffloadEngine;
261
262 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
263 @NonNull String interfaceName, long capabilities, long offloadType) {
264 this.mOffloadEngine = offloadEngine;
265 this.mInterfaceName = interfaceName;
266 this.mOffloadCapabilities = capabilities;
267 this.mOffloadType = offloadType;
268 }
269 }
270
Paul Hu812e9212023-06-20 06:24:53 +0000271 @VisibleForTesting
272 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000273 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800274 protected final int mTransactionId;
275 @NonNull
Paul Hu23fa2022023-01-13 22:57:24 +0800276 protected final String mListenedServiceType;
277
Kangping Dong97b2adc2024-01-11 16:00:37 +0800278 MdnsListener(int clientRequestId, int transactionId, @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000279 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800280 mTransactionId = transactionId;
Paul Hu23fa2022023-01-13 22:57:24 +0800281 mListenedServiceType = listenedServiceType;
282 }
283
284 @NonNull
285 public String getListenedServiceType() {
286 return mListenedServiceType;
287 }
288
289 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000290 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
291 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800292
293 @Override
294 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
295
296 @Override
297 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
298
299 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000300 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
301 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800302
303 @Override
304 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
305
306 @Override
307 public void onSearchStoppedWithError(int error) { }
308
309 @Override
310 public void onSearchFailedToStart() { }
311
312 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800313 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
314 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800315
316 @Override
317 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
318 }
319
320 private class DiscoveryListener extends MdnsListener {
321
Paul Hud44e1b72023-06-16 02:07:42 +0000322 DiscoveryListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800323 @NonNull String listenServiceType) {
324 super(clientRequestId, transactionId, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800325 }
326
327 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000328 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
329 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800330 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
331 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000332 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800333 }
334
335 @Override
336 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800337 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
338 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000339 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800340 }
Paul Hubad6fe92023-07-24 21:25:22 +0800341
342 @Override
343 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
344 int sentQueryTransactionId) {
345 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
346 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
347 }
Paul Hu23fa2022023-01-13 22:57:24 +0800348 }
349
Paul Hu75069ed2023-01-14 00:31:09 +0800350 private class ResolutionListener extends MdnsListener {
351
Paul Hud44e1b72023-06-16 02:07:42 +0000352 ResolutionListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800353 @NonNull String listenServiceType) {
354 super(clientRequestId, transactionId, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800355 }
356
357 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000358 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800359 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
360 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000361 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800362 }
Paul Hubad6fe92023-07-24 21:25:22 +0800363
364 @Override
365 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
366 int sentQueryTransactionId) {
367 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
368 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
369 }
Paul Hu75069ed2023-01-14 00:31:09 +0800370 }
371
Paul Hu30bd70d2023-02-07 13:20:56 +0000372 private class ServiceInfoListener extends MdnsListener {
373
Paul Hud44e1b72023-06-16 02:07:42 +0000374 ServiceInfoListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800375 @NonNull String listenServiceType) {
376 super(clientRequestId, transactionId, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000377 }
378
379 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000380 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
381 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000382 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
383 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000384 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000385 }
386
387 @Override
388 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
389 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
390 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000391 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000392 }
393
394 @Override
395 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
396 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
397 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000398 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000399 }
Paul Hubad6fe92023-07-24 21:25:22 +0800400
401 @Override
402 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
403 int sentQueryTransactionId) {
404 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
405 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
406 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000407 }
408
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900409 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
410 @Override
411 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
412 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
413 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
414 // filtering on such interfaces, so taking the multicast lock is not necessary to
415 // disable APF filtering of multicast.
416 if (socketNetwork == null
417 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
418 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
419 return;
420 }
421
422 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
423 updateMulticastLock();
424 }
425 }
426
427 @Override
428 public void onSocketDestroyed(@Nullable Network socketNetwork,
429 @NonNull MdnsInterfaceSocket socket) {
430 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
431 updateMulticastLock();
432 }
433 }
434 }
435
436 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
437 private final Handler mHandler;
438
439 private UidImportanceListener(Handler handler) {
440 mHandler = handler;
441 }
442
443 @Override
444 public void onUidImportance(int uid, int importance) {
445 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
446 }
447 }
448
449 private void handleUidImportanceChanged(int uid, int importance) {
450 // Lower importance values are more "important"
451 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
452 ? mRunningAppActiveUids.add(uid)
453 : mRunningAppActiveUids.remove(uid);
454 if (modified) {
455 updateMulticastLock();
456 }
457 }
458
459 /**
460 * Take or release the lock based on updated internal state.
461 *
462 * This determines whether the lock needs to be held based on
463 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
464 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
465 * updated.
466 */
467 private void updateMulticastLock() {
468 final int needsLockUid = getMulticastLockNeededUid();
469 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
470 final WifiManager wm = mContext.getSystemService(WifiManager.class);
471 if (wm == null) {
472 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
473 return;
474 }
475 mHeldMulticastLock = wm.createMulticastLock(TAG);
476 mHeldMulticastLock.acquire();
477 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
478 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
479 mHeldMulticastLock.release();
480 mHeldMulticastLock = null;
481 mServiceLogs.log("Released multicast lock");
482 }
483 }
484
485 /**
486 * @return The UID of an app requiring the multicast lock, or -1 if none.
487 */
488 private int getMulticastLockNeededUid() {
489 if (mWifiLockRequiredNetworks.size() == 0) {
490 // Return early if NSD is not active, or not on any relevant network
491 return -1;
492 }
Paul Hud44e1b72023-06-16 02:07:42 +0000493 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
494 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900495 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
496 // Ignore non-active UIDs
497 continue;
498 }
499
500 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
501 return clientInfo.mUid;
502 }
503 }
504 return -1;
505 }
506
Paul Hu019621e2023-01-13 23:26:49 +0800507 /**
508 * Data class of mdns service callback information.
509 */
510 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000511 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800512 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800513 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000514 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800515
Paul Hubad6fe92023-07-24 21:25:22 +0800516 MdnsEvent(int clientRequestId) {
517 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
518 }
519
520 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000521 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
522 }
523
Paul Hubad6fe92023-07-24 21:25:22 +0800524 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000525 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000526 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800527 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000528 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800529 }
530 }
531
Paul Hu77c11182023-10-23 16:17:32 +0800532 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700533 private class NsdStateMachine extends StateMachine {
534
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700535 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700536
537 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700538 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900539 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700540 }
541
Luke Huang92860f92021-06-23 06:29:30 +0000542 private void maybeStartDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000543 if (mIsDaemonStarted) {
544 if (DBG) Log.d(TAG, "Daemon is already started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800545 return;
546 }
547
Paul Hu4a87ed42024-01-10 08:58:30 +0000548 if (mMDnsManager == null) {
549 Log.wtf(TAG, "maybeStartDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800550 return;
551 }
552 mMDnsManager.registerEventListener(mMDnsEventCallback);
553 mMDnsManager.startDaemon();
554 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000555 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000556 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000557 }
558
paulhu2b9ed952022-02-10 21:58:32 +0800559 private void maybeStopDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000560 if (!mIsDaemonStarted) {
561 if (DBG) Log.d(TAG, "Daemon has not been started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800562 return;
563 }
564
Paul Hu4a87ed42024-01-10 08:58:30 +0000565 if (mMDnsManager == null) {
566 Log.wtf(TAG, "maybeStopDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800567 return;
568 }
569 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
570 mMDnsManager.stopDaemon();
571 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000572 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800573 }
574
Luke Huang92860f92021-06-23 06:29:30 +0000575 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000576 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000577 }
578
579 private void scheduleStop() {
580 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
581 }
582 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800583 // The native daemon should stay alive and can't be cleanup
584 // if any legacy client connected.
585 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000586 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000587 }
588 }
589
Luke Huang92860f92021-06-23 06:29:30 +0000590 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000591 this.removeMessages(NsdManager.DAEMON_CLEANUP);
592 }
593
Paul Hu23fa2022023-01-13 22:57:24 +0800594 private void maybeStartMonitoringSockets() {
595 if (mIsMonitoringSocketsStarted) {
596 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
597 return;
598 }
599
600 mMdnsSocketProvider.startMonitoringSockets();
601 mIsMonitoringSocketsStarted = true;
602 }
603
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900604 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
605 if (!mIsMonitoringSocketsStarted) return;
606 if (isAnyRequestActive()) return;
607
Paul Hu58f20602023-02-18 11:41:07 +0800608 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800609 mIsMonitoringSocketsStarted = false;
610 }
611
Hugo Benichi803a2f02017-04-24 11:35:06 +0900612 NsdStateMachine(String name, Handler handler) {
613 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800614 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800615 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900616 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700617 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 }
619
Irfan Sheriff75006652012-04-17 23:15:29 -0700620 class EnabledState extends State {
621 @Override
622 public void enter() {
623 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700624 }
625
626 @Override
627 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000628 // TODO: it is incorrect to stop the daemon without expunging all requests
629 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000630 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700631 }
632
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700633 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900634 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800635 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700636 return true;
637 }
638 return false;
639 }
640
Paul Hu508a0122023-09-11 15:31:33 +0800641 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000642 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800643 final LegacyClientRequest request =
644 new LegacyClientRequest(transactionId, what, startTimeMs);
645 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000646 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000647 // Remove the cleanup event because here comes a new request.
648 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800649 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700650 }
651
Paul Hud44e1b72023-06-16 02:07:42 +0000652 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900653 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000654 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000655 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000656 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900657 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800658 }
659
Paul Hud44e1b72023-06-16 02:07:42 +0000660 private void removeRequestMap(
661 int clientRequestId, int transactionId, ClientInfo clientInfo) {
662 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900663 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000664 clientInfo.mClientRequests.remove(clientRequestId);
665 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900666
667 if (existing instanceof LegacyClientRequest) {
668 maybeScheduleStop();
669 } else {
670 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900671 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900672 }
673 }
674
Paul Hu508a0122023-09-11 15:31:33 +0800675 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
676 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900677 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800678 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
679 listener, requestedNetwork, mClock.elapsedRealtime());
680 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000681 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900682 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800683 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800684 }
685
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900686 /**
687 * Truncate a service name to up to 63 UTF-8 bytes.
688 *
689 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
690 * names used in registerService follows historical behavior (see mdnsresponder
691 * handle_regservice_request).
692 */
693 @NonNull
694 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900695 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800696 }
697
Paul Hud44e1b72023-06-16 02:07:42 +0000698 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
699 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800700 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000701 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800702 }
703
Paul Hu77c11182023-10-23 16:17:32 +0800704 private ClientInfo getClientInfoForReply(Message msg) {
705 final ListenerArgs args = (ListenerArgs) msg.obj;
706 return mClients.get(args.connector);
707 }
708
Kangping Dong5af24b62023-12-10 21:41:16 +0800709 /**
710 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
711 * contains invalid subtype label.
712 */
713 private boolean checkSubtypeLabels(Set<String> subtypes) {
714 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
715 mServiceLogs.e(
716 "Too many subtypes: " + subtypes.size() + " (max = "
717 + MAX_SUBTYPE_COUNT + ")");
718 return false;
719 }
720
721 for (String subtype : subtypes) {
722 if (!checkSubtypeLabel(subtype)) {
723 mServiceLogs.e("Subtype " + subtype + " is invalid");
724 return false;
725 }
726 }
727 return true;
728 }
729
730 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
731 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
732 for (String subtype : subtypes) {
733 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
734 }
735 return new ArraySet<>(subtypeMap.values());
736 }
737
Irfan Sheriff75006652012-04-17 23:15:29 -0700738 @Override
739 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900740 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000741 final int transactionId;
742 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900743 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700744 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800745 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800746 if (DBG) Log.d(TAG, "Discover services");
Kangping Dong1f1a3792023-12-10 22:05:04 +0800747 final DiscoveryArgs discoveryArgs = (DiscoveryArgs) msg.obj;
748 clientInfo = mClients.get(discoveryArgs.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000749 // If the binder death notification for a INsdManagerCallback was received
750 // before any calls are received by NsdService, the clientInfo would be
751 // cleared and cause NPE. Add a null check here to prevent this corner case.
752 if (clientInfo == null) {
753 Log.e(TAG, "Unknown connector in discovery");
754 break;
755 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700756
757 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800758 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
759 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700760 break;
761 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700762
Kangping Dong1f1a3792023-12-10 22:05:04 +0800763 final DiscoveryRequest discoveryRequest = discoveryArgs.discoveryRequest;
Paul Hud44e1b72023-06-16 02:07:42 +0000764 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900765 final Pair<String, List<String>> typeAndSubtype =
Kangping Dong1f1a3792023-12-10 22:05:04 +0800766 parseTypeAndSubtype(discoveryRequest.getServiceType());
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900767 final String serviceType = typeAndSubtype == null
768 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800769 if (clientInfo.mUseJavaBackend
770 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900771 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900772 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800773 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
774 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800775 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700776 }
Paul Hu23fa2022023-01-13 22:57:24 +0800777
Kangping Dong1f1a3792023-12-10 22:05:04 +0800778 String subtype = discoveryRequest.getSubtype();
779 if (subtype == null && !typeAndSubtype.second.isEmpty()) {
780 subtype = typeAndSubtype.second.get(0);
781 }
782
783 if (subtype != null && !checkSubtypeLabel(subtype)) {
784 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
785 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
786 break;
787 }
788
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900789 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800790 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000791 final MdnsListener listener = new DiscoveryListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800792 transactionId, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900793 final MdnsSearchOptions.Builder optionsBuilder =
794 MdnsSearchOptions.newBuilder()
Kangping Dong1f1a3792023-12-10 22:05:04 +0800795 .setNetwork(discoveryRequest.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900796 .setRemoveExpiredService(true)
Paul Hu05086bd2024-01-26 03:48:51 +0000797 .setQueryMode(PASSIVE_QUERY_MODE);
Kangping Dong1f1a3792023-12-10 22:05:04 +0800798 if (subtype != null) {
799 // checkSubtypeLabels() ensures that subtypes start with '_' but
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900800 // MdnsSearchOptions expects the underscore to not be present.
Kangping Dong1f1a3792023-12-10 22:05:04 +0800801 optionsBuilder.addSubtype(subtype.substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900802 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900803 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900804 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800805 final ClientRequest request = storeDiscoveryManagerRequestMap(
806 clientRequestId, transactionId, listener, clientInfo,
Kangping Dong1f1a3792023-12-10 22:05:04 +0800807 discoveryRequest.getNetwork());
808 clientInfo.onDiscoverServicesStarted(
809 clientRequestId, discoveryRequest, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000810 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000811 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700812 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800813 maybeStartDaemon();
Kangping Dong1f1a3792023-12-10 22:05:04 +0800814 if (discoverServices(transactionId, discoveryRequest)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800815 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000816 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Kangping Dong1f1a3792023-12-10 22:05:04 +0800817 + discoveryRequest.getServiceType());
Paul Hu23fa2022023-01-13 22:57:24 +0800818 }
Paul Hu508a0122023-09-11 15:31:33 +0800819 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
820 transactionId, clientInfo, msg.what,
821 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000822 clientInfo.onDiscoverServicesStarted(
Kangping Dong1f1a3792023-12-10 22:05:04 +0800823 clientRequestId, discoveryRequest, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800824 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000825 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800826 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
827 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800828 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700829 }
830 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800831 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800833 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900834 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900835 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000836 // If the binder death notification for a INsdManagerCallback was received
837 // before any calls are received by NsdService, the clientInfo would be
838 // cleared and cause NPE. Add a null check here to prevent this corner case.
839 if (clientInfo == null) {
840 Log.e(TAG, "Unknown connector in stop discovery");
841 break;
842 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700843
Paul Hud44e1b72023-06-16 02:07:42 +0000844 final ClientRequest request =
845 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900846 if (request == null) {
847 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700848 break;
849 }
Paul Hud44e1b72023-06-16 02:07:42 +0000850 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900851 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
852 // point, so this needs to check the type of the original request to
853 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900854 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000855 stopDiscoveryManagerRequest(
856 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000857 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000858 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700859 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000860 removeRequestMap(clientRequestId, transactionId, clientInfo);
861 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000862 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800863 } else {
864 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000865 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800866 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700867 }
868 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900869 }
870 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800871 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900872 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900873 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000874 // If the binder death notification for a INsdManagerCallback was received
875 // before any calls are received by NsdService, the clientInfo would be
876 // cleared and cause NPE. Add a null check here to prevent this corner case.
877 if (clientInfo == null) {
878 Log.e(TAG, "Unknown connector in registration");
879 break;
880 }
881
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700882 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800883 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
884 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700885 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700886 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900887 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
888 if (advertisingRequest == null) {
889 Log.e(TAG, "Unknown advertisingRequest in registration");
890 break;
891 }
892 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900893 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900894 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
895 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900896 final String registerServiceType = typeSubtype == null
897 ? null : typeSubtype.first;
Handa Wang096e32e2024-01-14 08:21:28 +0000898 final String hostname = serviceInfo.getHostname();
899 // Keep compatible with the legacy behavior: It's allowed to set host
900 // addresses for a service registration although the host addresses
901 // won't be registered. To register the addresses for a host, the
902 // hostname must be specified.
903 if (hostname == null) {
904 serviceInfo.setHostAddresses(Collections.emptyList());
905 }
Paul Hu2e0a88c2023-03-09 16:05:01 +0800906 if (clientInfo.mUseJavaBackend
907 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900908 || useAdvertiserForType(registerServiceType)) {
Handa Wang096e32e2024-01-14 08:21:28 +0000909 if (serviceType != null && registerServiceType == null) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900910 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800911 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
912 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900913 break;
914 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900915 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
916 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
917 // If it is an update request, then reuse the old transactionId
918 if (isUpdateOnly) {
919 final ClientRequest existingClientRequest =
920 clientInfo.mClientRequests.get(clientRequestId);
921 if (existingClientRequest == null) {
922 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
923 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
924 NsdManager.FAILURE_INTERNAL_ERROR,
925 false /* isLegacy */);
926 break;
927 }
928 transactionId = existingClientRequest.mTransactionId;
929 } else {
930 transactionId = getUniqueId();
931 }
Handa Wang096e32e2024-01-14 08:21:28 +0000932
933 if (registerServiceType != null) {
934 serviceInfo.setServiceType(registerServiceType);
935 serviceInfo.setServiceName(
936 truncateServiceName(serviceInfo.getServiceName()));
937 }
938
939 if (!checkHostname(hostname)) {
940 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
941 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
942 break;
943 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900944
Kangping Dong5af24b62023-12-10 21:41:16 +0800945 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Handa Wang096e32e2024-01-14 08:21:28 +0000946 if (typeSubtype != null && typeSubtype.second != null) {
947 for (String subType : typeSubtype.second) {
948 if (!TextUtils.isEmpty(subType)) {
949 subtypes.add(subType);
950 }
Yuyang Huang170d42f2023-12-09 15:26:16 +0900951 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800952 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800953 subtypes = dedupSubtypeLabels(subtypes);
954
955 if (!checkSubtypeLabels(subtypes)) {
956 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
957 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
958 break;
959 }
960
961 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900962 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900963 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
964 MdnsAdvertisingOptions.newBuilder().setIsOnlyUpdate(
965 isUpdateOnly).build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900966 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Handa Wang096e32e2024-01-14 08:21:28 +0000967 mdnsAdvertisingOptions, clientInfo.mUid);
Paul Hud44e1b72023-06-16 02:07:42 +0000968 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900969 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700970 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900971 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900972 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +0000973 if (registerService(transactionId, serviceInfo)) {
974 if (DBG) {
975 Log.d(TAG, "Register " + clientRequestId
976 + " " + transactionId);
977 }
Paul Hua6bc4632023-06-26 01:18:29 +0000978 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
979 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900980 // Return success after mDns reports success
981 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000982 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800983 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
984 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900985 }
986
Irfan Sheriff75006652012-04-17 23:15:29 -0700987 }
988 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900989 }
990 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800991 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900992 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900993 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000994 // If the binder death notification for a INsdManagerCallback was received
995 // before any calls are received by NsdService, the clientInfo would be
996 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900997 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800998 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700999 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001000 }
Paul Hud44e1b72023-06-16 02:07:42 +00001001 final ClientRequest request =
1002 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001003 if (request == null) {
1004 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
1005 break;
1006 }
Paul Hud44e1b72023-06-16 02:07:42 +00001007 transactionId = request.mTransactionId;
1008 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001009
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001010 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
1011 // so this needs to check the type of the original request to unregister
1012 // instead of looking at the flag value.
1013 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001014 final AdvertiserMetrics metrics =
1015 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001016 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001017 clientInfo.onUnregisterServiceSucceeded(
1018 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001019 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001020 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001021 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001022 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1023 NO_PACKET /* sentPacketCount */,
1024 0 /* conflictDuringProbingCount */,
1025 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001026 } else {
1027 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001028 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001029 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001030 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001031 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001032 }
Paul Hu75069ed2023-01-14 00:31:09 +08001033 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001034 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001035 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001036 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001037 // If the binder death notification for a INsdManagerCallback was received
1038 // before any calls are received by NsdService, the clientInfo would be
1039 // cleared and cause NPE. Add a null check here to prevent this corner case.
1040 if (clientInfo == null) {
1041 Log.e(TAG, "Unknown connector in resolution");
1042 break;
1043 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001044
Paul Hu75069ed2023-01-14 00:31:09 +08001045 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001046 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001047 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001048 parseTypeAndSubtype(info.getServiceType());
1049 final String serviceType = typeSubtype == null
1050 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001051 if (clientInfo.mUseJavaBackend
1052 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001053 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001054 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001055 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1056 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001057 break;
1058 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001059 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001060
1061 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001062 final MdnsListener listener = new ResolutionListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001063 transactionId, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001064 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1065 .setNetwork(info.getNetwork())
Paul Hu05086bd2024-01-26 03:48:51 +00001066 .setQueryMode(PASSIVE_QUERY_MODE)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001067 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001068 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001069 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001070 mMdnsDiscoveryManager.registerListener(
1071 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001072 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1073 listener, clientInfo, info.getNetwork());
1074 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001075 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001076 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001077 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001078 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1079 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001080 break;
1081 }
1082
1083 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001084 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001085 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001086 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1087 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001088 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001089 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1090 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001091 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001092 }
1093 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001094 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001095 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001096 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001097 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001098 clientInfo = mClients.get(args.connector);
1099 // If the binder death notification for a INsdManagerCallback was received
1100 // before any calls are received by NsdService, the clientInfo would be
1101 // cleared and cause NPE. Add a null check here to prevent this corner case.
1102 if (clientInfo == null) {
1103 Log.e(TAG, "Unknown connector in stop resolution");
1104 break;
1105 }
1106
Paul Hud44e1b72023-06-16 02:07:42 +00001107 final ClientRequest request =
1108 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001109 if (request == null) {
1110 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1111 break;
1112 }
Paul Hud44e1b72023-06-16 02:07:42 +00001113 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001114 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1115 // point, so this needs to check the type of the original request to
1116 // unregister instead of looking at the flag value.
1117 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001118 stopDiscoveryManagerRequest(
1119 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001120 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001121 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001122 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001123 removeRequestMap(clientRequestId, transactionId, clientInfo);
1124 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001125 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001126 } else {
1127 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001128 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001129 }
1130 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001131 }
Paul Hub58deb72022-12-26 09:24:42 +00001132 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001133 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001134 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001135 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001136 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001137 clientInfo = mClients.get(args.connector);
1138 // If the binder death notification for a INsdManagerCallback was received
1139 // before any calls are received by NsdService, the clientInfo would be
1140 // cleared and cause NPE. Add a null check here to prevent this corner case.
1141 if (clientInfo == null) {
1142 Log.e(TAG, "Unknown connector in callback registration");
1143 break;
1144 }
1145
Paul Hu30bd70d2023-02-07 13:20:56 +00001146 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001147 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001148 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001149 parseTypeAndSubtype(info.getServiceType());
1150 final String serviceType = typeAndSubtype == null
1151 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001152 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001153 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001154 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001155 break;
1156 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001157 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001158
Paul Hu30bd70d2023-02-07 13:20:56 +00001159 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001160 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001161 transactionId, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001162 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1163 .setNetwork(info.getNetwork())
Paul Hu05086bd2024-01-26 03:48:51 +00001164 .setQueryMode(PASSIVE_QUERY_MODE)
Paul Hu30bd70d2023-02-07 13:20:56 +00001165 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001166 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001167 .build();
1168 mMdnsDiscoveryManager.registerListener(
1169 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001170 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1171 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001172 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001173 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001174 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001175 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001176 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001177 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001178 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001179 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001180 clientInfo = mClients.get(args.connector);
1181 // If the binder death notification for a INsdManagerCallback was received
1182 // before any calls are received by NsdService, the clientInfo would be
1183 // cleared and cause NPE. Add a null check here to prevent this corner case.
1184 if (clientInfo == null) {
1185 Log.e(TAG, "Unknown connector in callback unregistration");
1186 break;
1187 }
1188
Paul Hud44e1b72023-06-16 02:07:42 +00001189 final ClientRequest request =
1190 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001191 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001192 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001193 break;
1194 }
Paul Hud44e1b72023-06-16 02:07:42 +00001195 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001196 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001197 stopDiscoveryManagerRequest(
1198 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001199 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001200 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001201 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001202 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001203 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001204 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001205 }
paulhu2b9ed952022-02-10 21:58:32 +08001206 case MDNS_SERVICE_EVENT:
1207 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001208 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001209 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001210 break;
Paul Hu019621e2023-01-13 23:26:49 +08001211 case MDNS_DISCOVERY_MANAGER_EVENT:
1212 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1213 return NOT_HANDLED;
1214 }
1215 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001216 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1217 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1218 // TODO: Limits the number of registrations created by a given class.
1219 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1220 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001221 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001222 break;
1223 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1224 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1225 break;
Paul Hu77c11182023-10-23 16:17:32 +08001226 case NsdManager.REGISTER_CLIENT:
1227 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1228 final INsdManagerCallback cb = arg.callback;
1229 try {
1230 cb.asBinder().linkToDeath(arg.connector, 0);
1231 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1232 final NetworkNsdReportedMetrics metrics =
1233 mDeps.makeNetworkNsdReportedMetrics(
1234 (int) mClock.elapsedRealtime());
1235 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1236 mServiceLogs.forSubComponent(tag), metrics);
1237 mClients.put(arg.connector, clientInfo);
1238 } catch (RemoteException e) {
1239 Log.w(TAG, "Client request id " + clientRequestId
1240 + " has already died");
1241 }
1242 break;
1243 case NsdManager.UNREGISTER_CLIENT:
1244 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1245 clientInfo = mClients.remove(connector);
1246 if (clientInfo != null) {
1247 clientInfo.expungeAllRequests();
1248 if (clientInfo.isPreSClient()) {
1249 mLegacyClientCount -= 1;
1250 }
1251 }
1252 maybeStopMonitoringSocketsIfNoActiveRequest();
1253 maybeScheduleStop();
1254 break;
1255 case NsdManager.DAEMON_CLEANUP:
1256 maybeStopDaemon();
1257 break;
1258 // This event should be only sent by the legacy (target SDK < S) clients.
1259 // Mark the sending client as legacy.
1260 case NsdManager.DAEMON_STARTUP:
1261 clientInfo = getClientInfoForReply(msg);
1262 if (clientInfo != null) {
1263 cancelStop();
1264 clientInfo.setPreSClient();
1265 mLegacyClientCount += 1;
1266 maybeStartDaemon();
1267 }
1268 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001269 default:
Paul Hu77c11182023-10-23 16:17:32 +08001270 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001271 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001272 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001273 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001274 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275
Paul Hud44e1b72023-06-16 02:07:42 +00001276 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001277 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001278 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001279 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001280 Log.e(TAG, String.format(
1281 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001282 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001283 }
1284
1285 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001286 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1287 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001288 // This can happen because of race conditions. For example,
1289 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1290 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001291 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1292 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001293 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001294 }
Paul Hu812e9212023-06-20 06:24:53 +00001295 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1296 if (request == null) {
1297 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1298 return false;
1299 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001300 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001301 Log.d(TAG, String.format(
1302 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001303 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001304 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001305 case IMDnsEventListener.SERVICE_FOUND: {
1306 final DiscoveryInfo info = (DiscoveryInfo) obj;
1307 final String name = info.serviceName;
1308 final String type = info.registrationType;
1309 servInfo = new NsdServiceInfo(name, type);
1310 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001311 if (foundNetId == 0L) {
1312 // Ignore services that do not have a Network: they are not usable
1313 // by apps, as they would need privileged permissions to use
1314 // interfaces that do not have an associated Network.
1315 break;
1316 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001317 if (foundNetId == INetd.DUMMY_NET_ID) {
1318 // Ignore services on the dummy0 interface: they are only seen when
1319 // discovering locally advertised services, and are not reachable
1320 // through that interface.
1321 break;
1322 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001323 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001324
1325 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001326 break;
paulhu2b9ed952022-02-10 21:58:32 +08001327 }
1328 case IMDnsEventListener.SERVICE_LOST: {
1329 final DiscoveryInfo info = (DiscoveryInfo) obj;
1330 final String name = info.serviceName;
1331 final String type = info.registrationType;
1332 final int lostNetId = info.netId;
1333 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001334 // The network could be set to null (netId 0) if it was torn down when the
1335 // service is lost
1336 // TODO: avoid returning null in that case, possibly by remembering
1337 // found services on the same interface index and their network at the time
1338 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001339 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001340 break;
paulhu2b9ed952022-02-10 21:58:32 +08001341 }
1342 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001343 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001344 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1345 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001346 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 break;
paulhu2b9ed952022-02-10 21:58:32 +08001348 case IMDnsEventListener.SERVICE_REGISTERED: {
1349 final RegistrationInfo info = (RegistrationInfo) obj;
1350 final String name = info.serviceName;
1351 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001352 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001353 break;
paulhu2b9ed952022-02-10 21:58:32 +08001354 }
1355 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001356 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001357 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1358 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001359 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001360 break;
paulhu2b9ed952022-02-10 21:58:32 +08001361 case IMDnsEventListener.SERVICE_RESOLVED: {
1362 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001363 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001364 final String fullName = info.serviceFullName;
1365 while (index < fullName.length() && fullName.charAt(index) != '.') {
1366 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001367 ++index;
1368 }
1369 ++index;
1370 }
paulhu2b9ed952022-02-10 21:58:32 +08001371 if (index >= fullName.length()) {
1372 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001373 break;
1374 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001375
paulhube186602022-04-12 07:18:23 +00001376 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001377 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001378 String type = rest.replace(".local.", "");
1379
Paul Hu30bd70d2023-02-07 13:20:56 +00001380 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001381 serviceInfo.setServiceName(name);
1382 serviceInfo.setServiceType(type);
1383 serviceInfo.setPort(info.port);
1384 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001385 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001386
Paul Hud44e1b72023-06-16 02:07:42 +00001387 stopResolveService(transactionId);
1388 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001389
Paul Hud44e1b72023-06-16 02:07:42 +00001390 final int transactionId2 = getUniqueId();
1391 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1392 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001393 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001394 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001395 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001396 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1397 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001398 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001399 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001400 }
1401 break;
paulhu2b9ed952022-02-10 21:58:32 +08001402 }
1403 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001404 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001405 stopResolveService(transactionId);
1406 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001407 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001408 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1409 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001410 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001411 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001412 break;
paulhu2b9ed952022-02-10 21:58:32 +08001413 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001414 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001415 stopGetAddrInfo(transactionId);
1416 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001417 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001418 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1419 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001420 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001421 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001422 break;
paulhu2b9ed952022-02-10 21:58:32 +08001423 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001424 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001425 final GetAddressInfo info = (GetAddressInfo) obj;
1426 final String address = info.address;
1427 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001428 InetAddress serviceHost = null;
1429 try {
paulhu2b9ed952022-02-10 21:58:32 +08001430 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001431 } catch (UnknownHostException e) {
1432 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1433 }
1434
1435 // If the resolved service is on an interface without a network, consider it
1436 // as a failure: it would not be usable by apps as they would need
1437 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001438 if (netId != NETID_UNSET && serviceHost != null) {
1439 clientInfo.mResolvedService.setHost(serviceHost);
1440 setServiceNetworkForCallback(clientInfo.mResolvedService,
1441 netId, info.interfaceIdx);
1442 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001443 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001444 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001445 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001446 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1447 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001448 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001449 }
Paul Hud44e1b72023-06-16 02:07:42 +00001450 stopGetAddrInfo(transactionId);
1451 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001452 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001453 break;
paulhu2b9ed952022-02-10 21:58:32 +08001454 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001455 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001456 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001457 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001458 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001459 }
Paul Hu019621e2023-01-13 23:26:49 +08001460
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001461 @Nullable
1462 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1463 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001464 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001465 final String[] typeArray = serviceInfo.getServiceType();
1466 final String joinedType;
1467 if (typeArray.length == 0
1468 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1469 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1470 + Arrays.toString(typeArray));
1471 return null;
1472 } else {
1473 joinedType = TextUtils.join(".",
1474 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1475 }
1476 final String serviceType;
1477 switch (code) {
1478 case NsdManager.SERVICE_FOUND:
1479 case NsdManager.SERVICE_LOST:
1480 // For consistency with historical behavior, discovered service types have
1481 // a dot at the end.
1482 serviceType = joinedType + ".";
1483 break;
1484 case RESOLVE_SERVICE_SUCCEEDED:
1485 // For consistency with historical behavior, resolved service types have
1486 // a dot at the beginning.
1487 serviceType = "." + joinedType;
1488 break;
1489 default:
1490 serviceType = joinedType;
1491 break;
1492 }
Paul Hu019621e2023-01-13 23:26:49 +08001493 final String serviceName = serviceInfo.getServiceInstanceName();
1494 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1495 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001496 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1497 // network for Tethering interface. In other words, the network == null means the
1498 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001499 setServiceNetworkForCallback(
1500 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001501 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001502 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001503 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001504 return servInfo;
1505 }
1506
1507 private boolean handleMdnsDiscoveryManagerEvent(
1508 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001509 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001510 if (clientInfo == null) {
1511 Log.e(TAG, String.format(
1512 "id %d for %d has no client mapping", transactionId, code));
1513 return false;
1514 }
1515
1516 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001517 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001518 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1519 if (request == null) {
1520 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1521 return false;
1522 }
1523
1524 // Deal with the discovery sent callback
1525 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1526 request.onQuerySent();
1527 return true;
1528 }
1529
1530 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001531 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1532 // Errors are already logged if null
1533 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001534 mServiceLogs.log(String.format(
1535 "MdnsDiscoveryManager event code=%s transactionId=%d",
1536 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001537 switch (code) {
1538 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001539 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001540 break;
1541 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001542 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001543 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001544 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1545 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001546 info.setPort(serviceInfo.getPort());
1547
1548 Map<String, String> attrs = serviceInfo.getAttributes();
1549 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1550 final String key = kv.getKey();
1551 try {
1552 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1553 } catch (IllegalArgumentException e) {
1554 Log.e(TAG, "Invalid attribute", e);
1555 }
1556 }
Handa Wang096e32e2024-01-14 08:21:28 +00001557 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001558 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001559 if (addresses.size() != 0) {
1560 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001561 request.setServiceFromCache(event.mIsServiceFromCache);
1562 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001563 } else {
1564 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001565 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001566 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1567 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001568 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001569 }
1570
1571 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001572 if (!(request instanceof DiscoveryManagerRequest)) {
1573 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1574 break;
1575 }
Paul Hud44e1b72023-06-16 02:07:42 +00001576 stopDiscoveryManagerRequest(
1577 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001578 break;
1579 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001580 case NsdManager.SERVICE_UPDATED: {
1581 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1582 info.setPort(serviceInfo.getPort());
1583
1584 Map<String, String> attrs = serviceInfo.getAttributes();
1585 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1586 final String key = kv.getKey();
1587 try {
1588 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1589 } catch (IllegalArgumentException e) {
1590 Log.e(TAG, "Invalid attribute", e);
1591 }
1592 }
1593
Handa Wang096e32e2024-01-14 08:21:28 +00001594 info.setHostname(getHostname(serviceInfo));
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001595 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001596 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001597 clientInfo.onServiceUpdated(clientRequestId, info, request);
1598 // Set the ServiceFromCache flag only if the service is actually being
1599 // retrieved from the cache. This flag should not be overridden by later
1600 // service updates, which may not be cached.
1601 if (event.mIsServiceFromCache) {
1602 request.setServiceFromCache(true);
1603 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001604 break;
1605 }
1606 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001607 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001608 break;
Paul Hu019621e2023-01-13 23:26:49 +08001609 default:
1610 return false;
1611 }
1612 return true;
1613 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001614 }
1615 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001616
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001617 @NonNull
1618 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1619 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1620 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1621 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1622 for (String ipv4Address : v4Addrs) {
1623 try {
1624 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1625 } catch (IllegalArgumentException e) {
1626 Log.wtf(TAG, "Invalid ipv4 address", e);
1627 }
1628 }
1629 for (String ipv6Address : v6Addrs) {
1630 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001631 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1632 ipv6Address);
1633 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1634 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001635 Log.wtf(TAG, "Invalid ipv6 address", e);
1636 }
1637 }
1638 return addresses;
1639 }
1640
Handa Wang096e32e2024-01-14 08:21:28 +00001641 @NonNull
1642 private static String getHostname(@NonNull MdnsServiceInfo serviceInfo) {
1643 String[] hostname = serviceInfo.getHostName();
1644 // Strip the "local" top-level domain.
1645 if (hostname.length >= 2 && hostname[hostname.length - 1].equals("local")) {
1646 hostname = Arrays.copyOf(hostname, hostname.length - 1);
1647 }
1648 return String.join(".", hostname);
1649 }
1650
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001651 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1652 switch (netId) {
1653 case NETID_UNSET:
1654 info.setNetwork(null);
1655 break;
1656 case INetd.LOCAL_NET_ID:
1657 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1658 // visible / usable for apps, so do not return it. Store the interface
1659 // index instead, so at least if the client tries to resolve the service
1660 // with that NsdServiceInfo, it will be done on the same interface.
1661 // If they recreate the NsdServiceInfo themselves, resolution would be
1662 // done on all interfaces as before T, which should also work.
1663 info.setNetwork(null);
1664 info.setInterfaceIndex(ifaceIdx);
1665 break;
1666 default:
1667 info.setNetwork(new Network(netId));
1668 }
1669 }
1670
paulhube186602022-04-12 07:18:23 +00001671 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1672 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1673 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1674 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1675 private String unescape(String s) {
1676 StringBuilder sb = new StringBuilder(s.length());
1677 for (int i = 0; i < s.length(); ++i) {
1678 char c = s.charAt(i);
1679 if (c == '\\') {
1680 if (++i >= s.length()) {
1681 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1682 break;
1683 }
1684 c = s.charAt(i);
1685 if (c != '.' && c != '\\') {
1686 if (i + 2 >= s.length()) {
1687 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1688 break;
1689 }
1690 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1691 + (s.charAt(i + 2) - '0'));
1692 i += 2;
1693 }
1694 }
1695 sb.append(c);
1696 }
1697 return sb.toString();
1698 }
1699
Paul Hu7445e3d2023-03-03 15:14:00 +08001700 /**
1701 * Check the given service type is valid and construct it to a service type
1702 * which can use for discovery / resolution service.
1703 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001704 * <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 +08001705 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1706 * underscore; they are alphanumerical characters or dashes or underscore, except the
1707 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1708 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001709 * <p>The subtypes may also be specified with a comma after the service type, for example
1710 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001711 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001712 * @param serviceType the request service type for discovery / resolution service
1713 * @return constructed service type or null if the given service type is invalid.
1714 */
1715 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001716 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001717 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001718 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001719 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1720 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001721 final String queryType = matcher.group(2);
1722 // Use the subtype at the beginning
1723 if (matcher.group(1) != null) {
1724 return new Pair<>(queryType, List.of(matcher.group(1)));
1725 }
1726 // Use the subtypes at the end
1727 final String subTypesStr = matcher.group(3);
1728 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1729 final String[] subTypes = subTypesStr.substring(1).split(",");
1730 return new Pair<>(queryType, List.of(subTypes));
1731 }
1732
1733 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001734 }
1735
Handa Wang096e32e2024-01-14 08:21:28 +00001736 /**
1737 * Checks if the hostname is valid.
1738 *
1739 * <p>For now NsdService only allows single-label hostnames conforming to RFC 1035. In other
1740 * words, the hostname should be at most 63 characters long and it only contains letters, digits
1741 * and hyphens.
1742 */
1743 public static boolean checkHostname(@Nullable String hostname) {
1744 if (hostname == null) {
1745 return true;
1746 }
1747 String HOSTNAME_REGEX = "^[a-zA-Z]([a-zA-Z0-9-_]{0,61}[a-zA-Z0-9])?$";
1748 return Pattern.compile(HOSTNAME_REGEX).matcher(hostname).matches();
1749 }
1750
Kangping Dong5af24b62023-12-10 21:41:16 +08001751 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1752 private static boolean checkSubtypeLabel(String subtype) {
1753 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1754 }
1755
Hugo Benichi803a2f02017-04-24 11:35:06 +09001756 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001757 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001758 this(ctx, handler, cleanupDelayMs, new Dependencies());
1759 }
1760
1761 @VisibleForTesting
1762 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001763 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001764 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001765 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001766 mNsdStateMachine.start();
Ken Chen80c9f6f2023-11-15 18:24:54 +08001767 // It can fail on V+ device since mdns native service provided by netd is removed.
1768 mMDnsManager = SdkLevel.isAtLeastV() ? null : ctx.getSystemService(MDnsManager.class);
paulhu2b9ed952022-02-10 21:58:32 +08001769 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001770 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001771
Paul Hu14667de2023-04-17 22:42:47 +08001772 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001773 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001774 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001775 // address events are received. When the netlink monitor starts, any IP addresses already
1776 // on the interfaces will not be seen. In practice, the network will not connect at boot
1777 // time As a result, all the netlink message should be observed if the netlink monitor
1778 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001779 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001780
1781 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1782 // startBootstrapServices).
1783 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1784 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1785 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1786 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1787 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1788 mRunningAppActiveImportanceCutoff);
1789
Paul Huf3fe3332023-10-16 17:13:25 +08001790 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1791 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1792 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1793 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1794 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001795 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1796 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001797 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1798 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001799 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1800 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001801 .setIsUnicastReplyEnabled(mDeps.isFeatureEnabled(
1802 mContext, MdnsFeatureFlags.NSD_UNICAST_REPLY_ENABLED))
1803 .setOverrideProvider(flag -> mDeps.isFeatureEnabled(
1804 mContext, FORCE_ENABLE_FLAG_FOR_TEST_PREFIX + flag))
Paul Huf3fe3332023-10-16 17:13:25 +08001805 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001806 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001807 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001808 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001809 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001810 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001811 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1812 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001813 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags,
1814 mContext);
Paul Hu777ed052023-06-19 13:35:15 +00001815 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001816 }
1817
1818 /**
1819 * Dependencies of NsdService, for injection in tests.
1820 */
1821 @VisibleForTesting
1822 public static class Dependencies {
1823 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001824 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001825 *
1826 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001827 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001828 */
1829 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001830 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001831 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001832 }
1833
1834 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001835 * Check whether the MdnsAdvertiser feature is enabled.
1836 *
1837 * @param context The global context information about an app environment.
1838 * @return true if the MdnsAdvertiser feature is enabled.
1839 */
1840 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001841 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001842 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001843 }
1844
1845 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001846 * Get the type allowlist flag value.
1847 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1848 */
1849 @Nullable
1850 public String getTypeAllowlistFlags() {
1851 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1852 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1853 }
1854
1855 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001856 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001857 */
1858 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001859 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001860 }
1861
1862 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001863 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1864 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001865 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1866 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001867 }
1868
1869 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001870 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1871 */
1872 public boolean isTrunkStableFeatureEnabled(String feature) {
1873 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1874 }
1875
1876 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001877 * @see MdnsDiscoveryManager
1878 */
1879 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001880 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001881 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1882 @NonNull MdnsFeatureFlags featureFlags) {
1883 return new MdnsDiscoveryManager(
1884 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001885 }
1886
1887 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001888 * @see MdnsAdvertiser
1889 */
1890 public MdnsAdvertiser makeMdnsAdvertiser(
1891 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001892 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001893 MdnsFeatureFlags featureFlags, Context context) {
1894 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags, context);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001895 }
1896
1897 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001898 * @see MdnsSocketProvider
1899 */
Paul Hu14667de2023-04-17 22:42:47 +08001900 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001901 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1902 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1903 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1904 }
1905
1906 /**
1907 * @see DeviceConfig#getInt(String, String, int)
1908 */
1909 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1910 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1911 }
1912
1913 /**
1914 * @see Binder#getCallingUid()
1915 */
1916 public int getCallingUid() {
1917 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001918 }
Paul Hu777ed052023-06-19 13:35:15 +00001919
1920 /**
1921 * @see NetworkNsdReportedMetrics
1922 */
Paul Hu508a0122023-09-11 15:31:33 +08001923 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1924 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001925 }
1926
1927 /**
1928 * @see MdnsUtils.Clock
1929 */
1930 public Clock makeClock() {
1931 return new Clock();
1932 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001933 }
1934
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001935 /**
1936 * Return whether a type is allowlisted to use the Java backend.
1937 * @param type The service type
1938 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1939 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1940 */
1941 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1942 @NonNull String flagPrefix) {
1943 if (type == null) return false;
1944 final String typesConfig = mDeps.getTypeAllowlistFlags();
1945 if (TextUtils.isEmpty(typesConfig)) return false;
1946
1947 final String mappingPrefix = type + ":";
1948 String mappedFlag = null;
1949 for (String mapping : TextUtils.split(typesConfig, ",")) {
1950 if (mapping.startsWith(mappingPrefix)) {
1951 mappedFlag = mapping.substring(mappingPrefix.length());
1952 break;
1953 }
1954 }
1955
1956 if (mappedFlag == null) return false;
1957
1958 return mDeps.isFeatureEnabled(mContext,
1959 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1960 }
1961
1962 private boolean useDiscoveryManagerForType(@Nullable String type) {
1963 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1964 }
1965
1966 private boolean useAdvertiserForType(@Nullable String type) {
1967 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1968 }
1969
paulhu1b35e822022-04-08 14:48:41 +08001970 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001971 HandlerThread thread = new HandlerThread(TAG);
1972 thread.start();
1973 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001974 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001975 return service;
1976 }
1977
paulhu2b9ed952022-02-10 21:58:32 +08001978 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1979 private final StateMachine mStateMachine;
1980
1981 MDnsEventCallback(StateMachine sm) {
1982 mStateMachine = sm;
1983 }
1984
1985 @Override
1986 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1987 mStateMachine.sendMessage(
1988 MDNS_SERVICE_EVENT, status.result, status.id, status);
1989 }
1990
1991 @Override
1992 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1993 mStateMachine.sendMessage(
1994 MDNS_SERVICE_EVENT, status.result, status.id, status);
1995 }
1996
1997 @Override
1998 public void onServiceResolutionStatus(final ResolutionInfo status) {
1999 mStateMachine.sendMessage(
2000 MDNS_SERVICE_EVENT, status.result, status.id, status);
2001 }
2002
2003 @Override
2004 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
2005 mStateMachine.sendMessage(
2006 MDNS_SERVICE_EVENT, status.result, status.id, status);
2007 }
2008
2009 @Override
2010 public int getInterfaceVersion() throws RemoteException {
2011 return this.VERSION;
2012 }
2013
2014 @Override
2015 public String getInterfaceHash() throws RemoteException {
2016 return this.HASH;
2017 }
2018 }
2019
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002020 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
2021 final String targetInterface = offloadEngineInfo.mInterfaceName;
2022 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
2023 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
2024 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
2025 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
2026 try {
2027 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
2028 } catch (RemoteException e) {
2029 // Can happen in regular cases, do not log a stacktrace
2030 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
2031 }
2032 }
2033 }
2034
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002035 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
2036 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
2037 final int count = mOffloadEngines.beginBroadcast();
2038 try {
2039 for (int i = 0; i < count; i++) {
2040 final OffloadEngineInfo offloadEngineInfo =
2041 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
2042 final String interfaceName = offloadEngineInfo.mInterfaceName;
2043 if (!targetInterfaceName.equals(interfaceName)
2044 || ((offloadEngineInfo.mOffloadType
2045 & offloadServiceInfo.getOffloadType()) == 0)) {
2046 continue;
2047 }
2048 try {
2049 if (isRemove) {
2050 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
2051 offloadServiceInfo);
2052 } else {
2053 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
2054 offloadServiceInfo);
2055 }
2056 } catch (RemoteException e) {
2057 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002058 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002059 }
2060 }
2061 } finally {
2062 mOffloadEngines.finishBroadcast();
2063 }
2064 }
2065
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002066 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002067 // TODO: add a callback to notify when a service is being added on each interface (as soon
2068 // as probing starts), and call mOffloadCallbacks. This callback is for
2069 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2070
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002071 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002072 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2073 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2074 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002075 if (clientInfo == null) return;
2076
Paul Hud44e1b72023-06-16 02:07:42 +00002077 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2078 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002079
Handa Wang096e32e2024-01-14 08:21:28 +00002080 // onRegisterServiceSucceeded only has the service name and hostname in its info. This
2081 // aligns with historical behavior.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002082 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Handa Wang096e32e2024-01-14 08:21:28 +00002083 cbInfo.setHostname(registeredInfo.getHostname());
Paul Hu777ed052023-06-19 13:35:15 +00002084 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002085 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002086 }
2087
2088 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002089 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2090 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002091 if (clientInfo == null) return;
2092
Paul Hud44e1b72023-06-16 02:07:42 +00002093 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2094 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002095 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002096 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2097 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002098 }
2099
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002100 @Override
2101 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2102 @NonNull OffloadServiceInfo offloadServiceInfo) {
2103 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2104 }
2105
2106 @Override
2107 public void onOffloadStop(@NonNull String interfaceName,
2108 @NonNull OffloadServiceInfo offloadServiceInfo) {
2109 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2110 }
2111
Paul Hud44e1b72023-06-16 02:07:42 +00002112 private ClientInfo getClientInfoOrLog(int transactionId) {
2113 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002114 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002115 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002116 }
2117 return clientInfo;
2118 }
2119
Paul Hud44e1b72023-06-16 02:07:42 +00002120 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2121 final int clientRequestId = info.getClientRequestId(transactionId);
2122 if (clientRequestId < 0) {
2123 Log.e(TAG, String.format(
2124 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002125 }
Paul Hud44e1b72023-06-16 02:07:42 +00002126 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002127 }
2128 }
2129
Paul Hu2e0a88c2023-03-09 16:05:01 +08002130 private static class ConnectorArgs {
2131 @NonNull public final NsdServiceConnector connector;
2132 @NonNull public final INsdManagerCallback callback;
2133 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002134 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002135
2136 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002137 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002138 this.connector = connector;
2139 this.callback = callback;
2140 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002141 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002142 }
2143 }
2144
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002145 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002146 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002147 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002148 final int uid = mDeps.getCallingUid();
2149 if (cb == null) {
2150 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2151 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002152 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002153 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002154 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002155 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002156 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002157 }
2158
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002159 private static class ListenerArgs {
2160 public final NsdServiceConnector connector;
2161 public final NsdServiceInfo serviceInfo;
2162 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2163 this.connector = connector;
2164 this.serviceInfo = serviceInfo;
2165 }
2166 }
2167
Yuyang Huang86d083f2023-12-12 19:56:41 +09002168 private static class AdvertisingArgs {
2169 public final NsdServiceConnector connector;
2170 public final AdvertisingRequest advertisingRequest;
2171
2172 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2173 this.connector = connector;
2174 this.advertisingRequest = advertisingRequest;
2175 }
2176 }
2177
Kangping Dong1f1a3792023-12-10 22:05:04 +08002178 private static final class DiscoveryArgs {
2179 public final NsdServiceConnector connector;
2180 public final DiscoveryRequest discoveryRequest;
2181 DiscoveryArgs(NsdServiceConnector connector, DiscoveryRequest discoveryRequest) {
2182 this.connector = connector;
2183 this.discoveryRequest = discoveryRequest;
2184 }
2185 }
2186
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002187 private class NsdServiceConnector extends INsdServiceConnector.Stub
2188 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002189
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002190 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002191 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2192 throws RemoteException {
Handa Wang096e32e2024-01-14 08:21:28 +00002193 NsdManager.checkServiceInfoForRegistration(advertisingRequest.getServiceInfo());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002194 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2195 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002196 new AdvertisingArgs(this, advertisingRequest)
2197 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002198 }
2199
2200 @Override
2201 public void unregisterService(int listenerKey) {
2202 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2203 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002204 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002205 }
2206
2207 @Override
Kangping Dong1f1a3792023-12-10 22:05:04 +08002208 public void discoverServices(int listenerKey, DiscoveryRequest discoveryRequest) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002209 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2210 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
Kangping Dong1f1a3792023-12-10 22:05:04 +08002211 new DiscoveryArgs(this, discoveryRequest)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002212 }
2213
2214 @Override
2215 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002216 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2217 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002218 }
2219
2220 @Override
2221 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2222 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2223 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2224 new ListenerArgs(this, serviceInfo)));
2225 }
2226
2227 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002228 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002229 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2230 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002231 }
2232
2233 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002234 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2235 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2236 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2237 new ListenerArgs(this, serviceInfo)));
2238 }
2239
2240 @Override
2241 public void unregisterServiceInfoCallback(int listenerKey) {
2242 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2243 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002244 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002245 }
2246
2247 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002248 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002249 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2250 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002251 }
2252
2253 @Override
2254 public void binderDied() {
2255 mNsdStateMachine.sendMessage(
2256 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002257
2258 }
2259
2260 @Override
2261 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2262 @OffloadEngine.OffloadCapability long offloadCapabilities,
2263 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002264 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002265 Objects.requireNonNull(ifaceName);
2266 Objects.requireNonNull(cb);
2267 mNsdStateMachine.sendMessage(
2268 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2269 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2270 offloadTypes)));
2271 }
2272
2273 @Override
2274 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002275 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002276 Objects.requireNonNull(cb);
2277 mNsdStateMachine.sendMessage(
2278 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002279 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002280
2281 private static void checkOffloadEnginePermission(Context context) {
2282 if (!SdkLevel.isAtLeastT()) {
2283 throw new SecurityException("API is not available in before API level 33");
2284 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002285
Ken Chena7bae552023-12-27 11:40:57 +08002286 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2287 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2288
2289 if (SdkLevel.isAtLeastV()) {
2290 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2291 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2292 } else if (SdkLevel.isAtLeastU()) {
2293 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2294 // permission instead.
2295 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002296 }
2297
Ken Chena7bae552023-12-27 11:40:57 +08002298 if (PermissionUtils.checkAnyPermissionOf(context,
2299 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002300 return;
2301 }
2302 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002303 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002304 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002305 }
2306
Hugo Benichi912db992017-04-24 16:41:03 +09002307 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002308 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002309 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002310 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2311 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002312 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002313 }
2314
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002315 private int getUniqueId() {
2316 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2317 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002318 }
2319
Paul Hud44e1b72023-06-16 02:07:42 +00002320 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002321 if (mMDnsManager == null) {
2322 Log.wtf(TAG, "registerService: mMDnsManager is null");
2323 return false;
2324 }
2325
Hugo Benichi6d706442017-04-24 16:19:58 +09002326 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002327 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002328 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002329 String name = service.getServiceName();
2330 String type = service.getServiceType();
2331 int port = service.getPort();
2332 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002333 final int registerInterface = getNetworkInterfaceIndex(service);
2334 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002335 Log.e(TAG, "Interface to register service on not found");
2336 return false;
2337 }
Paul Hud44e1b72023-06-16 02:07:42 +00002338 return mMDnsManager.registerService(
2339 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002340 }
2341
Paul Hud44e1b72023-06-16 02:07:42 +00002342 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002343 if (mMDnsManager == null) {
2344 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2345 return false;
2346 }
Paul Hud44e1b72023-06-16 02:07:42 +00002347 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002348 }
2349
Kangping Dong1f1a3792023-12-10 22:05:04 +08002350 private boolean discoverServices(int transactionId, DiscoveryRequest discoveryRequest) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002351 if (mMDnsManager == null) {
2352 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2353 return false;
2354 }
2355
Kangping Dong1f1a3792023-12-10 22:05:04 +08002356 final String type = discoveryRequest.getServiceType();
2357 final int discoverInterface = getNetworkInterfaceIndex(discoveryRequest);
2358 if (discoveryRequest.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002359 Log.e(TAG, "Interface to discover service on not found");
2360 return false;
2361 }
Paul Hud44e1b72023-06-16 02:07:42 +00002362 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002363 }
2364
Paul Hud44e1b72023-06-16 02:07:42 +00002365 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002366 if (mMDnsManager == null) {
2367 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2368 return false;
2369 }
Paul Hud44e1b72023-06-16 02:07:42 +00002370 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002371 }
2372
Paul Hud44e1b72023-06-16 02:07:42 +00002373 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002374 if (mMDnsManager == null) {
2375 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2376 return false;
2377 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002378 final String name = service.getServiceName();
2379 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002380 final int resolveInterface = getNetworkInterfaceIndex(service);
2381 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002382 Log.e(TAG, "Interface to resolve service on not found");
2383 return false;
2384 }
Paul Hud44e1b72023-06-16 02:07:42 +00002385 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002386 }
2387
2388 /**
2389 * Guess the interface to use to resolve or discover a service on a specific network.
2390 *
2391 * This is an imperfect guess, as for example the network may be gone or not yet fully
2392 * registered. This is fine as failing is correct if the network is gone, and a client
2393 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2394 * this is to support the legacy mdnsresponder implementation, which historically resolved
2395 * services on an unspecified network.
2396 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002397 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2398 final Network network = serviceInfo.getNetwork();
2399 if (network == null) {
2400 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2401 // provided by NsdService from discovery results, and the service was found on an
2402 // interface that has no app-usable Network).
2403 if (serviceInfo.getInterfaceIndex() != 0) {
2404 return serviceInfo.getInterfaceIndex();
2405 }
2406 return IFACE_IDX_ANY;
2407 }
Kangping Dong1f1a3792023-12-10 22:05:04 +08002408 return getNetworkInterfaceIndex(network);
2409 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002410
Kangping Dong1f1a3792023-12-10 22:05:04 +08002411 /**
2412 * Returns the interface to use to discover a service on a specific network, or {@link
2413 * IFACE_IDX_ANY} if no network is specified.
2414 */
2415 private int getNetworkInterfaceIndex(DiscoveryRequest discoveryRequest) {
2416 final Network network = discoveryRequest.getNetwork();
2417 if (network == null) {
2418 return IFACE_IDX_ANY;
2419 }
2420 return getNetworkInterfaceIndex(network);
2421 }
2422
2423 /**
2424 * Returns the interface of a specific network, or {@link IFACE_IDX_ANY} if no interface is
2425 * associated with {@code network}.
2426 */
2427 private int getNetworkInterfaceIndex(@NonNull Network network) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002428 String interfaceName = getNetworkInterfaceName(network);
2429 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002430 return IFACE_IDX_ANY;
2431 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002432 return getNetworkInterfaceIndexByName(interfaceName);
2433 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002434
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002435 private String getNetworkInterfaceName(@Nullable Network network) {
2436 if (network == null) {
2437 return null;
2438 }
2439 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2440 if (cm == null) {
2441 Log.wtf(TAG, "No ConnectivityManager");
2442 return null;
2443 }
2444 final LinkProperties lp = cm.getLinkProperties(network);
2445 if (lp == null) {
2446 return null;
2447 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002448 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002449 return lp.getInterfaceName();
2450 }
2451
2452 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002453 final NetworkInterface iface;
2454 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002455 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002456 } catch (SocketException e) {
2457 Log.e(TAG, "Error querying interface", e);
2458 return IFACE_IDX_ANY;
2459 }
2460
2461 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002462 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002463 return IFACE_IDX_ANY;
2464 }
2465
2466 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002467 }
2468
Paul Hud44e1b72023-06-16 02:07:42 +00002469 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002470 if (mMDnsManager == null) {
2471 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2472 return false;
2473 }
Paul Hud44e1b72023-06-16 02:07:42 +00002474 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002475 }
2476
Paul Hud44e1b72023-06-16 02:07:42 +00002477 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002478 if (mMDnsManager == null) {
2479 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2480 return false;
2481 }
Paul Hud44e1b72023-06-16 02:07:42 +00002482 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002483 }
2484
Paul Hud44e1b72023-06-16 02:07:42 +00002485 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002486 if (mMDnsManager == null) {
2487 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2488 return false;
2489 }
Paul Hud44e1b72023-06-16 02:07:42 +00002490 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002491 }
2492
2493 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002494 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2495 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002496
Paul Hub2e67d32023-04-18 05:50:14 +00002497 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2498 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002499 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002500
2501 // Dump service and clients logs
2502 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002503 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002504 pw.increaseIndent();
2505 mServiceLogs.reverseDump(pw);
2506 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002507 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002508
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002509 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002510 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002511 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002512 private int mFoundServiceCount = 0;
2513 private int mLostServiceCount = 0;
2514 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002515 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002516 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002517
Paul Hu812e9212023-06-20 06:24:53 +00002518 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002519 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002520 mStartTimeMs = startTimeMs;
2521 }
2522
Paul Hu812e9212023-06-20 06:24:53 +00002523 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002524 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002525 }
Paul Hu812e9212023-06-20 06:24:53 +00002526
2527 public void onServiceFound(String serviceName) {
2528 mFoundServiceCount++;
2529 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2530 mServices.add(serviceName);
2531 }
2532 }
2533
2534 public void onServiceLost() {
2535 mLostServiceCount++;
2536 }
2537
2538 public int getFoundServiceCount() {
2539 return mFoundServiceCount;
2540 }
2541
2542 public int getLostServiceCount() {
2543 return mLostServiceCount;
2544 }
2545
2546 public int getServicesCount() {
2547 return mServices.size();
2548 }
Paul Hua6bc4632023-06-26 01:18:29 +00002549
2550 public void setServiceFromCache(boolean isServiceFromCache) {
2551 mIsServiceFromCache = isServiceFromCache;
2552 }
2553
2554 public boolean isServiceFromCache() {
2555 return mIsServiceFromCache;
2556 }
Paul Hubad6fe92023-07-24 21:25:22 +08002557
2558 public void onQuerySent() {
2559 mSentQueryCount++;
2560 }
2561
2562 public int getSentQueryCount() {
2563 return mSentQueryCount;
2564 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002565 }
2566
2567 private static class LegacyClientRequest extends ClientRequest {
2568 private final int mRequestCode;
2569
Paul Hu812e9212023-06-20 06:24:53 +00002570 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2571 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002572 mRequestCode = requestCode;
2573 }
2574 }
2575
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002576 private abstract static class JavaBackendClientRequest extends ClientRequest {
2577 @Nullable
2578 private final Network mRequestedNetwork;
2579
Paul Hu777ed052023-06-19 13:35:15 +00002580 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002581 long startTimeMs) {
2582 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002583 mRequestedNetwork = requestedNetwork;
2584 }
2585
2586 @Nullable
2587 public Network getRequestedNetwork() {
2588 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002589 }
2590 }
2591
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002592 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002593 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002594 long startTimeMs) {
2595 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002596 }
2597 }
2598
2599 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002600 @NonNull
2601 private final MdnsListener mListener;
2602
Paul Hud44e1b72023-06-16 02:07:42 +00002603 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002604 @Nullable Network requestedNetwork, long startTimeMs) {
2605 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002606 mListener = listener;
2607 }
2608 }
2609
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002610 /* Information tracked per client */
2611 private class ClientInfo {
2612
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002613 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002614 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002615 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002616 private NsdServiceInfo mResolvedService;
2617
Paul Hud44e1b72023-06-16 02:07:42 +00002618 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002619 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002620
Luke Huangf7277ed2021-07-12 21:15:10 +08002621 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002622 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002623 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002624 // The flag of using java backend if the client's target SDK >= U
2625 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002626 // Store client logs
2627 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002628 // Report the nsd metrics data
2629 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002630
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002631 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002632 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002633 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002634 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002635 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002636 mClientLogs = sharedLog;
2637 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002638 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002639 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002640
2641 @Override
2642 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002643 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002644 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002645 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002646 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2647 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002648 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002649 int clientRequestId = mClientRequests.keyAt(i);
2650 sb.append("clientRequestId ")
2651 .append(clientRequestId)
2652 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002653 .append(" type ").append(
2654 mClientRequests.valueAt(i).getClass().getSimpleName())
2655 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002656 }
2657 return sb.toString();
2658 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002659
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002660 private boolean isPreSClient() {
2661 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002662 }
2663
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002664 private void setPreSClient() {
2665 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002666 }
2667
Paul Hu812e9212023-06-20 06:24:53 +00002668 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002669 final MdnsListener listener =
2670 ((DiscoveryManagerRequest) request).mListener;
2671 mMdnsDiscoveryManager.unregisterListener(
2672 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002673 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002674 }
2675
Dave Plattfeff2af2014-03-07 14:48:22 -08002676 // Remove any pending requests from the global map when we get rid of a client,
2677 // and send cancellations to the daemon.
2678 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002679 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002680 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002681 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002682 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002683 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002684 final int transactionId = request.mTransactionId;
2685 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002686 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002687 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2688 + " transactionId " + transactionId
2689 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002690 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002691
2692 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002693 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2694 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002695 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002696 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2697 request.getFoundServiceCount(),
2698 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002699 request.getServicesCount(),
2700 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002701 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002702 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002703 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002704 } else if (listener instanceof ServiceInfoListener) {
2705 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2706 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2707 request.getFoundServiceCount(),
2708 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002709 request.isServiceFromCache(),
2710 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002711 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002712 continue;
2713 }
2714
2715 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002716 final AdvertiserMetrics metrics =
2717 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002718 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002719 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002720 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2721 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2722 metrics.mConflictDuringProbingCount,
2723 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002724 continue;
2725 }
2726
2727 if (!(request instanceof LegacyClientRequest)) {
2728 throw new IllegalStateException("Unknown request type: " + request.getClass());
2729 }
2730
2731 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002732 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002733 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002734 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002735 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2736 request.getFoundServiceCount(),
2737 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002738 request.getServicesCount(),
2739 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002740 break;
2741 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002742 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002743 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002744 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002745 break;
2746 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002747 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002748 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002749 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2750 NO_PACKET /* repliedRequestsCount */,
2751 NO_PACKET /* sentPacketCount */,
2752 0 /* conflictDuringProbingCount */,
2753 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002754 break;
2755 default:
2756 break;
2757 }
2758 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002759 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002760 updateMulticastLock();
2761 }
2762
2763 /**
2764 * Returns true if this client has any Java backend request that requests one of the given
2765 * networks.
2766 */
2767 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2768 for (int i = 0; i < mClientRequests.size(); i++) {
2769 final ClientRequest req = mClientRequests.valueAt(i);
2770 if (!(req instanceof JavaBackendClientRequest)) {
2771 continue;
2772 }
2773 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2774 .getRequestedNetwork();
2775 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2776 return true;
2777 }
2778 }
2779 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002780 }
2781
Paul Hud44e1b72023-06-16 02:07:42 +00002782 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2783 // transaction id, return the corresponding client request id.
2784 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002785 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002786 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002787 return mClientRequests.keyAt(i);
2788 }
Christopher Lane74411222014-04-25 18:39:07 -07002789 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002790 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002791 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002792
Paul Hub2e67d32023-04-18 05:50:14 +00002793 private void log(String message) {
2794 mClientLogs.log(message);
2795 }
2796
Paul Hu508a0122023-09-11 15:31:33 +08002797 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2798 return !(request instanceof DiscoveryManagerRequest)
2799 && !(request instanceof AdvertiserClientRequest);
2800 }
2801
Kangping Dong1f1a3792023-12-10 22:05:04 +08002802 void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest,
Paul Hu508a0122023-09-11 15:31:33 +08002803 ClientRequest request) {
2804 mMetrics.reportServiceDiscoveryStarted(
2805 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002806 try {
Kangping Dong1f1a3792023-12-10 22:05:04 +08002807 mCb.onDiscoverServicesStarted(listenerKey, discoveryRequest);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002808 } catch (RemoteException e) {
2809 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2810 }
2811 }
Paul Hu508a0122023-09-11 15:31:33 +08002812 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2813 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2814 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002815 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002816
Paul Hu508a0122023-09-11 15:31:33 +08002817 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2818 int transactionId, long durationMs) {
2819 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002820 try {
2821 mCb.onDiscoverServicesFailed(listenerKey, error);
2822 } catch (RemoteException e) {
2823 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2824 }
2825 }
2826
Paul Hu812e9212023-06-20 06:24:53 +00002827 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2828 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002829 try {
2830 mCb.onServiceFound(listenerKey, info);
2831 } catch (RemoteException e) {
2832 Log.e(TAG, "Error calling onServiceFound(", e);
2833 }
2834 }
2835
Paul Hu812e9212023-06-20 06:24:53 +00002836 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2837 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002838 try {
2839 mCb.onServiceLost(listenerKey, info);
2840 } catch (RemoteException e) {
2841 Log.e(TAG, "Error calling onServiceLost(", e);
2842 }
2843 }
2844
2845 void onStopDiscoveryFailed(int listenerKey, int error) {
2846 try {
2847 mCb.onStopDiscoveryFailed(listenerKey, error);
2848 } catch (RemoteException e) {
2849 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2850 }
2851 }
2852
Paul Hu812e9212023-06-20 06:24:53 +00002853 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2854 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002855 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002856 request.mTransactionId,
2857 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2858 request.getFoundServiceCount(),
2859 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002860 request.getServicesCount(),
2861 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002862 try {
2863 mCb.onStopDiscoverySucceeded(listenerKey);
2864 } catch (RemoteException e) {
2865 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2866 }
2867 }
2868
Paul Hu508a0122023-09-11 15:31:33 +08002869 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2870 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2871 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002872 }
2873
Paul Hu508a0122023-09-11 15:31:33 +08002874 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2875 int transactionId, long durationMs) {
2876 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002877 try {
2878 mCb.onRegisterServiceFailed(listenerKey, error);
2879 } catch (RemoteException e) {
2880 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2881 }
2882 }
2883
Paul Hu508a0122023-09-11 15:31:33 +08002884 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2885 ClientRequest request) {
2886 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2887 request.mTransactionId,
2888 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002889 try {
2890 mCb.onRegisterServiceSucceeded(listenerKey, info);
2891 } catch (RemoteException e) {
2892 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2893 }
2894 }
2895
2896 void onUnregisterServiceFailed(int listenerKey, int error) {
2897 try {
2898 mCb.onUnregisterServiceFailed(listenerKey, error);
2899 } catch (RemoteException e) {
2900 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2901 }
2902 }
2903
Paul Hu508a0122023-09-11 15:31:33 +08002904 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002905 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002906 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2907 request.mTransactionId,
2908 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002909 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2910 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002911 try {
2912 mCb.onUnregisterServiceSucceeded(listenerKey);
2913 } catch (RemoteException e) {
2914 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2915 }
2916 }
2917
Paul Hu508a0122023-09-11 15:31:33 +08002918 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2919 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2920 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002921 }
2922
Paul Hu508a0122023-09-11 15:31:33 +08002923 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2924 int transactionId, long durationMs) {
2925 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002926 try {
2927 mCb.onResolveServiceFailed(listenerKey, error);
2928 } catch (RemoteException e) {
2929 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2930 }
2931 }
2932
Paul Hua6bc4632023-06-26 01:18:29 +00002933 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2934 ClientRequest request) {
2935 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002936 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002937 request.mTransactionId,
2938 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002939 request.isServiceFromCache(),
2940 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002941 try {
2942 mCb.onResolveServiceSucceeded(listenerKey, info);
2943 } catch (RemoteException e) {
2944 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2945 }
2946 }
Paul Hub58deb72022-12-26 09:24:42 +00002947
2948 void onStopResolutionFailed(int listenerKey, int error) {
2949 try {
2950 mCb.onStopResolutionFailed(listenerKey, error);
2951 } catch (RemoteException e) {
2952 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2953 }
2954 }
2955
Paul Hu60149052023-07-31 14:26:08 +08002956 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2957 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002958 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002959 request.mTransactionId,
2960 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002961 try {
2962 mCb.onStopResolutionSucceeded(listenerKey);
2963 } catch (RemoteException e) {
2964 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2965 }
2966 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002967
2968 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002969 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002970 try {
2971 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2972 } catch (RemoteException e) {
2973 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2974 }
2975 }
2976
Paul Huddce5912023-08-01 10:26:49 +08002977 void onServiceInfoCallbackRegistered(int transactionId) {
2978 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2979 }
2980
2981 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2982 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002983 try {
2984 mCb.onServiceUpdated(listenerKey, info);
2985 } catch (RemoteException e) {
2986 Log.e(TAG, "Error calling onServiceUpdated", e);
2987 }
2988 }
2989
Paul Huddce5912023-08-01 10:26:49 +08002990 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2991 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002992 try {
2993 mCb.onServiceUpdatedLost(listenerKey);
2994 } catch (RemoteException e) {
2995 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2996 }
2997 }
2998
Paul Huddce5912023-08-01 10:26:49 +08002999 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
3000 mMetrics.reportServiceInfoCallbackUnregistered(
3001 request.mTransactionId,
3002 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
3003 request.getFoundServiceCount(),
3004 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08003005 request.isServiceFromCache(),
3006 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00003007 try {
3008 mCb.onServiceInfoCallbackUnregistered(listenerKey);
3009 } catch (RemoteException e) {
3010 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
3011 }
3012 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07003013 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003014}