blob: 1e234fe2af5f8fb377370e570a0ba3c1eb229643 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yuyang Huang33fa4d22023-02-14 22:59:37 +090019import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090020import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090022import static android.net.NetworkCapabilities.TRANSPORT_VPN;
23import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090024import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080025import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080026import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090027import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090028import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090029
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090030import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090031import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080032import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
33import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090034import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000035import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090036
Paul Hu23fa2022023-01-13 22:57:24 +080037import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080038import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090039import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090040import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080041import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070042import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090043import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090044import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080045import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090046import android.net.LinkProperties;
47import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080048import android.net.mdns.aidl.DiscoveryInfo;
49import android.net.mdns.aidl.GetAddressInfo;
50import android.net.mdns.aidl.IMDnsEventListener;
51import android.net.mdns.aidl.RegistrationInfo;
52import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070053import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090054import android.net.nsd.INsdManagerCallback;
55import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090056import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080057import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080059import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090060import android.net.nsd.OffloadEngine;
61import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090062import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000063import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090064import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090065import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080066import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090067import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070069import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090070import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090071import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070072import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090073import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080074import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090075import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090076import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090077import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070078import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070079
paulhua262cc12019-08-12 16:25:11 +080080import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000081import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080082import com.android.internal.util.State;
83import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000084import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090085import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090086import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080087import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090088import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080089import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000090import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090092import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090093import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080094import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090095import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090096import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080097import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080098import com.android.server.connectivity.mdns.MdnsSearchOptions;
99import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
100import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800101import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900102import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800103
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700104import java.io.FileDescriptor;
105import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900106import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700107import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900108import java.net.NetworkInterface;
109import java.net.SocketException;
110import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800111import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900112import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700113import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800114import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800115import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900116import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000117import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800118import java.util.regex.Matcher;
119import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700120
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700121/**
122 * Network Service Discovery Service handles remote service discovery operation requests by
123 * implementing the INsdManager interface.
124 *
125 * @hide
126 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900127@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700128public class NsdService extends INsdManager.Stub {
129 private static final String TAG = "NsdService";
130 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900131 /**
132 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
133 * implementation.
134 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800135 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800136 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700137
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900138 /**
139 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
140 * implementation.
141 */
142 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
143
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900144 /**
145 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
146 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
147 *
148 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
149 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
150 *
151 * In which case the flags:
152 * "mdns_discovery_manager_allowlist_mytype_version",
153 * "mdns_advertiser_allowlist_mytype_version",
154 * "mdns_discovery_manager_allowlist_othertype_version",
155 * "mdns_advertiser_allowlist_othertype_version"
156 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
157 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900158 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900159 *
160 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
161 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
162 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
163 */
164 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
165
166 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
167 "mdns_discovery_manager_allowlist_";
168 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
169 "mdns_advertiser_allowlist_";
170 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
171
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900172 @VisibleForTesting
173 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
174 "mdns_config_running_app_active_importance_cutoff";
175 @VisibleForTesting
176 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
177 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
178 private final int mRunningAppActiveImportanceCutoff;
179
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900180 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000181 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900182 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000183 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
184 @VisibleForTesting
185 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800186 private static final int NO_SENT_QUERY_COUNT = 0;
187 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800188 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700189
Hugo Benichi32be63d2017-04-05 14:06:11 +0900190 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900191 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800192 private final MDnsManager mMDnsManager;
193 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900194 @NonNull
195 private final Dependencies mDeps;
196 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800197 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900198 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800199 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900200 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800201 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900202 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900203 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000204 @NonNull
205 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800206 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800207 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800208 // state machine thread. If change this outside state machine, it will need to introduce
209 // synchronization.
210 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800211 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700212
213 /**
214 * Clients receiving asynchronous messages
215 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900216 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700217
Paul Hud44e1b72023-06-16 02:07:42 +0000218 /* A map from transaction(unique) id to client info */
219 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700220
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900221 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
222 @Nullable
223 private WifiManager.MulticastLock mHeldMulticastLock;
224 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
225 // (non-null), value is the requested Network (nullable)
226 @NonNull
227 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
228 @NonNull
229 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
230
Luke Huang05298582021-06-13 16:52:05 +0000231 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700232
Hugo Benichi32be63d2017-04-05 14:06:11 +0900233 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700234 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800235 // The count of the connected legacy clients.
236 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000237 // The number of client that ever connected.
238 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700239
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900240 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
241 new RemoteCallbackList<>();
242
243 private static class OffloadEngineInfo {
244 @NonNull final String mInterfaceName;
245 final long mOffloadCapabilities;
246 final long mOffloadType;
247 @NonNull final IOffloadEngine mOffloadEngine;
248
249 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
250 @NonNull String interfaceName, long capabilities, long offloadType) {
251 this.mOffloadEngine = offloadEngine;
252 this.mInterfaceName = interfaceName;
253 this.mOffloadCapabilities = capabilities;
254 this.mOffloadType = offloadType;
255 }
256 }
257
Paul Hu812e9212023-06-20 06:24:53 +0000258 @VisibleForTesting
259 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000260 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800261 protected final int mTransactionId;
262 @NonNull
263 protected final NsdServiceInfo mReqServiceInfo;
264 @NonNull
265 protected final String mListenedServiceType;
266
Paul Hud44e1b72023-06-16 02:07:42 +0000267 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800268 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000269 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800270 mTransactionId = transactionId;
271 mReqServiceInfo = reqServiceInfo;
272 mListenedServiceType = listenedServiceType;
273 }
274
275 @NonNull
276 public String getListenedServiceType() {
277 return mListenedServiceType;
278 }
279
280 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000281 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
282 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800283
284 @Override
285 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
286
287 @Override
288 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
289
290 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000291 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
292 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800293
294 @Override
295 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
296
297 @Override
298 public void onSearchStoppedWithError(int error) { }
299
300 @Override
301 public void onSearchFailedToStart() { }
302
303 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800304 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
305 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800306
307 @Override
308 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
309 }
310
311 private class DiscoveryListener extends MdnsListener {
312
Paul Hud44e1b72023-06-16 02:07:42 +0000313 DiscoveryListener(int clientRequestId, int transactionId,
314 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
315 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800316 }
317
318 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000319 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
320 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800321 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
322 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000323 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800324 }
325
326 @Override
327 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800328 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
329 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000330 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800331 }
Paul Hubad6fe92023-07-24 21:25:22 +0800332
333 @Override
334 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
335 int sentQueryTransactionId) {
336 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
337 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
338 }
Paul Hu23fa2022023-01-13 22:57:24 +0800339 }
340
Paul Hu75069ed2023-01-14 00:31:09 +0800341 private class ResolutionListener extends MdnsListener {
342
Paul Hud44e1b72023-06-16 02:07:42 +0000343 ResolutionListener(int clientRequestId, int transactionId,
344 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
345 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800346 }
347
348 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000349 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800350 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
351 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000352 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800353 }
Paul Hubad6fe92023-07-24 21:25:22 +0800354
355 @Override
356 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
357 int sentQueryTransactionId) {
358 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
359 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
360 }
Paul Hu75069ed2023-01-14 00:31:09 +0800361 }
362
Paul Hu30bd70d2023-02-07 13:20:56 +0000363 private class ServiceInfoListener extends MdnsListener {
364
Paul Hud44e1b72023-06-16 02:07:42 +0000365 ServiceInfoListener(int clientRequestId, int transactionId,
366 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
367 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000368 }
369
370 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000371 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
372 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000373 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
374 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000375 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000376 }
377
378 @Override
379 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
380 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
381 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000382 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
384
385 @Override
386 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
387 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
388 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000389 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000390 }
Paul Hubad6fe92023-07-24 21:25:22 +0800391
392 @Override
393 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
394 int sentQueryTransactionId) {
395 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
396 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
397 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000398 }
399
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900400 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
401 @Override
402 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
403 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
404 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
405 // filtering on such interfaces, so taking the multicast lock is not necessary to
406 // disable APF filtering of multicast.
407 if (socketNetwork == null
408 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
409 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
410 return;
411 }
412
413 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
414 updateMulticastLock();
415 }
416 }
417
418 @Override
419 public void onSocketDestroyed(@Nullable Network socketNetwork,
420 @NonNull MdnsInterfaceSocket socket) {
421 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
422 updateMulticastLock();
423 }
424 }
425 }
426
427 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
428 private final Handler mHandler;
429
430 private UidImportanceListener(Handler handler) {
431 mHandler = handler;
432 }
433
434 @Override
435 public void onUidImportance(int uid, int importance) {
436 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
437 }
438 }
439
440 private void handleUidImportanceChanged(int uid, int importance) {
441 // Lower importance values are more "important"
442 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
443 ? mRunningAppActiveUids.add(uid)
444 : mRunningAppActiveUids.remove(uid);
445 if (modified) {
446 updateMulticastLock();
447 }
448 }
449
450 /**
451 * Take or release the lock based on updated internal state.
452 *
453 * This determines whether the lock needs to be held based on
454 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
455 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
456 * updated.
457 */
458 private void updateMulticastLock() {
459 final int needsLockUid = getMulticastLockNeededUid();
460 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
461 final WifiManager wm = mContext.getSystemService(WifiManager.class);
462 if (wm == null) {
463 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
464 return;
465 }
466 mHeldMulticastLock = wm.createMulticastLock(TAG);
467 mHeldMulticastLock.acquire();
468 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
469 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
470 mHeldMulticastLock.release();
471 mHeldMulticastLock = null;
472 mServiceLogs.log("Released multicast lock");
473 }
474 }
475
476 /**
477 * @return The UID of an app requiring the multicast lock, or -1 if none.
478 */
479 private int getMulticastLockNeededUid() {
480 if (mWifiLockRequiredNetworks.size() == 0) {
481 // Return early if NSD is not active, or not on any relevant network
482 return -1;
483 }
Paul Hud44e1b72023-06-16 02:07:42 +0000484 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
485 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900486 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
487 // Ignore non-active UIDs
488 continue;
489 }
490
491 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
492 return clientInfo.mUid;
493 }
494 }
495 return -1;
496 }
497
Paul Hu019621e2023-01-13 23:26:49 +0800498 /**
499 * Data class of mdns service callback information.
500 */
501 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000502 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800503 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800504 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000505 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800506
Paul Hubad6fe92023-07-24 21:25:22 +0800507 MdnsEvent(int clientRequestId) {
508 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
509 }
510
511 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000512 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
513 }
514
Paul Hubad6fe92023-07-24 21:25:22 +0800515 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000516 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000517 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800518 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000519 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800520 }
521 }
522
Paul Hu77c11182023-10-23 16:17:32 +0800523 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700524 private class NsdStateMachine extends StateMachine {
525
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700526 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700527
528 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700529 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900530 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700531 }
532
Luke Huang92860f92021-06-23 06:29:30 +0000533 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800534 if (mIsDaemonStarted) {
535 if (DBG) Log.d(TAG, "Daemon is already started.");
536 return;
537 }
538 mMDnsManager.registerEventListener(mMDnsEventCallback);
539 mMDnsManager.startDaemon();
540 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000541 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000542 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000543 }
544
paulhu2b9ed952022-02-10 21:58:32 +0800545 private void maybeStopDaemon() {
546 if (!mIsDaemonStarted) {
547 if (DBG) Log.d(TAG, "Daemon has not been started.");
548 return;
549 }
550 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
551 mMDnsManager.stopDaemon();
552 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000553 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800554 }
555
Luke Huang92860f92021-06-23 06:29:30 +0000556 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000557 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000558 }
559
560 private void scheduleStop() {
561 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
562 }
563 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800564 // The native daemon should stay alive and can't be cleanup
565 // if any legacy client connected.
566 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000567 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000568 }
569 }
570
Luke Huang92860f92021-06-23 06:29:30 +0000571 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000572 this.removeMessages(NsdManager.DAEMON_CLEANUP);
573 }
574
Paul Hu23fa2022023-01-13 22:57:24 +0800575 private void maybeStartMonitoringSockets() {
576 if (mIsMonitoringSocketsStarted) {
577 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
578 return;
579 }
580
581 mMdnsSocketProvider.startMonitoringSockets();
582 mIsMonitoringSocketsStarted = true;
583 }
584
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900585 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
586 if (!mIsMonitoringSocketsStarted) return;
587 if (isAnyRequestActive()) return;
588
Paul Hu58f20602023-02-18 11:41:07 +0800589 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800590 mIsMonitoringSocketsStarted = false;
591 }
592
Hugo Benichi803a2f02017-04-24 11:35:06 +0900593 NsdStateMachine(String name, Handler handler) {
594 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800595 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800596 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900597 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700598 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700599 }
600
Irfan Sheriff75006652012-04-17 23:15:29 -0700601 class EnabledState extends State {
602 @Override
603 public void enter() {
604 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 }
606
607 @Override
608 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000609 // TODO: it is incorrect to stop the daemon without expunging all requests
610 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000611 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700612 }
613
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700614 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900615 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800616 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617 return true;
618 }
619 return false;
620 }
621
Paul Hu508a0122023-09-11 15:31:33 +0800622 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000623 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800624 final LegacyClientRequest request =
625 new LegacyClientRequest(transactionId, what, startTimeMs);
626 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000627 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000628 // Remove the cleanup event because here comes a new request.
629 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800630 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700631 }
632
Paul Hud44e1b72023-06-16 02:07:42 +0000633 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900634 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000635 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000636 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000637 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900638 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800639 }
640
Paul Hud44e1b72023-06-16 02:07:42 +0000641 private void removeRequestMap(
642 int clientRequestId, int transactionId, ClientInfo clientInfo) {
643 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900644 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000645 clientInfo.mClientRequests.remove(clientRequestId);
646 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900647
648 if (existing instanceof LegacyClientRequest) {
649 maybeScheduleStop();
650 } else {
651 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900652 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900653 }
654 }
655
Paul Hu508a0122023-09-11 15:31:33 +0800656 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
657 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900658 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800659 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
660 listener, requestedNetwork, mClock.elapsedRealtime());
661 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000662 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900663 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800664 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800665 }
666
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900667 /**
668 * Truncate a service name to up to 63 UTF-8 bytes.
669 *
670 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
671 * names used in registerService follows historical behavior (see mdnsresponder
672 * handle_regservice_request).
673 */
674 @NonNull
675 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900676 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800677 }
678
Paul Hud44e1b72023-06-16 02:07:42 +0000679 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
680 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800681 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000682 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800683 }
684
Paul Hu77c11182023-10-23 16:17:32 +0800685 private ClientInfo getClientInfoForReply(Message msg) {
686 final ListenerArgs args = (ListenerArgs) msg.obj;
687 return mClients.get(args.connector);
688 }
689
Irfan Sheriff75006652012-04-17 23:15:29 -0700690 @Override
691 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900692 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000693 final int transactionId;
694 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900695 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900696 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700697 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800698 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800699 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900700 args = (ListenerArgs) msg.obj;
701 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000702 // If the binder death notification for a INsdManagerCallback was received
703 // before any calls are received by NsdService, the clientInfo would be
704 // cleared and cause NPE. Add a null check here to prevent this corner case.
705 if (clientInfo == null) {
706 Log.e(TAG, "Unknown connector in discovery");
707 break;
708 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700709
710 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800711 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
712 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700713 break;
714 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700715
Paul Hu23fa2022023-01-13 22:57:24 +0800716 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000717 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900718 final Pair<String, String> typeAndSubtype =
719 parseTypeAndSubtype(info.getServiceType());
720 final String serviceType = typeAndSubtype == null
721 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800722 if (clientInfo.mUseJavaBackend
723 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900724 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800725 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800726 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
727 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800728 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700729 }
Paul Hu23fa2022023-01-13 22:57:24 +0800730
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900731 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800732 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000733 final MdnsListener listener = new DiscoveryListener(clientRequestId,
734 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900735 final MdnsSearchOptions.Builder optionsBuilder =
736 MdnsSearchOptions.newBuilder()
737 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900738 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900739 .setIsPassiveMode(true);
740 if (typeAndSubtype.second != null) {
741 // The parsing ensures subtype starts with an underscore.
742 // MdnsSearchOptions expects the underscore to not be present.
743 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
744 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900745 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900746 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800747 final ClientRequest request = storeDiscoveryManagerRequestMap(
748 clientRequestId, transactionId, listener, clientInfo,
749 info.getNetwork());
750 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000751 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000752 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700753 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800754 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000755 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800756 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000757 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800758 + info.getServiceType());
759 }
Paul Hu508a0122023-09-11 15:31:33 +0800760 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
761 transactionId, clientInfo, msg.what,
762 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000763 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800764 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800765 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000766 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800767 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
768 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800769 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700770 }
771 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800772 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900773 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800774 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900775 args = (ListenerArgs) msg.obj;
776 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000777 // If the binder death notification for a INsdManagerCallback was received
778 // before any calls are received by NsdService, the clientInfo would be
779 // cleared and cause NPE. Add a null check here to prevent this corner case.
780 if (clientInfo == null) {
781 Log.e(TAG, "Unknown connector in stop discovery");
782 break;
783 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700784
Paul Hud44e1b72023-06-16 02:07:42 +0000785 final ClientRequest request =
786 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900787 if (request == null) {
788 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700789 break;
790 }
Paul Hud44e1b72023-06-16 02:07:42 +0000791 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900792 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
793 // point, so this needs to check the type of the original request to
794 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900795 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000796 stopDiscoveryManagerRequest(
797 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000798 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000799 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700800 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000801 removeRequestMap(clientRequestId, transactionId, clientInfo);
802 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000803 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800804 } else {
805 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000806 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800807 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700808 }
809 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900810 }
811 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800812 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900813 args = (ListenerArgs) msg.obj;
814 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000815 // If the binder death notification for a INsdManagerCallback was received
816 // before any calls are received by NsdService, the clientInfo would be
817 // cleared and cause NPE. Add a null check here to prevent this corner case.
818 if (clientInfo == null) {
819 Log.e(TAG, "Unknown connector in registration");
820 break;
821 }
822
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700823 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800824 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
825 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700826 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700827 }
828
Paul Hud44e1b72023-06-16 02:07:42 +0000829 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900830 final NsdServiceInfo serviceInfo = args.serviceInfo;
831 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900832 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
833 final String registerServiceType = typeSubtype == null
834 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800835 if (clientInfo.mUseJavaBackend
836 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900837 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900838 if (registerServiceType == null) {
839 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800840 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
841 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900842 break;
843 }
844 serviceInfo.setServiceType(registerServiceType);
845 serviceInfo.setServiceName(truncateServiceName(
846 serviceInfo.getServiceName()));
847
848 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900849 // TODO: pass in the subtype as well. Including the subtype in the
850 // service type would generate service instance names like
851 // Name._subtype._sub._type._tcp, which is incorrect
852 // (it should be Name._type._tcp).
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900853 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
854 typeSubtype.second,
855 MdnsAdvertisingOptions.newBuilder().build());
Paul Hud44e1b72023-06-16 02:07:42 +0000856 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900857 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700858 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900859 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000860 if (registerService(transactionId, serviceInfo)) {
861 if (DBG) {
862 Log.d(TAG, "Register " + clientRequestId
863 + " " + transactionId);
864 }
Paul Hua6bc4632023-06-26 01:18:29 +0000865 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
866 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900867 // Return success after mDns reports success
868 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000869 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800870 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
871 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900872 }
873
Irfan Sheriff75006652012-04-17 23:15:29 -0700874 }
875 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900876 }
877 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800878 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900879 args = (ListenerArgs) msg.obj;
880 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000881 // If the binder death notification for a INsdManagerCallback was received
882 // before any calls are received by NsdService, the clientInfo would be
883 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900884 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800885 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700886 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700887 }
Paul Hud44e1b72023-06-16 02:07:42 +0000888 final ClientRequest request =
889 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900890 if (request == null) {
891 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
892 break;
893 }
Paul Hud44e1b72023-06-16 02:07:42 +0000894 transactionId = request.mTransactionId;
895 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900896
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900897 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
898 // so this needs to check the type of the original request to unregister
899 // instead of looking at the flag value.
900 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800901 final AdvertiserMetrics metrics =
902 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000903 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800904 clientInfo.onUnregisterServiceSucceeded(
905 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700906 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000907 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800908 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800909 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
910 NO_PACKET /* sentPacketCount */,
911 0 /* conflictDuringProbingCount */,
912 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900913 } else {
914 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000915 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900916 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700917 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700918 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900919 }
Paul Hu75069ed2023-01-14 00:31:09 +0800920 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800921 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900922 args = (ListenerArgs) msg.obj;
923 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000924 // If the binder death notification for a INsdManagerCallback was received
925 // before any calls are received by NsdService, the clientInfo would be
926 // cleared and cause NPE. Add a null check here to prevent this corner case.
927 if (clientInfo == null) {
928 Log.e(TAG, "Unknown connector in resolution");
929 break;
930 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700931
Paul Hu75069ed2023-01-14 00:31:09 +0800932 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000933 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900934 final Pair<String, String> typeSubtype =
935 parseTypeAndSubtype(info.getServiceType());
936 final String serviceType = typeSubtype == null
937 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800938 if (clientInfo.mUseJavaBackend
939 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900940 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800941 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800942 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
943 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800944 break;
945 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900946 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800947
948 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000949 final MdnsListener listener = new ResolutionListener(clientRequestId,
950 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800951 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
952 .setNetwork(info.getNetwork())
953 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900954 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900955 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800956 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900957 mMdnsDiscoveryManager.registerListener(
958 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000959 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
960 listener, clientInfo, info.getNetwork());
961 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000962 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700963 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800964 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800965 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
966 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800967 break;
968 }
969
970 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000971 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800972 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +0000973 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
974 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +0800975 } else {
Paul Hu508a0122023-09-11 15:31:33 +0800976 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
977 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800978 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700979 }
980 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800981 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900982 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000983 if (DBG) Log.d(TAG, "Stop service resolution");
984 args = (ListenerArgs) msg.obj;
985 clientInfo = mClients.get(args.connector);
986 // If the binder death notification for a INsdManagerCallback was received
987 // before any calls are received by NsdService, the clientInfo would be
988 // cleared and cause NPE. Add a null check here to prevent this corner case.
989 if (clientInfo == null) {
990 Log.e(TAG, "Unknown connector in stop resolution");
991 break;
992 }
993
Paul Hud44e1b72023-06-16 02:07:42 +0000994 final ClientRequest request =
995 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900996 if (request == null) {
997 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
998 break;
999 }
Paul Hud44e1b72023-06-16 02:07:42 +00001000 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001001 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1002 // point, so this needs to check the type of the original request to
1003 // unregister instead of looking at the flag value.
1004 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001005 stopDiscoveryManagerRequest(
1006 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001007 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001008 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001009 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001010 removeRequestMap(clientRequestId, transactionId, clientInfo);
1011 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001012 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001013 } else {
1014 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001015 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001016 }
1017 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001018 }
Paul Hub58deb72022-12-26 09:24:42 +00001019 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001020 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001021 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001022 if (DBG) Log.d(TAG, "Register a service callback");
1023 args = (ListenerArgs) msg.obj;
1024 clientInfo = mClients.get(args.connector);
1025 // If the binder death notification for a INsdManagerCallback was received
1026 // before any calls are received by NsdService, the clientInfo would be
1027 // cleared and cause NPE. Add a null check here to prevent this corner case.
1028 if (clientInfo == null) {
1029 Log.e(TAG, "Unknown connector in callback registration");
1030 break;
1031 }
1032
Paul Hu30bd70d2023-02-07 13:20:56 +00001033 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001034 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001035 final Pair<String, String> typeAndSubtype =
1036 parseTypeAndSubtype(info.getServiceType());
1037 final String serviceType = typeAndSubtype == null
1038 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001039 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001040 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001041 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001042 break;
1043 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001044 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001045
Paul Hu30bd70d2023-02-07 13:20:56 +00001046 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001047 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1048 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001049 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1050 .setNetwork(info.getNetwork())
1051 .setIsPassiveMode(true)
1052 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001053 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001054 .build();
1055 mMdnsDiscoveryManager.registerListener(
1056 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001057 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1058 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001059 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001060 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001061 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001062 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001063 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001064 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001065 if (DBG) Log.d(TAG, "Unregister a service callback");
1066 args = (ListenerArgs) msg.obj;
1067 clientInfo = mClients.get(args.connector);
1068 // If the binder death notification for a INsdManagerCallback was received
1069 // before any calls are received by NsdService, the clientInfo would be
1070 // cleared and cause NPE. Add a null check here to prevent this corner case.
1071 if (clientInfo == null) {
1072 Log.e(TAG, "Unknown connector in callback unregistration");
1073 break;
1074 }
1075
Paul Hud44e1b72023-06-16 02:07:42 +00001076 final ClientRequest request =
1077 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001078 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001079 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001080 break;
1081 }
Paul Hud44e1b72023-06-16 02:07:42 +00001082 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001083 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001084 stopDiscoveryManagerRequest(
1085 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001086 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001087 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001088 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001089 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001090 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001091 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001092 }
paulhu2b9ed952022-02-10 21:58:32 +08001093 case MDNS_SERVICE_EVENT:
1094 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001095 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001096 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001097 break;
Paul Hu019621e2023-01-13 23:26:49 +08001098 case MDNS_DISCOVERY_MANAGER_EVENT:
1099 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1100 return NOT_HANDLED;
1101 }
1102 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001103 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1104 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1105 // TODO: Limits the number of registrations created by a given class.
1106 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1107 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001108 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001109 break;
1110 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1111 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1112 break;
Paul Hu77c11182023-10-23 16:17:32 +08001113 case NsdManager.REGISTER_CLIENT:
1114 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1115 final INsdManagerCallback cb = arg.callback;
1116 try {
1117 cb.asBinder().linkToDeath(arg.connector, 0);
1118 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1119 final NetworkNsdReportedMetrics metrics =
1120 mDeps.makeNetworkNsdReportedMetrics(
1121 (int) mClock.elapsedRealtime());
1122 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1123 mServiceLogs.forSubComponent(tag), metrics);
1124 mClients.put(arg.connector, clientInfo);
1125 } catch (RemoteException e) {
1126 Log.w(TAG, "Client request id " + clientRequestId
1127 + " has already died");
1128 }
1129 break;
1130 case NsdManager.UNREGISTER_CLIENT:
1131 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1132 clientInfo = mClients.remove(connector);
1133 if (clientInfo != null) {
1134 clientInfo.expungeAllRequests();
1135 if (clientInfo.isPreSClient()) {
1136 mLegacyClientCount -= 1;
1137 }
1138 }
1139 maybeStopMonitoringSocketsIfNoActiveRequest();
1140 maybeScheduleStop();
1141 break;
1142 case NsdManager.DAEMON_CLEANUP:
1143 maybeStopDaemon();
1144 break;
1145 // This event should be only sent by the legacy (target SDK < S) clients.
1146 // Mark the sending client as legacy.
1147 case NsdManager.DAEMON_STARTUP:
1148 clientInfo = getClientInfoForReply(msg);
1149 if (clientInfo != null) {
1150 cancelStop();
1151 clientInfo.setPreSClient();
1152 mLegacyClientCount += 1;
1153 maybeStartDaemon();
1154 }
1155 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001156 default:
Paul Hu77c11182023-10-23 16:17:32 +08001157 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001158 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001159 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001160 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001161 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001162
Paul Hud44e1b72023-06-16 02:07:42 +00001163 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001164 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001165 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001166 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001167 Log.e(TAG, String.format(
1168 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001169 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001170 }
1171
1172 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001173 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1174 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001175 // This can happen because of race conditions. For example,
1176 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1177 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001178 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1179 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001180 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 }
Paul Hu812e9212023-06-20 06:24:53 +00001182 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1183 if (request == null) {
1184 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1185 return false;
1186 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001187 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001188 Log.d(TAG, String.format(
1189 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001190 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001191 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001192 case IMDnsEventListener.SERVICE_FOUND: {
1193 final DiscoveryInfo info = (DiscoveryInfo) obj;
1194 final String name = info.serviceName;
1195 final String type = info.registrationType;
1196 servInfo = new NsdServiceInfo(name, type);
1197 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001198 if (foundNetId == 0L) {
1199 // Ignore services that do not have a Network: they are not usable
1200 // by apps, as they would need privileged permissions to use
1201 // interfaces that do not have an associated Network.
1202 break;
1203 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001204 if (foundNetId == INetd.DUMMY_NET_ID) {
1205 // Ignore services on the dummy0 interface: they are only seen when
1206 // discovering locally advertised services, and are not reachable
1207 // through that interface.
1208 break;
1209 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001210 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001211
1212 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001213 break;
paulhu2b9ed952022-02-10 21:58:32 +08001214 }
1215 case IMDnsEventListener.SERVICE_LOST: {
1216 final DiscoveryInfo info = (DiscoveryInfo) obj;
1217 final String name = info.serviceName;
1218 final String type = info.registrationType;
1219 final int lostNetId = info.netId;
1220 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001221 // The network could be set to null (netId 0) if it was torn down when the
1222 // service is lost
1223 // TODO: avoid returning null in that case, possibly by remembering
1224 // found services on the same interface index and their network at the time
1225 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001226 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001227 break;
paulhu2b9ed952022-02-10 21:58:32 +08001228 }
1229 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001230 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001231 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1232 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001233 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001234 break;
paulhu2b9ed952022-02-10 21:58:32 +08001235 case IMDnsEventListener.SERVICE_REGISTERED: {
1236 final RegistrationInfo info = (RegistrationInfo) obj;
1237 final String name = info.serviceName;
1238 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001239 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001240 break;
paulhu2b9ed952022-02-10 21:58:32 +08001241 }
1242 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001243 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001244 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1245 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001246 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001247 break;
paulhu2b9ed952022-02-10 21:58:32 +08001248 case IMDnsEventListener.SERVICE_RESOLVED: {
1249 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001250 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001251 final String fullName = info.serviceFullName;
1252 while (index < fullName.length() && fullName.charAt(index) != '.') {
1253 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001254 ++index;
1255 }
1256 ++index;
1257 }
paulhu2b9ed952022-02-10 21:58:32 +08001258 if (index >= fullName.length()) {
1259 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001260 break;
1261 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001262
paulhube186602022-04-12 07:18:23 +00001263 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001264 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001265 String type = rest.replace(".local.", "");
1266
Paul Hu30bd70d2023-02-07 13:20:56 +00001267 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001268 serviceInfo.setServiceName(name);
1269 serviceInfo.setServiceType(type);
1270 serviceInfo.setPort(info.port);
1271 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001272 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001273
Paul Hud44e1b72023-06-16 02:07:42 +00001274 stopResolveService(transactionId);
1275 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001276
Paul Hud44e1b72023-06-16 02:07:42 +00001277 final int transactionId2 = getUniqueId();
1278 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1279 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001280 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001281 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001282 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001283 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1284 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001285 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001286 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001287 }
1288 break;
paulhu2b9ed952022-02-10 21:58:32 +08001289 }
1290 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001291 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001292 stopResolveService(transactionId);
1293 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001294 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001295 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1296 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001297 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001298 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001299 break;
paulhu2b9ed952022-02-10 21:58:32 +08001300 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001301 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001302 stopGetAddrInfo(transactionId);
1303 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001304 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001305 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1306 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001307 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001308 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001309 break;
paulhu2b9ed952022-02-10 21:58:32 +08001310 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001311 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001312 final GetAddressInfo info = (GetAddressInfo) obj;
1313 final String address = info.address;
1314 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001315 InetAddress serviceHost = null;
1316 try {
paulhu2b9ed952022-02-10 21:58:32 +08001317 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001318 } catch (UnknownHostException e) {
1319 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1320 }
1321
1322 // If the resolved service is on an interface without a network, consider it
1323 // as a failure: it would not be usable by apps as they would need
1324 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001325 if (netId != NETID_UNSET && serviceHost != null) {
1326 clientInfo.mResolvedService.setHost(serviceHost);
1327 setServiceNetworkForCallback(clientInfo.mResolvedService,
1328 netId, info.interfaceIdx);
1329 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001330 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001331 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001332 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001333 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1334 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001335 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001336 }
Paul Hud44e1b72023-06-16 02:07:42 +00001337 stopGetAddrInfo(transactionId);
1338 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001339 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001340 break;
paulhu2b9ed952022-02-10 21:58:32 +08001341 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001342 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001343 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001344 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001345 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001346 }
Paul Hu019621e2023-01-13 23:26:49 +08001347
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001348 @Nullable
1349 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1350 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001351 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001352 final String[] typeArray = serviceInfo.getServiceType();
1353 final String joinedType;
1354 if (typeArray.length == 0
1355 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1356 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1357 + Arrays.toString(typeArray));
1358 return null;
1359 } else {
1360 joinedType = TextUtils.join(".",
1361 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1362 }
1363 final String serviceType;
1364 switch (code) {
1365 case NsdManager.SERVICE_FOUND:
1366 case NsdManager.SERVICE_LOST:
1367 // For consistency with historical behavior, discovered service types have
1368 // a dot at the end.
1369 serviceType = joinedType + ".";
1370 break;
1371 case RESOLVE_SERVICE_SUCCEEDED:
1372 // For consistency with historical behavior, resolved service types have
1373 // a dot at the beginning.
1374 serviceType = "." + joinedType;
1375 break;
1376 default:
1377 serviceType = joinedType;
1378 break;
1379 }
Paul Hu019621e2023-01-13 23:26:49 +08001380 final String serviceName = serviceInfo.getServiceInstanceName();
1381 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1382 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001383 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1384 // network for Tethering interface. In other words, the network == null means the
1385 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001386 setServiceNetworkForCallback(
1387 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001388 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001389 serviceInfo.getInterfaceIndex());
1390 return servInfo;
1391 }
1392
1393 private boolean handleMdnsDiscoveryManagerEvent(
1394 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001395 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001396 if (clientInfo == null) {
1397 Log.e(TAG, String.format(
1398 "id %d for %d has no client mapping", transactionId, code));
1399 return false;
1400 }
1401
1402 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001403 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001404 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1405 if (request == null) {
1406 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1407 return false;
1408 }
1409
1410 // Deal with the discovery sent callback
1411 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1412 request.onQuerySent();
1413 return true;
1414 }
1415
1416 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001417 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1418 // Errors are already logged if null
1419 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001420 mServiceLogs.log(String.format(
1421 "MdnsDiscoveryManager event code=%s transactionId=%d",
1422 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001423 switch (code) {
1424 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001425 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001426 break;
1427 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001428 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001429 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001430 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1431 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001432 info.setPort(serviceInfo.getPort());
1433
1434 Map<String, String> attrs = serviceInfo.getAttributes();
1435 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1436 final String key = kv.getKey();
1437 try {
1438 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1439 } catch (IllegalArgumentException e) {
1440 Log.e(TAG, "Invalid attribute", e);
1441 }
1442 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001443 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001444 if (addresses.size() != 0) {
1445 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001446 request.setServiceFromCache(event.mIsServiceFromCache);
1447 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001448 } else {
1449 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001450 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001451 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1452 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001453 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001454 }
1455
1456 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001457 if (!(request instanceof DiscoveryManagerRequest)) {
1458 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1459 break;
1460 }
Paul Hud44e1b72023-06-16 02:07:42 +00001461 stopDiscoveryManagerRequest(
1462 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001463 break;
1464 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001465 case NsdManager.SERVICE_UPDATED: {
1466 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1467 info.setPort(serviceInfo.getPort());
1468
1469 Map<String, String> attrs = serviceInfo.getAttributes();
1470 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1471 final String key = kv.getKey();
1472 try {
1473 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1474 } catch (IllegalArgumentException e) {
1475 Log.e(TAG, "Invalid attribute", e);
1476 }
1477 }
1478
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001479 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001480 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001481 clientInfo.onServiceUpdated(clientRequestId, info, request);
1482 // Set the ServiceFromCache flag only if the service is actually being
1483 // retrieved from the cache. This flag should not be overridden by later
1484 // service updates, which may not be cached.
1485 if (event.mIsServiceFromCache) {
1486 request.setServiceFromCache(true);
1487 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001488 break;
1489 }
1490 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001491 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001492 break;
Paul Hu019621e2023-01-13 23:26:49 +08001493 default:
1494 return false;
1495 }
1496 return true;
1497 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001498 }
1499 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001500
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001501 @NonNull
1502 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1503 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1504 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1505 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1506 for (String ipv4Address : v4Addrs) {
1507 try {
1508 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1509 } catch (IllegalArgumentException e) {
1510 Log.wtf(TAG, "Invalid ipv4 address", e);
1511 }
1512 }
1513 for (String ipv6Address : v6Addrs) {
1514 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001515 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1516 ipv6Address);
1517 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1518 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001519 Log.wtf(TAG, "Invalid ipv6 address", e);
1520 }
1521 }
1522 return addresses;
1523 }
1524
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001525 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1526 switch (netId) {
1527 case NETID_UNSET:
1528 info.setNetwork(null);
1529 break;
1530 case INetd.LOCAL_NET_ID:
1531 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1532 // visible / usable for apps, so do not return it. Store the interface
1533 // index instead, so at least if the client tries to resolve the service
1534 // with that NsdServiceInfo, it will be done on the same interface.
1535 // If they recreate the NsdServiceInfo themselves, resolution would be
1536 // done on all interfaces as before T, which should also work.
1537 info.setNetwork(null);
1538 info.setInterfaceIndex(ifaceIdx);
1539 break;
1540 default:
1541 info.setNetwork(new Network(netId));
1542 }
1543 }
1544
paulhube186602022-04-12 07:18:23 +00001545 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1546 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1547 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1548 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1549 private String unescape(String s) {
1550 StringBuilder sb = new StringBuilder(s.length());
1551 for (int i = 0; i < s.length(); ++i) {
1552 char c = s.charAt(i);
1553 if (c == '\\') {
1554 if (++i >= s.length()) {
1555 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1556 break;
1557 }
1558 c = s.charAt(i);
1559 if (c != '.' && c != '\\') {
1560 if (i + 2 >= s.length()) {
1561 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1562 break;
1563 }
1564 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1565 + (s.charAt(i + 2) - '0'));
1566 i += 2;
1567 }
1568 }
1569 sb.append(c);
1570 }
1571 return sb.toString();
1572 }
1573
Paul Hu7445e3d2023-03-03 15:14:00 +08001574 /**
1575 * Check the given service type is valid and construct it to a service type
1576 * which can use for discovery / resolution service.
1577 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001578 * <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 +08001579 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1580 * underscore; they are alphanumerical characters or dashes or underscore, except the
1581 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1582 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001583 * <p>The subtype may also be specified with a comma after the service type, for example
1584 * _type._tcp,_subtype.
1585 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001586 * @param serviceType the request service type for discovery / resolution service
1587 * @return constructed service type or null if the given service type is invalid.
1588 */
1589 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001590 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001591 if (TextUtils.isEmpty(serviceType)) return null;
1592
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001593 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001594 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001595 // Optional leading subtype (_subtype._type._tcp)
1596 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1597 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1598 // Actual type (_type._tcp.local)
1599 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001600 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001601 // e.g. allow "_type._tcp.local."
1602 + "\\.?"
1603 // Optional subtype after comma, for "_type._tcp,_subtype" format
1604 + "(?:,(" + typeOrSubtypePattern + "))?"
1605 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001606 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1607 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001608 // Use the subtype either at the beginning or after the comma
1609 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1610 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001611 }
1612
Hugo Benichi803a2f02017-04-24 11:35:06 +09001613 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001614 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001615 this(ctx, handler, cleanupDelayMs, new Dependencies());
1616 }
1617
1618 @VisibleForTesting
1619 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001620 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001621 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001622 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001623 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001624 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1625 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001626 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001627
Paul Hu14667de2023-04-17 22:42:47 +08001628 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001629 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001630 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001631 // address events are received. When the netlink monitor starts, any IP addresses already
1632 // on the interfaces will not be seen. In practice, the network will not connect at boot
1633 // time As a result, all the netlink message should be observed if the netlink monitor
1634 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001635 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001636
1637 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1638 // startBootstrapServices).
1639 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1640 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1641 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1642 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1643 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1644 mRunningAppActiveImportanceCutoff);
1645
Paul Huf3fe3332023-10-16 17:13:25 +08001646 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1647 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1648 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1649 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1650 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001651 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1652 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001653 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1654 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001655 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001656 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001657 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001658 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001659 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001660 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001661 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1662 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001663 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001664 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001665 }
1666
1667 /**
1668 * Dependencies of NsdService, for injection in tests.
1669 */
1670 @VisibleForTesting
1671 public static class Dependencies {
1672 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001673 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001674 *
1675 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001676 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001677 */
1678 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001679 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001680 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001681 }
1682
1683 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001684 * Check whether the MdnsAdvertiser feature is enabled.
1685 *
1686 * @param context The global context information about an app environment.
1687 * @return true if the MdnsAdvertiser feature is enabled.
1688 */
1689 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001690 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001691 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001692 }
1693
1694 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001695 * Get the type allowlist flag value.
1696 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1697 */
1698 @Nullable
1699 public String getTypeAllowlistFlags() {
1700 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1701 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1702 }
1703
1704 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001705 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001706 */
1707 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001708 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001709 }
1710
1711 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001712 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1713 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001714 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1715 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001716 }
1717
1718 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001719 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1720 */
1721 public boolean isTrunkStableFeatureEnabled(String feature) {
1722 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1723 }
1724
1725 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001726 * @see MdnsDiscoveryManager
1727 */
1728 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001729 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001730 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1731 @NonNull MdnsFeatureFlags featureFlags) {
1732 return new MdnsDiscoveryManager(
1733 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001734 }
1735
1736 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001737 * @see MdnsAdvertiser
1738 */
1739 public MdnsAdvertiser makeMdnsAdvertiser(
1740 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001741 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1742 MdnsFeatureFlags featureFlags) {
1743 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001744 }
1745
1746 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001747 * @see MdnsSocketProvider
1748 */
Paul Hu14667de2023-04-17 22:42:47 +08001749 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001750 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1751 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1752 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1753 }
1754
1755 /**
1756 * @see DeviceConfig#getInt(String, String, int)
1757 */
1758 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1759 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1760 }
1761
1762 /**
1763 * @see Binder#getCallingUid()
1764 */
1765 public int getCallingUid() {
1766 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001767 }
Paul Hu777ed052023-06-19 13:35:15 +00001768
1769 /**
1770 * @see NetworkNsdReportedMetrics
1771 */
Paul Hu508a0122023-09-11 15:31:33 +08001772 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1773 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001774 }
1775
1776 /**
1777 * @see MdnsUtils.Clock
1778 */
1779 public Clock makeClock() {
1780 return new Clock();
1781 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001782 }
1783
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001784 /**
1785 * Return whether a type is allowlisted to use the Java backend.
1786 * @param type The service type
1787 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1788 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1789 */
1790 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1791 @NonNull String flagPrefix) {
1792 if (type == null) return false;
1793 final String typesConfig = mDeps.getTypeAllowlistFlags();
1794 if (TextUtils.isEmpty(typesConfig)) return false;
1795
1796 final String mappingPrefix = type + ":";
1797 String mappedFlag = null;
1798 for (String mapping : TextUtils.split(typesConfig, ",")) {
1799 if (mapping.startsWith(mappingPrefix)) {
1800 mappedFlag = mapping.substring(mappingPrefix.length());
1801 break;
1802 }
1803 }
1804
1805 if (mappedFlag == null) return false;
1806
1807 return mDeps.isFeatureEnabled(mContext,
1808 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1809 }
1810
1811 private boolean useDiscoveryManagerForType(@Nullable String type) {
1812 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1813 }
1814
1815 private boolean useAdvertiserForType(@Nullable String type) {
1816 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1817 }
1818
paulhu1b35e822022-04-08 14:48:41 +08001819 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001820 HandlerThread thread = new HandlerThread(TAG);
1821 thread.start();
1822 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001823 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001824 return service;
1825 }
1826
paulhu2b9ed952022-02-10 21:58:32 +08001827 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1828 private final StateMachine mStateMachine;
1829
1830 MDnsEventCallback(StateMachine sm) {
1831 mStateMachine = sm;
1832 }
1833
1834 @Override
1835 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1836 mStateMachine.sendMessage(
1837 MDNS_SERVICE_EVENT, status.result, status.id, status);
1838 }
1839
1840 @Override
1841 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1842 mStateMachine.sendMessage(
1843 MDNS_SERVICE_EVENT, status.result, status.id, status);
1844 }
1845
1846 @Override
1847 public void onServiceResolutionStatus(final ResolutionInfo status) {
1848 mStateMachine.sendMessage(
1849 MDNS_SERVICE_EVENT, status.result, status.id, status);
1850 }
1851
1852 @Override
1853 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1854 mStateMachine.sendMessage(
1855 MDNS_SERVICE_EVENT, status.result, status.id, status);
1856 }
1857
1858 @Override
1859 public int getInterfaceVersion() throws RemoteException {
1860 return this.VERSION;
1861 }
1862
1863 @Override
1864 public String getInterfaceHash() throws RemoteException {
1865 return this.HASH;
1866 }
1867 }
1868
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001869 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1870 final String targetInterface = offloadEngineInfo.mInterfaceName;
1871 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1872 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1873 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1874 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1875 try {
1876 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1877 } catch (RemoteException e) {
1878 // Can happen in regular cases, do not log a stacktrace
1879 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1880 }
1881 }
1882 }
1883
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001884 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1885 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1886 final int count = mOffloadEngines.beginBroadcast();
1887 try {
1888 for (int i = 0; i < count; i++) {
1889 final OffloadEngineInfo offloadEngineInfo =
1890 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1891 final String interfaceName = offloadEngineInfo.mInterfaceName;
1892 if (!targetInterfaceName.equals(interfaceName)
1893 || ((offloadEngineInfo.mOffloadType
1894 & offloadServiceInfo.getOffloadType()) == 0)) {
1895 continue;
1896 }
1897 try {
1898 if (isRemove) {
1899 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1900 offloadServiceInfo);
1901 } else {
1902 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1903 offloadServiceInfo);
1904 }
1905 } catch (RemoteException e) {
1906 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001907 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001908 }
1909 }
1910 } finally {
1911 mOffloadEngines.finishBroadcast();
1912 }
1913 }
1914
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001915 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001916 // TODO: add a callback to notify when a service is being added on each interface (as soon
1917 // as probing starts), and call mOffloadCallbacks. This callback is for
1918 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1919
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001920 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001921 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1922 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1923 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001924 if (clientInfo == null) return;
1925
Paul Hud44e1b72023-06-16 02:07:42 +00001926 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1927 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001928
1929 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1930 // historical behavior.
1931 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001932 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001933 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001934 }
1935
1936 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001937 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1938 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001939 if (clientInfo == null) return;
1940
Paul Hud44e1b72023-06-16 02:07:42 +00001941 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1942 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001943 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001944 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1945 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001946 }
1947
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001948 @Override
1949 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1950 @NonNull OffloadServiceInfo offloadServiceInfo) {
1951 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1952 }
1953
1954 @Override
1955 public void onOffloadStop(@NonNull String interfaceName,
1956 @NonNull OffloadServiceInfo offloadServiceInfo) {
1957 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1958 }
1959
Paul Hud44e1b72023-06-16 02:07:42 +00001960 private ClientInfo getClientInfoOrLog(int transactionId) {
1961 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001962 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001963 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001964 }
1965 return clientInfo;
1966 }
1967
Paul Hud44e1b72023-06-16 02:07:42 +00001968 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1969 final int clientRequestId = info.getClientRequestId(transactionId);
1970 if (clientRequestId < 0) {
1971 Log.e(TAG, String.format(
1972 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001973 }
Paul Hud44e1b72023-06-16 02:07:42 +00001974 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001975 }
1976 }
1977
Paul Hu2e0a88c2023-03-09 16:05:01 +08001978 private static class ConnectorArgs {
1979 @NonNull public final NsdServiceConnector connector;
1980 @NonNull public final INsdManagerCallback callback;
1981 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001982 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001983
1984 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001985 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001986 this.connector = connector;
1987 this.callback = callback;
1988 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001989 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001990 }
1991 }
1992
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001993 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001994 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001996 final int uid = mDeps.getCallingUid();
1997 if (cb == null) {
1998 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1999 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002000 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002001 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002002 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002003 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002004 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002005 }
2006
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002007 private static class ListenerArgs {
2008 public final NsdServiceConnector connector;
2009 public final NsdServiceInfo serviceInfo;
2010 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2011 this.connector = connector;
2012 this.serviceInfo = serviceInfo;
2013 }
2014 }
2015
2016 private class NsdServiceConnector extends INsdServiceConnector.Stub
2017 implements IBinder.DeathRecipient {
2018 @Override
2019 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2020 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2021 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2022 new ListenerArgs(this, serviceInfo)));
2023 }
2024
2025 @Override
2026 public void unregisterService(int listenerKey) {
2027 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2028 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2029 new ListenerArgs(this, null)));
2030 }
2031
2032 @Override
2033 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2034 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2035 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2036 new ListenerArgs(this, serviceInfo)));
2037 }
2038
2039 @Override
2040 public void stopDiscovery(int listenerKey) {
2041 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2042 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2043 }
2044
2045 @Override
2046 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2047 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2048 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2049 new ListenerArgs(this, serviceInfo)));
2050 }
2051
2052 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002053 public void stopResolution(int listenerKey) {
2054 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2055 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2056 }
2057
2058 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002059 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2060 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2061 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2062 new ListenerArgs(this, serviceInfo)));
2063 }
2064
2065 @Override
2066 public void unregisterServiceInfoCallback(int listenerKey) {
2067 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2068 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2069 new ListenerArgs(this, null)));
2070 }
2071
2072 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002073 public void startDaemon() {
2074 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2075 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2076 }
2077
2078 @Override
2079 public void binderDied() {
2080 mNsdStateMachine.sendMessage(
2081 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002082
2083 }
2084
2085 @Override
2086 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2087 @OffloadEngine.OffloadCapability long offloadCapabilities,
2088 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002089 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002090 Objects.requireNonNull(ifaceName);
2091 Objects.requireNonNull(cb);
2092 mNsdStateMachine.sendMessage(
2093 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2094 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2095 offloadTypes)));
2096 }
2097
2098 @Override
2099 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002100 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002101 Objects.requireNonNull(cb);
2102 mNsdStateMachine.sendMessage(
2103 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002104 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002105
2106 private static void checkOffloadEnginePermission(Context context) {
2107 if (!SdkLevel.isAtLeastT()) {
2108 throw new SecurityException("API is not available in before API level 33");
2109 }
2110 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2111 // be back ported to older builds: accept it as long as it's signature-protected
2112 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2113 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2114 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2115 return;
2116 }
2117 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2118 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2119 return;
2120 }
2121 throw new SecurityException("Requires one of the following permissions: "
2122 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2123 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2124 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002125 }
2126
Hugo Benichi912db992017-04-24 16:41:03 +09002127 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002128 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002129 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002130 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2131 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002132 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002133 }
2134
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002135 private int getUniqueId() {
2136 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2137 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002138 }
2139
Paul Hud44e1b72023-06-16 02:07:42 +00002140 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002141 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002142 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002143 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002144 String name = service.getServiceName();
2145 String type = service.getServiceType();
2146 int port = service.getPort();
2147 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002148 final int registerInterface = getNetworkInterfaceIndex(service);
2149 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002150 Log.e(TAG, "Interface to register service on not found");
2151 return false;
2152 }
Paul Hud44e1b72023-06-16 02:07:42 +00002153 return mMDnsManager.registerService(
2154 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002155 }
2156
Paul Hud44e1b72023-06-16 02:07:42 +00002157 private boolean unregisterService(int transactionId) {
2158 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002159 }
2160
Paul Hud44e1b72023-06-16 02:07:42 +00002161 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002162 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002163 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2164 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002165 Log.e(TAG, "Interface to discover service on not found");
2166 return false;
2167 }
Paul Hud44e1b72023-06-16 02:07:42 +00002168 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002169 }
2170
Paul Hud44e1b72023-06-16 02:07:42 +00002171 private boolean stopServiceDiscovery(int transactionId) {
2172 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002173 }
2174
Paul Hud44e1b72023-06-16 02:07:42 +00002175 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002176 final String name = service.getServiceName();
2177 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002178 final int resolveInterface = getNetworkInterfaceIndex(service);
2179 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002180 Log.e(TAG, "Interface to resolve service on not found");
2181 return false;
2182 }
Paul Hud44e1b72023-06-16 02:07:42 +00002183 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002184 }
2185
2186 /**
2187 * Guess the interface to use to resolve or discover a service on a specific network.
2188 *
2189 * This is an imperfect guess, as for example the network may be gone or not yet fully
2190 * registered. This is fine as failing is correct if the network is gone, and a client
2191 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2192 * this is to support the legacy mdnsresponder implementation, which historically resolved
2193 * services on an unspecified network.
2194 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002195 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2196 final Network network = serviceInfo.getNetwork();
2197 if (network == null) {
2198 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2199 // provided by NsdService from discovery results, and the service was found on an
2200 // interface that has no app-usable Network).
2201 if (serviceInfo.getInterfaceIndex() != 0) {
2202 return serviceInfo.getInterfaceIndex();
2203 }
2204 return IFACE_IDX_ANY;
2205 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002206
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002207 String interfaceName = getNetworkInterfaceName(network);
2208 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002209 return IFACE_IDX_ANY;
2210 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002211 return getNetworkInterfaceIndexByName(interfaceName);
2212 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002213
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002214 private String getNetworkInterfaceName(@Nullable Network network) {
2215 if (network == null) {
2216 return null;
2217 }
2218 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2219 if (cm == null) {
2220 Log.wtf(TAG, "No ConnectivityManager");
2221 return null;
2222 }
2223 final LinkProperties lp = cm.getLinkProperties(network);
2224 if (lp == null) {
2225 return null;
2226 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002227 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002228 return lp.getInterfaceName();
2229 }
2230
2231 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002232 final NetworkInterface iface;
2233 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002234 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002235 } catch (SocketException e) {
2236 Log.e(TAG, "Error querying interface", e);
2237 return IFACE_IDX_ANY;
2238 }
2239
2240 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002241 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002242 return IFACE_IDX_ANY;
2243 }
2244
2245 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002246 }
2247
Paul Hud44e1b72023-06-16 02:07:42 +00002248 private boolean stopResolveService(int transactionId) {
2249 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002250 }
2251
Paul Hud44e1b72023-06-16 02:07:42 +00002252 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2253 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002254 }
2255
Paul Hud44e1b72023-06-16 02:07:42 +00002256 private boolean stopGetAddrInfo(int transactionId) {
2257 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002258 }
2259
2260 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002261 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2262 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002263
Paul Hub2e67d32023-04-18 05:50:14 +00002264 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2265 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002266 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002267
2268 // Dump service and clients logs
2269 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002270 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002271 pw.increaseIndent();
2272 mServiceLogs.reverseDump(pw);
2273 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002274 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002275
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002276 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002277 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002278 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002279 private int mFoundServiceCount = 0;
2280 private int mLostServiceCount = 0;
2281 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002282 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002283 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002284
Paul Hu812e9212023-06-20 06:24:53 +00002285 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002286 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002287 mStartTimeMs = startTimeMs;
2288 }
2289
Paul Hu812e9212023-06-20 06:24:53 +00002290 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002291 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002292 }
Paul Hu812e9212023-06-20 06:24:53 +00002293
2294 public void onServiceFound(String serviceName) {
2295 mFoundServiceCount++;
2296 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2297 mServices.add(serviceName);
2298 }
2299 }
2300
2301 public void onServiceLost() {
2302 mLostServiceCount++;
2303 }
2304
2305 public int getFoundServiceCount() {
2306 return mFoundServiceCount;
2307 }
2308
2309 public int getLostServiceCount() {
2310 return mLostServiceCount;
2311 }
2312
2313 public int getServicesCount() {
2314 return mServices.size();
2315 }
Paul Hua6bc4632023-06-26 01:18:29 +00002316
2317 public void setServiceFromCache(boolean isServiceFromCache) {
2318 mIsServiceFromCache = isServiceFromCache;
2319 }
2320
2321 public boolean isServiceFromCache() {
2322 return mIsServiceFromCache;
2323 }
Paul Hubad6fe92023-07-24 21:25:22 +08002324
2325 public void onQuerySent() {
2326 mSentQueryCount++;
2327 }
2328
2329 public int getSentQueryCount() {
2330 return mSentQueryCount;
2331 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002332 }
2333
2334 private static class LegacyClientRequest extends ClientRequest {
2335 private final int mRequestCode;
2336
Paul Hu812e9212023-06-20 06:24:53 +00002337 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2338 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002339 mRequestCode = requestCode;
2340 }
2341 }
2342
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002343 private abstract static class JavaBackendClientRequest extends ClientRequest {
2344 @Nullable
2345 private final Network mRequestedNetwork;
2346
Paul Hu777ed052023-06-19 13:35:15 +00002347 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002348 long startTimeMs) {
2349 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002350 mRequestedNetwork = requestedNetwork;
2351 }
2352
2353 @Nullable
2354 public Network getRequestedNetwork() {
2355 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002356 }
2357 }
2358
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002359 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002360 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002361 long startTimeMs) {
2362 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002363 }
2364 }
2365
2366 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002367 @NonNull
2368 private final MdnsListener mListener;
2369
Paul Hud44e1b72023-06-16 02:07:42 +00002370 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002371 @Nullable Network requestedNetwork, long startTimeMs) {
2372 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002373 mListener = listener;
2374 }
2375 }
2376
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002377 /* Information tracked per client */
2378 private class ClientInfo {
2379
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002380 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002381 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002382 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002383 private NsdServiceInfo mResolvedService;
2384
Paul Hud44e1b72023-06-16 02:07:42 +00002385 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002386 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002387
Luke Huangf7277ed2021-07-12 21:15:10 +08002388 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002389 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002390 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002391 // The flag of using java backend if the client's target SDK >= U
2392 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002393 // Store client logs
2394 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002395 // Report the nsd metrics data
2396 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002397
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002398 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002399 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002400 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002401 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002402 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002403 mClientLogs = sharedLog;
2404 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002405 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002406 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002407
2408 @Override
2409 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002410 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002411 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002412 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002413 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2414 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002415 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002416 int clientRequestId = mClientRequests.keyAt(i);
2417 sb.append("clientRequestId ")
2418 .append(clientRequestId)
2419 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002420 .append(" type ").append(
2421 mClientRequests.valueAt(i).getClass().getSimpleName())
2422 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002423 }
2424 return sb.toString();
2425 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002426
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002427 private boolean isPreSClient() {
2428 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002429 }
2430
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002431 private void setPreSClient() {
2432 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002433 }
2434
Paul Hu812e9212023-06-20 06:24:53 +00002435 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002436 final MdnsListener listener =
2437 ((DiscoveryManagerRequest) request).mListener;
2438 mMdnsDiscoveryManager.unregisterListener(
2439 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002440 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002441 }
2442
Dave Plattfeff2af2014-03-07 14:48:22 -08002443 // Remove any pending requests from the global map when we get rid of a client,
2444 // and send cancellations to the daemon.
2445 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002446 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002447 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002448 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002449 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002450 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002451 final int transactionId = request.mTransactionId;
2452 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002453 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002454 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2455 + " transactionId " + transactionId
2456 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002457 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002458
2459 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002460 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2461 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002462 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002463 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2464 request.getFoundServiceCount(),
2465 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002466 request.getServicesCount(),
2467 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002468 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002469 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002470 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002471 } else if (listener instanceof ServiceInfoListener) {
2472 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2473 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2474 request.getFoundServiceCount(),
2475 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002476 request.isServiceFromCache(),
2477 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002478 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002479 continue;
2480 }
2481
2482 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002483 final AdvertiserMetrics metrics =
2484 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002485 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002486 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002487 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2488 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2489 metrics.mConflictDuringProbingCount,
2490 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002491 continue;
2492 }
2493
2494 if (!(request instanceof LegacyClientRequest)) {
2495 throw new IllegalStateException("Unknown request type: " + request.getClass());
2496 }
2497
2498 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002499 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002500 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002501 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002502 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2503 request.getFoundServiceCount(),
2504 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002505 request.getServicesCount(),
2506 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002507 break;
2508 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002509 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002510 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002511 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002512 break;
2513 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002514 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002515 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002516 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2517 NO_PACKET /* repliedRequestsCount */,
2518 NO_PACKET /* sentPacketCount */,
2519 0 /* conflictDuringProbingCount */,
2520 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002521 break;
2522 default:
2523 break;
2524 }
2525 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002526 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002527 updateMulticastLock();
2528 }
2529
2530 /**
2531 * Returns true if this client has any Java backend request that requests one of the given
2532 * networks.
2533 */
2534 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2535 for (int i = 0; i < mClientRequests.size(); i++) {
2536 final ClientRequest req = mClientRequests.valueAt(i);
2537 if (!(req instanceof JavaBackendClientRequest)) {
2538 continue;
2539 }
2540 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2541 .getRequestedNetwork();
2542 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2543 return true;
2544 }
2545 }
2546 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002547 }
2548
Paul Hud44e1b72023-06-16 02:07:42 +00002549 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2550 // transaction id, return the corresponding client request id.
2551 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002552 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002553 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002554 return mClientRequests.keyAt(i);
2555 }
Christopher Lane74411222014-04-25 18:39:07 -07002556 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002557 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002558 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002559
Paul Hub2e67d32023-04-18 05:50:14 +00002560 private void log(String message) {
2561 mClientLogs.log(message);
2562 }
2563
Paul Hu508a0122023-09-11 15:31:33 +08002564 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2565 return !(request instanceof DiscoveryManagerRequest)
2566 && !(request instanceof AdvertiserClientRequest);
2567 }
2568
2569 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2570 ClientRequest request) {
2571 mMetrics.reportServiceDiscoveryStarted(
2572 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002573 try {
2574 mCb.onDiscoverServicesStarted(listenerKey, info);
2575 } catch (RemoteException e) {
2576 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2577 }
2578 }
Paul Hu508a0122023-09-11 15:31:33 +08002579 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2580 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2581 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002582 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002583
Paul Hu508a0122023-09-11 15:31:33 +08002584 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2585 int transactionId, long durationMs) {
2586 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002587 try {
2588 mCb.onDiscoverServicesFailed(listenerKey, error);
2589 } catch (RemoteException e) {
2590 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2591 }
2592 }
2593
Paul Hu812e9212023-06-20 06:24:53 +00002594 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2595 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002596 try {
2597 mCb.onServiceFound(listenerKey, info);
2598 } catch (RemoteException e) {
2599 Log.e(TAG, "Error calling onServiceFound(", e);
2600 }
2601 }
2602
Paul Hu812e9212023-06-20 06:24:53 +00002603 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2604 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002605 try {
2606 mCb.onServiceLost(listenerKey, info);
2607 } catch (RemoteException e) {
2608 Log.e(TAG, "Error calling onServiceLost(", e);
2609 }
2610 }
2611
2612 void onStopDiscoveryFailed(int listenerKey, int error) {
2613 try {
2614 mCb.onStopDiscoveryFailed(listenerKey, error);
2615 } catch (RemoteException e) {
2616 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2617 }
2618 }
2619
Paul Hu812e9212023-06-20 06:24:53 +00002620 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2621 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002622 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002623 request.mTransactionId,
2624 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2625 request.getFoundServiceCount(),
2626 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002627 request.getServicesCount(),
2628 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002629 try {
2630 mCb.onStopDiscoverySucceeded(listenerKey);
2631 } catch (RemoteException e) {
2632 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2633 }
2634 }
2635
Paul Hu508a0122023-09-11 15:31:33 +08002636 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2637 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2638 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002639 }
2640
Paul Hu508a0122023-09-11 15:31:33 +08002641 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2642 int transactionId, long durationMs) {
2643 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002644 try {
2645 mCb.onRegisterServiceFailed(listenerKey, error);
2646 } catch (RemoteException e) {
2647 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2648 }
2649 }
2650
Paul Hu508a0122023-09-11 15:31:33 +08002651 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2652 ClientRequest request) {
2653 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2654 request.mTransactionId,
2655 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002656 try {
2657 mCb.onRegisterServiceSucceeded(listenerKey, info);
2658 } catch (RemoteException e) {
2659 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2660 }
2661 }
2662
2663 void onUnregisterServiceFailed(int listenerKey, int error) {
2664 try {
2665 mCb.onUnregisterServiceFailed(listenerKey, error);
2666 } catch (RemoteException e) {
2667 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2668 }
2669 }
2670
Paul Hu508a0122023-09-11 15:31:33 +08002671 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002672 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002673 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2674 request.mTransactionId,
2675 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002676 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2677 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002678 try {
2679 mCb.onUnregisterServiceSucceeded(listenerKey);
2680 } catch (RemoteException e) {
2681 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2682 }
2683 }
2684
Paul Hu508a0122023-09-11 15:31:33 +08002685 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2686 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2687 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002688 }
2689
Paul Hu508a0122023-09-11 15:31:33 +08002690 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2691 int transactionId, long durationMs) {
2692 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002693 try {
2694 mCb.onResolveServiceFailed(listenerKey, error);
2695 } catch (RemoteException e) {
2696 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2697 }
2698 }
2699
Paul Hua6bc4632023-06-26 01:18:29 +00002700 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2701 ClientRequest request) {
2702 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002703 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002704 request.mTransactionId,
2705 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002706 request.isServiceFromCache(),
2707 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002708 try {
2709 mCb.onResolveServiceSucceeded(listenerKey, info);
2710 } catch (RemoteException e) {
2711 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2712 }
2713 }
Paul Hub58deb72022-12-26 09:24:42 +00002714
2715 void onStopResolutionFailed(int listenerKey, int error) {
2716 try {
2717 mCb.onStopResolutionFailed(listenerKey, error);
2718 } catch (RemoteException e) {
2719 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2720 }
2721 }
2722
Paul Hu60149052023-07-31 14:26:08 +08002723 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2724 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002725 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002726 request.mTransactionId,
2727 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002728 try {
2729 mCb.onStopResolutionSucceeded(listenerKey);
2730 } catch (RemoteException e) {
2731 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2732 }
2733 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002734
2735 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002736 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002737 try {
2738 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2739 } catch (RemoteException e) {
2740 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2741 }
2742 }
2743
Paul Huddce5912023-08-01 10:26:49 +08002744 void onServiceInfoCallbackRegistered(int transactionId) {
2745 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2746 }
2747
2748 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2749 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002750 try {
2751 mCb.onServiceUpdated(listenerKey, info);
2752 } catch (RemoteException e) {
2753 Log.e(TAG, "Error calling onServiceUpdated", e);
2754 }
2755 }
2756
Paul Huddce5912023-08-01 10:26:49 +08002757 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2758 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002759 try {
2760 mCb.onServiceUpdatedLost(listenerKey);
2761 } catch (RemoteException e) {
2762 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2763 }
2764 }
2765
Paul Huddce5912023-08-01 10:26:49 +08002766 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2767 mMetrics.reportServiceInfoCallbackUnregistered(
2768 request.mTransactionId,
2769 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2770 request.getFoundServiceCount(),
2771 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002772 request.isServiceFromCache(),
2773 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002774 try {
2775 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2776 } catch (RemoteException e) {
2777 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2778 }
2779 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002780 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002781}