blob: 2640332b33bddcea9d9efba3e4b2949e87209dfa [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yuyang Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090029import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090030
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090032import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080033import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
34import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090035import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000036import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090037
Paul Hu23fa2022023-01-13 22:57:24 +080038import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080039import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090040import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090041import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080042import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070043import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090045import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080046import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090047import android.net.LinkProperties;
48import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080049import android.net.mdns.aidl.DiscoveryInfo;
50import android.net.mdns.aidl.GetAddressInfo;
51import android.net.mdns.aidl.IMDnsEventListener;
52import android.net.mdns.aidl.RegistrationInfo;
53import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.net.nsd.INsdManagerCallback;
56import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090057import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080058import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080060import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090061import android.net.nsd.OffloadEngine;
62import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090063import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000064import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090065import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090066import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080067import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070070import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090071import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070073import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080075import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090076import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090077import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090078import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070079import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080083import com.android.internal.util.State;
84import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000085import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090086import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090087import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090089import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080090import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000091import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090093import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090094import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090096import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090097import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080098import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080099import com.android.server.connectivity.mdns.MdnsSearchOptions;
100import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
101import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900103import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800104
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700105import java.io.FileDescriptor;
106import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900107import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700108import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900109import java.net.NetworkInterface;
110import java.net.SocketException;
111import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800112import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900113import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700114import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800115import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800116import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900117import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000118import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800119import java.util.regex.Matcher;
120import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700121
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700122/**
123 * Network Service Discovery Service handles remote service discovery operation requests by
124 * implementing the INsdManager interface.
125 *
126 * @hide
127 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900128@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700129public class NsdService extends INsdManager.Stub {
130 private static final String TAG = "NsdService";
131 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900132 /**
133 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
134 * implementation.
135 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800136 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800137 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700138
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900139 /**
140 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
141 * implementation.
142 */
143 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
144
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900145 /**
146 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
147 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
148 *
149 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
150 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
151 *
152 * In which case the flags:
153 * "mdns_discovery_manager_allowlist_mytype_version",
154 * "mdns_advertiser_allowlist_mytype_version",
155 * "mdns_discovery_manager_allowlist_othertype_version",
156 * "mdns_advertiser_allowlist_othertype_version"
157 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
158 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900159 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900160 *
161 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
162 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
163 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
164 */
165 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
166
167 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
168 "mdns_discovery_manager_allowlist_";
169 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
170 "mdns_advertiser_allowlist_";
171 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
172
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900173 @VisibleForTesting
174 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
175 "mdns_config_running_app_active_importance_cutoff";
176 @VisibleForTesting
177 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
178 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
179 private final int mRunningAppActiveImportanceCutoff;
180
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900181 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000182 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900183 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000184 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
185 @VisibleForTesting
186 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800187 private static final int NO_SENT_QUERY_COUNT = 0;
188 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800189 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700190
Hugo Benichi32be63d2017-04-05 14:06:11 +0900191 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900192 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800193 private final MDnsManager mMDnsManager;
194 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900195 @NonNull
196 private final Dependencies mDeps;
197 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800198 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900199 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800200 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900201 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800202 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900203 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900204 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000205 @NonNull
206 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800207 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800208 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800209 // state machine thread. If change this outside state machine, it will need to introduce
210 // synchronization.
211 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800212 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700213
214 /**
215 * Clients receiving asynchronous messages
216 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900217 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700218
Paul Hud44e1b72023-06-16 02:07:42 +0000219 /* A map from transaction(unique) id to client info */
220 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700221
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900222 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
223 @Nullable
224 private WifiManager.MulticastLock mHeldMulticastLock;
225 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
226 // (non-null), value is the requested Network (nullable)
227 @NonNull
228 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
229 @NonNull
230 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
231
Luke Huang05298582021-06-13 16:52:05 +0000232 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700233
Hugo Benichi32be63d2017-04-05 14:06:11 +0900234 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700235 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800236 // The count of the connected legacy clients.
237 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000238 // The number of client that ever connected.
239 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700240
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900241 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
242 new RemoteCallbackList<>();
243
244 private static class OffloadEngineInfo {
245 @NonNull final String mInterfaceName;
246 final long mOffloadCapabilities;
247 final long mOffloadType;
248 @NonNull final IOffloadEngine mOffloadEngine;
249
250 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
251 @NonNull String interfaceName, long capabilities, long offloadType) {
252 this.mOffloadEngine = offloadEngine;
253 this.mInterfaceName = interfaceName;
254 this.mOffloadCapabilities = capabilities;
255 this.mOffloadType = offloadType;
256 }
257 }
258
Paul Hu812e9212023-06-20 06:24:53 +0000259 @VisibleForTesting
260 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000261 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800262 protected final int mTransactionId;
263 @NonNull
264 protected final NsdServiceInfo mReqServiceInfo;
265 @NonNull
266 protected final String mListenedServiceType;
267
Paul Hud44e1b72023-06-16 02:07:42 +0000268 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800269 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000270 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800271 mTransactionId = transactionId;
272 mReqServiceInfo = reqServiceInfo;
273 mListenedServiceType = listenedServiceType;
274 }
275
276 @NonNull
277 public String getListenedServiceType() {
278 return mListenedServiceType;
279 }
280
281 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000282 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
283 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800284
285 @Override
286 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
287
288 @Override
289 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
290
291 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000292 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
293 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800294
295 @Override
296 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
297
298 @Override
299 public void onSearchStoppedWithError(int error) { }
300
301 @Override
302 public void onSearchFailedToStart() { }
303
304 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800305 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
306 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800307
308 @Override
309 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
310 }
311
312 private class DiscoveryListener extends MdnsListener {
313
Paul Hud44e1b72023-06-16 02:07:42 +0000314 DiscoveryListener(int clientRequestId, int transactionId,
315 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
316 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800317 }
318
319 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000320 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
321 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800322 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
323 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000324 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800325 }
326
327 @Override
328 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800329 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
330 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000331 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800332 }
Paul Hubad6fe92023-07-24 21:25:22 +0800333
334 @Override
335 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
336 int sentQueryTransactionId) {
337 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
338 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
339 }
Paul Hu23fa2022023-01-13 22:57:24 +0800340 }
341
Paul Hu75069ed2023-01-14 00:31:09 +0800342 private class ResolutionListener extends MdnsListener {
343
Paul Hud44e1b72023-06-16 02:07:42 +0000344 ResolutionListener(int clientRequestId, int transactionId,
345 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
346 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800347 }
348
349 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000350 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800351 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
352 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000353 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800354 }
Paul Hubad6fe92023-07-24 21:25:22 +0800355
356 @Override
357 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
358 int sentQueryTransactionId) {
359 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
360 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
361 }
Paul Hu75069ed2023-01-14 00:31:09 +0800362 }
363
Paul Hu30bd70d2023-02-07 13:20:56 +0000364 private class ServiceInfoListener extends MdnsListener {
365
Paul Hud44e1b72023-06-16 02:07:42 +0000366 ServiceInfoListener(int clientRequestId, int transactionId,
367 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
368 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000369 }
370
371 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000372 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
373 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000374 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
375 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000376 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000377 }
378
379 @Override
380 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
381 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
382 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000383 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000384 }
385
386 @Override
387 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
388 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
389 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000390 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000391 }
Paul Hubad6fe92023-07-24 21:25:22 +0800392
393 @Override
394 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
395 int sentQueryTransactionId) {
396 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
397 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
398 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000399 }
400
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900401 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
402 @Override
403 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
404 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
405 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
406 // filtering on such interfaces, so taking the multicast lock is not necessary to
407 // disable APF filtering of multicast.
408 if (socketNetwork == null
409 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
410 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
411 return;
412 }
413
414 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
415 updateMulticastLock();
416 }
417 }
418
419 @Override
420 public void onSocketDestroyed(@Nullable Network socketNetwork,
421 @NonNull MdnsInterfaceSocket socket) {
422 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
423 updateMulticastLock();
424 }
425 }
426 }
427
428 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
429 private final Handler mHandler;
430
431 private UidImportanceListener(Handler handler) {
432 mHandler = handler;
433 }
434
435 @Override
436 public void onUidImportance(int uid, int importance) {
437 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
438 }
439 }
440
441 private void handleUidImportanceChanged(int uid, int importance) {
442 // Lower importance values are more "important"
443 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
444 ? mRunningAppActiveUids.add(uid)
445 : mRunningAppActiveUids.remove(uid);
446 if (modified) {
447 updateMulticastLock();
448 }
449 }
450
451 /**
452 * Take or release the lock based on updated internal state.
453 *
454 * This determines whether the lock needs to be held based on
455 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
456 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
457 * updated.
458 */
459 private void updateMulticastLock() {
460 final int needsLockUid = getMulticastLockNeededUid();
461 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
462 final WifiManager wm = mContext.getSystemService(WifiManager.class);
463 if (wm == null) {
464 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
465 return;
466 }
467 mHeldMulticastLock = wm.createMulticastLock(TAG);
468 mHeldMulticastLock.acquire();
469 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
470 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
471 mHeldMulticastLock.release();
472 mHeldMulticastLock = null;
473 mServiceLogs.log("Released multicast lock");
474 }
475 }
476
477 /**
478 * @return The UID of an app requiring the multicast lock, or -1 if none.
479 */
480 private int getMulticastLockNeededUid() {
481 if (mWifiLockRequiredNetworks.size() == 0) {
482 // Return early if NSD is not active, or not on any relevant network
483 return -1;
484 }
Paul Hud44e1b72023-06-16 02:07:42 +0000485 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
486 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900487 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
488 // Ignore non-active UIDs
489 continue;
490 }
491
492 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
493 return clientInfo.mUid;
494 }
495 }
496 return -1;
497 }
498
Paul Hu019621e2023-01-13 23:26:49 +0800499 /**
500 * Data class of mdns service callback information.
501 */
502 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000503 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800504 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800505 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000506 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800507
Paul Hubad6fe92023-07-24 21:25:22 +0800508 MdnsEvent(int clientRequestId) {
509 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
510 }
511
512 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000513 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
514 }
515
Paul Hubad6fe92023-07-24 21:25:22 +0800516 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000517 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000518 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800519 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000520 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800521 }
522 }
523
Paul Hu77c11182023-10-23 16:17:32 +0800524 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700525 private class NsdStateMachine extends StateMachine {
526
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700527 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700528
529 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700530 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900531 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700532 }
533
Luke Huang92860f92021-06-23 06:29:30 +0000534 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800535 if (mIsDaemonStarted) {
536 if (DBG) Log.d(TAG, "Daemon is already started.");
537 return;
538 }
539 mMDnsManager.registerEventListener(mMDnsEventCallback);
540 mMDnsManager.startDaemon();
541 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000542 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000543 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000544 }
545
paulhu2b9ed952022-02-10 21:58:32 +0800546 private void maybeStopDaemon() {
547 if (!mIsDaemonStarted) {
548 if (DBG) Log.d(TAG, "Daemon has not been started.");
549 return;
550 }
551 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
552 mMDnsManager.stopDaemon();
553 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000554 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800555 }
556
Luke Huang92860f92021-06-23 06:29:30 +0000557 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000558 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000559 }
560
561 private void scheduleStop() {
562 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
563 }
564 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800565 // The native daemon should stay alive and can't be cleanup
566 // if any legacy client connected.
567 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000568 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000569 }
570 }
571
Luke Huang92860f92021-06-23 06:29:30 +0000572 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000573 this.removeMessages(NsdManager.DAEMON_CLEANUP);
574 }
575
Paul Hu23fa2022023-01-13 22:57:24 +0800576 private void maybeStartMonitoringSockets() {
577 if (mIsMonitoringSocketsStarted) {
578 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
579 return;
580 }
581
582 mMdnsSocketProvider.startMonitoringSockets();
583 mIsMonitoringSocketsStarted = true;
584 }
585
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900586 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
587 if (!mIsMonitoringSocketsStarted) return;
588 if (isAnyRequestActive()) return;
589
Paul Hu58f20602023-02-18 11:41:07 +0800590 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800591 mIsMonitoringSocketsStarted = false;
592 }
593
Hugo Benichi803a2f02017-04-24 11:35:06 +0900594 NsdStateMachine(String name, Handler handler) {
595 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800596 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800597 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900598 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700599 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700600 }
601
Irfan Sheriff75006652012-04-17 23:15:29 -0700602 class EnabledState extends State {
603 @Override
604 public void enter() {
605 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700606 }
607
608 @Override
609 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000610 // TODO: it is incorrect to stop the daemon without expunging all requests
611 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000612 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700613 }
614
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700615 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900616 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800617 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700618 return true;
619 }
620 return false;
621 }
622
Paul Hu508a0122023-09-11 15:31:33 +0800623 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000624 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800625 final LegacyClientRequest request =
626 new LegacyClientRequest(transactionId, what, startTimeMs);
627 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000628 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000629 // Remove the cleanup event because here comes a new request.
630 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800631 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700632 }
633
Paul Hud44e1b72023-06-16 02:07:42 +0000634 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900635 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000636 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000637 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000638 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900639 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800640 }
641
Paul Hud44e1b72023-06-16 02:07:42 +0000642 private void removeRequestMap(
643 int clientRequestId, int transactionId, ClientInfo clientInfo) {
644 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900645 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000646 clientInfo.mClientRequests.remove(clientRequestId);
647 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900648
649 if (existing instanceof LegacyClientRequest) {
650 maybeScheduleStop();
651 } else {
652 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900653 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900654 }
655 }
656
Paul Hu508a0122023-09-11 15:31:33 +0800657 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
658 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900659 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800660 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
661 listener, requestedNetwork, mClock.elapsedRealtime());
662 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000663 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900664 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800665 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800666 }
667
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900668 /**
669 * Truncate a service name to up to 63 UTF-8 bytes.
670 *
671 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
672 * names used in registerService follows historical behavior (see mdnsresponder
673 * handle_regservice_request).
674 */
675 @NonNull
676 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900677 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800678 }
679
Paul Hud44e1b72023-06-16 02:07:42 +0000680 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
681 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800682 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000683 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800684 }
685
Paul Hu77c11182023-10-23 16:17:32 +0800686 private ClientInfo getClientInfoForReply(Message msg) {
687 final ListenerArgs args = (ListenerArgs) msg.obj;
688 return mClients.get(args.connector);
689 }
690
Irfan Sheriff75006652012-04-17 23:15:29 -0700691 @Override
692 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900693 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000694 final int transactionId;
695 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900696 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900697 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700698 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800699 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800700 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900701 args = (ListenerArgs) msg.obj;
702 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000703 // If the binder death notification for a INsdManagerCallback was received
704 // before any calls are received by NsdService, the clientInfo would be
705 // cleared and cause NPE. Add a null check here to prevent this corner case.
706 if (clientInfo == null) {
707 Log.e(TAG, "Unknown connector in discovery");
708 break;
709 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700710
711 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800712 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
713 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700714 break;
715 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700716
Paul Hu23fa2022023-01-13 22:57:24 +0800717 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000718 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900719 final Pair<String, String> typeAndSubtype =
720 parseTypeAndSubtype(info.getServiceType());
721 final String serviceType = typeAndSubtype == null
722 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800723 if (clientInfo.mUseJavaBackend
724 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900725 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800726 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800727 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
728 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800729 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700730 }
Paul Hu23fa2022023-01-13 22:57:24 +0800731
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900732 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800733 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000734 final MdnsListener listener = new DiscoveryListener(clientRequestId,
735 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900736 final MdnsSearchOptions.Builder optionsBuilder =
737 MdnsSearchOptions.newBuilder()
738 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900739 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900740 .setIsPassiveMode(true);
741 if (typeAndSubtype.second != null) {
742 // The parsing ensures subtype starts with an underscore.
743 // MdnsSearchOptions expects the underscore to not be present.
744 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
745 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900746 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900747 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800748 final ClientRequest request = storeDiscoveryManagerRequestMap(
749 clientRequestId, transactionId, listener, clientInfo,
750 info.getNetwork());
751 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000752 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000753 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700754 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800755 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000756 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800757 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000758 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800759 + info.getServiceType());
760 }
Paul Hu508a0122023-09-11 15:31:33 +0800761 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
762 transactionId, clientInfo, msg.what,
763 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000764 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800765 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800766 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000767 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800768 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
769 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800770 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700771 }
772 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800773 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900774 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800775 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900776 args = (ListenerArgs) msg.obj;
777 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000778 // If the binder death notification for a INsdManagerCallback was received
779 // before any calls are received by NsdService, the clientInfo would be
780 // cleared and cause NPE. Add a null check here to prevent this corner case.
781 if (clientInfo == null) {
782 Log.e(TAG, "Unknown connector in stop discovery");
783 break;
784 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700785
Paul Hud44e1b72023-06-16 02:07:42 +0000786 final ClientRequest request =
787 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900788 if (request == null) {
789 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700790 break;
791 }
Paul Hud44e1b72023-06-16 02:07:42 +0000792 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900793 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
794 // point, so this needs to check the type of the original request to
795 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900796 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000797 stopDiscoveryManagerRequest(
798 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000799 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000800 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700801 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000802 removeRequestMap(clientRequestId, transactionId, clientInfo);
803 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000804 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800805 } else {
806 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000807 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800808 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700809 }
810 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900811 }
812 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800813 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900814 args = (ListenerArgs) msg.obj;
815 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000816 // If the binder death notification for a INsdManagerCallback was received
817 // before any calls are received by NsdService, the clientInfo would be
818 // cleared and cause NPE. Add a null check here to prevent this corner case.
819 if (clientInfo == null) {
820 Log.e(TAG, "Unknown connector in registration");
821 break;
822 }
823
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700824 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800825 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
826 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700827 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700828 }
829
Paul Hud44e1b72023-06-16 02:07:42 +0000830 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900831 final NsdServiceInfo serviceInfo = args.serviceInfo;
832 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900833 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
834 final String registerServiceType = typeSubtype == null
835 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800836 if (clientInfo.mUseJavaBackend
837 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900838 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900839 if (registerServiceType == null) {
840 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800841 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
842 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900843 break;
844 }
845 serviceInfo.setServiceType(registerServiceType);
846 serviceInfo.setServiceName(truncateServiceName(
847 serviceInfo.getServiceName()));
848
849 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900850 // TODO: pass in the subtype as well. Including the subtype in the
851 // service type would generate service instance names like
852 // Name._subtype._sub._type._tcp, which is incorrect
853 // (it should be Name._type._tcp).
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900854 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
855 typeSubtype.second,
856 MdnsAdvertisingOptions.newBuilder().build());
Paul Hud44e1b72023-06-16 02:07:42 +0000857 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900858 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700859 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900860 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000861 if (registerService(transactionId, serviceInfo)) {
862 if (DBG) {
863 Log.d(TAG, "Register " + clientRequestId
864 + " " + transactionId);
865 }
Paul Hua6bc4632023-06-26 01:18:29 +0000866 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
867 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900868 // Return success after mDns reports success
869 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000870 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800871 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
872 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900873 }
874
Irfan Sheriff75006652012-04-17 23:15:29 -0700875 }
876 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900877 }
878 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800879 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900880 args = (ListenerArgs) msg.obj;
881 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000882 // If the binder death notification for a INsdManagerCallback was received
883 // before any calls are received by NsdService, the clientInfo would be
884 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900885 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800886 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700887 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700888 }
Paul Hud44e1b72023-06-16 02:07:42 +0000889 final ClientRequest request =
890 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900891 if (request == null) {
892 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
893 break;
894 }
Paul Hud44e1b72023-06-16 02:07:42 +0000895 transactionId = request.mTransactionId;
896 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900897
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900898 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
899 // so this needs to check the type of the original request to unregister
900 // instead of looking at the flag value.
901 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800902 final AdvertiserMetrics metrics =
903 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000904 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800905 clientInfo.onUnregisterServiceSucceeded(
906 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700907 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000908 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800909 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800910 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
911 NO_PACKET /* sentPacketCount */,
912 0 /* conflictDuringProbingCount */,
913 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900914 } else {
915 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000916 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900917 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700918 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700919 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900920 }
Paul Hu75069ed2023-01-14 00:31:09 +0800921 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800922 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900923 args = (ListenerArgs) msg.obj;
924 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000925 // If the binder death notification for a INsdManagerCallback was received
926 // before any calls are received by NsdService, the clientInfo would be
927 // cleared and cause NPE. Add a null check here to prevent this corner case.
928 if (clientInfo == null) {
929 Log.e(TAG, "Unknown connector in resolution");
930 break;
931 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700932
Paul Hu75069ed2023-01-14 00:31:09 +0800933 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000934 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900935 final Pair<String, String> typeSubtype =
936 parseTypeAndSubtype(info.getServiceType());
937 final String serviceType = typeSubtype == null
938 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800939 if (clientInfo.mUseJavaBackend
940 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900941 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800942 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800943 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
944 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800945 break;
946 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900947 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800948
949 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000950 final MdnsListener listener = new ResolutionListener(clientRequestId,
951 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800952 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
953 .setNetwork(info.getNetwork())
954 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900955 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900956 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800957 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900958 mMdnsDiscoveryManager.registerListener(
959 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000960 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
961 listener, clientInfo, info.getNetwork());
962 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000963 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700964 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800965 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800966 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
967 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800968 break;
969 }
970
971 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000972 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800973 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +0000974 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
975 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +0800976 } else {
Paul Hu508a0122023-09-11 15:31:33 +0800977 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
978 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800979 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700980 }
981 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800982 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900983 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000984 if (DBG) Log.d(TAG, "Stop service resolution");
985 args = (ListenerArgs) msg.obj;
986 clientInfo = mClients.get(args.connector);
987 // If the binder death notification for a INsdManagerCallback was received
988 // before any calls are received by NsdService, the clientInfo would be
989 // cleared and cause NPE. Add a null check here to prevent this corner case.
990 if (clientInfo == null) {
991 Log.e(TAG, "Unknown connector in stop resolution");
992 break;
993 }
994
Paul Hud44e1b72023-06-16 02:07:42 +0000995 final ClientRequest request =
996 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900997 if (request == null) {
998 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
999 break;
1000 }
Paul Hud44e1b72023-06-16 02:07:42 +00001001 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001002 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1003 // point, so this needs to check the type of the original request to
1004 // unregister instead of looking at the flag value.
1005 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001006 stopDiscoveryManagerRequest(
1007 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001008 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001009 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001010 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001011 removeRequestMap(clientRequestId, transactionId, clientInfo);
1012 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001013 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001014 } else {
1015 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001016 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001017 }
1018 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001019 }
Paul Hub58deb72022-12-26 09:24:42 +00001020 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001021 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001022 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001023 if (DBG) Log.d(TAG, "Register a service callback");
1024 args = (ListenerArgs) msg.obj;
1025 clientInfo = mClients.get(args.connector);
1026 // If the binder death notification for a INsdManagerCallback was received
1027 // before any calls are received by NsdService, the clientInfo would be
1028 // cleared and cause NPE. Add a null check here to prevent this corner case.
1029 if (clientInfo == null) {
1030 Log.e(TAG, "Unknown connector in callback registration");
1031 break;
1032 }
1033
Paul Hu30bd70d2023-02-07 13:20:56 +00001034 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001035 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001036 final Pair<String, String> typeAndSubtype =
1037 parseTypeAndSubtype(info.getServiceType());
1038 final String serviceType = typeAndSubtype == null
1039 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001040 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001041 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001042 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001043 break;
1044 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001045 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001046
Paul Hu30bd70d2023-02-07 13:20:56 +00001047 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001048 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1049 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001050 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1051 .setNetwork(info.getNetwork())
1052 .setIsPassiveMode(true)
1053 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001054 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001055 .build();
1056 mMdnsDiscoveryManager.registerListener(
1057 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001058 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1059 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001060 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001061 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001062 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001063 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001064 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001065 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001066 if (DBG) Log.d(TAG, "Unregister a service callback");
1067 args = (ListenerArgs) msg.obj;
1068 clientInfo = mClients.get(args.connector);
1069 // If the binder death notification for a INsdManagerCallback was received
1070 // before any calls are received by NsdService, the clientInfo would be
1071 // cleared and cause NPE. Add a null check here to prevent this corner case.
1072 if (clientInfo == null) {
1073 Log.e(TAG, "Unknown connector in callback unregistration");
1074 break;
1075 }
1076
Paul Hud44e1b72023-06-16 02:07:42 +00001077 final ClientRequest request =
1078 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001079 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001080 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001081 break;
1082 }
Paul Hud44e1b72023-06-16 02:07:42 +00001083 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001084 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001085 stopDiscoveryManagerRequest(
1086 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001087 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001088 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001089 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001090 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001091 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001092 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001093 }
paulhu2b9ed952022-02-10 21:58:32 +08001094 case MDNS_SERVICE_EVENT:
1095 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001096 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001097 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001098 break;
Paul Hu019621e2023-01-13 23:26:49 +08001099 case MDNS_DISCOVERY_MANAGER_EVENT:
1100 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1101 return NOT_HANDLED;
1102 }
1103 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001104 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1105 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1106 // TODO: Limits the number of registrations created by a given class.
1107 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1108 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001109 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001110 break;
1111 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1112 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1113 break;
Paul Hu77c11182023-10-23 16:17:32 +08001114 case NsdManager.REGISTER_CLIENT:
1115 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1116 final INsdManagerCallback cb = arg.callback;
1117 try {
1118 cb.asBinder().linkToDeath(arg.connector, 0);
1119 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1120 final NetworkNsdReportedMetrics metrics =
1121 mDeps.makeNetworkNsdReportedMetrics(
1122 (int) mClock.elapsedRealtime());
1123 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1124 mServiceLogs.forSubComponent(tag), metrics);
1125 mClients.put(arg.connector, clientInfo);
1126 } catch (RemoteException e) {
1127 Log.w(TAG, "Client request id " + clientRequestId
1128 + " has already died");
1129 }
1130 break;
1131 case NsdManager.UNREGISTER_CLIENT:
1132 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1133 clientInfo = mClients.remove(connector);
1134 if (clientInfo != null) {
1135 clientInfo.expungeAllRequests();
1136 if (clientInfo.isPreSClient()) {
1137 mLegacyClientCount -= 1;
1138 }
1139 }
1140 maybeStopMonitoringSocketsIfNoActiveRequest();
1141 maybeScheduleStop();
1142 break;
1143 case NsdManager.DAEMON_CLEANUP:
1144 maybeStopDaemon();
1145 break;
1146 // This event should be only sent by the legacy (target SDK < S) clients.
1147 // Mark the sending client as legacy.
1148 case NsdManager.DAEMON_STARTUP:
1149 clientInfo = getClientInfoForReply(msg);
1150 if (clientInfo != null) {
1151 cancelStop();
1152 clientInfo.setPreSClient();
1153 mLegacyClientCount += 1;
1154 maybeStartDaemon();
1155 }
1156 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001157 default:
Paul Hu77c11182023-10-23 16:17:32 +08001158 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001159 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001160 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001161 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001162 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001163
Paul Hud44e1b72023-06-16 02:07:42 +00001164 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001165 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001166 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001167 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001168 Log.e(TAG, String.format(
1169 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001170 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001171 }
1172
1173 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001174 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1175 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001176 // This can happen because of race conditions. For example,
1177 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1178 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001179 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1180 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001181 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001182 }
Paul Hu812e9212023-06-20 06:24:53 +00001183 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1184 if (request == null) {
1185 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1186 return false;
1187 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001188 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001189 Log.d(TAG, String.format(
1190 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001191 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001192 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001193 case IMDnsEventListener.SERVICE_FOUND: {
1194 final DiscoveryInfo info = (DiscoveryInfo) obj;
1195 final String name = info.serviceName;
1196 final String type = info.registrationType;
1197 servInfo = new NsdServiceInfo(name, type);
1198 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001199 if (foundNetId == 0L) {
1200 // Ignore services that do not have a Network: they are not usable
1201 // by apps, as they would need privileged permissions to use
1202 // interfaces that do not have an associated Network.
1203 break;
1204 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001205 if (foundNetId == INetd.DUMMY_NET_ID) {
1206 // Ignore services on the dummy0 interface: they are only seen when
1207 // discovering locally advertised services, and are not reachable
1208 // through that interface.
1209 break;
1210 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001211 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001212
1213 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001214 break;
paulhu2b9ed952022-02-10 21:58:32 +08001215 }
1216 case IMDnsEventListener.SERVICE_LOST: {
1217 final DiscoveryInfo info = (DiscoveryInfo) obj;
1218 final String name = info.serviceName;
1219 final String type = info.registrationType;
1220 final int lostNetId = info.netId;
1221 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001222 // The network could be set to null (netId 0) if it was torn down when the
1223 // service is lost
1224 // TODO: avoid returning null in that case, possibly by remembering
1225 // found services on the same interface index and their network at the time
1226 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001227 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001228 break;
paulhu2b9ed952022-02-10 21:58:32 +08001229 }
1230 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001231 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001232 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1233 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001234 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001235 break;
paulhu2b9ed952022-02-10 21:58:32 +08001236 case IMDnsEventListener.SERVICE_REGISTERED: {
1237 final RegistrationInfo info = (RegistrationInfo) obj;
1238 final String name = info.serviceName;
1239 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001240 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001241 break;
paulhu2b9ed952022-02-10 21:58:32 +08001242 }
1243 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001244 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001245 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1246 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001247 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001248 break;
paulhu2b9ed952022-02-10 21:58:32 +08001249 case IMDnsEventListener.SERVICE_RESOLVED: {
1250 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001251 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001252 final String fullName = info.serviceFullName;
1253 while (index < fullName.length() && fullName.charAt(index) != '.') {
1254 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001255 ++index;
1256 }
1257 ++index;
1258 }
paulhu2b9ed952022-02-10 21:58:32 +08001259 if (index >= fullName.length()) {
1260 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001261 break;
1262 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001263
paulhube186602022-04-12 07:18:23 +00001264 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001265 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001266 String type = rest.replace(".local.", "");
1267
Paul Hu30bd70d2023-02-07 13:20:56 +00001268 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001269 serviceInfo.setServiceName(name);
1270 serviceInfo.setServiceType(type);
1271 serviceInfo.setPort(info.port);
1272 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001273 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001274
Paul Hud44e1b72023-06-16 02:07:42 +00001275 stopResolveService(transactionId);
1276 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001277
Paul Hud44e1b72023-06-16 02:07:42 +00001278 final int transactionId2 = getUniqueId();
1279 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1280 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001281 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001282 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001283 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001284 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1285 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001286 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001287 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001288 }
1289 break;
paulhu2b9ed952022-02-10 21:58:32 +08001290 }
1291 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001292 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001293 stopResolveService(transactionId);
1294 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001295 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001296 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1297 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001298 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001299 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001300 break;
paulhu2b9ed952022-02-10 21:58:32 +08001301 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001302 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001303 stopGetAddrInfo(transactionId);
1304 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001305 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001306 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1307 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001308 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001309 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001310 break;
paulhu2b9ed952022-02-10 21:58:32 +08001311 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001312 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001313 final GetAddressInfo info = (GetAddressInfo) obj;
1314 final String address = info.address;
1315 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001316 InetAddress serviceHost = null;
1317 try {
paulhu2b9ed952022-02-10 21:58:32 +08001318 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001319 } catch (UnknownHostException e) {
1320 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1321 }
1322
1323 // If the resolved service is on an interface without a network, consider it
1324 // as a failure: it would not be usable by apps as they would need
1325 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001326 if (netId != NETID_UNSET && serviceHost != null) {
1327 clientInfo.mResolvedService.setHost(serviceHost);
1328 setServiceNetworkForCallback(clientInfo.mResolvedService,
1329 netId, info.interfaceIdx);
1330 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001331 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001332 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001333 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001334 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1335 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001336 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001337 }
Paul Hud44e1b72023-06-16 02:07:42 +00001338 stopGetAddrInfo(transactionId);
1339 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001340 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 break;
paulhu2b9ed952022-02-10 21:58:32 +08001342 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001344 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001345 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001346 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 }
Paul Hu019621e2023-01-13 23:26:49 +08001348
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001349 @Nullable
1350 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1351 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001352 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001353 final String[] typeArray = serviceInfo.getServiceType();
1354 final String joinedType;
1355 if (typeArray.length == 0
1356 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1357 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1358 + Arrays.toString(typeArray));
1359 return null;
1360 } else {
1361 joinedType = TextUtils.join(".",
1362 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1363 }
1364 final String serviceType;
1365 switch (code) {
1366 case NsdManager.SERVICE_FOUND:
1367 case NsdManager.SERVICE_LOST:
1368 // For consistency with historical behavior, discovered service types have
1369 // a dot at the end.
1370 serviceType = joinedType + ".";
1371 break;
1372 case RESOLVE_SERVICE_SUCCEEDED:
1373 // For consistency with historical behavior, resolved service types have
1374 // a dot at the beginning.
1375 serviceType = "." + joinedType;
1376 break;
1377 default:
1378 serviceType = joinedType;
1379 break;
1380 }
Paul Hu019621e2023-01-13 23:26:49 +08001381 final String serviceName = serviceInfo.getServiceInstanceName();
1382 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1383 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001384 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1385 // network for Tethering interface. In other words, the network == null means the
1386 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001387 setServiceNetworkForCallback(
1388 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001389 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001390 serviceInfo.getInterfaceIndex());
1391 return servInfo;
1392 }
1393
1394 private boolean handleMdnsDiscoveryManagerEvent(
1395 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001396 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001397 if (clientInfo == null) {
1398 Log.e(TAG, String.format(
1399 "id %d for %d has no client mapping", transactionId, code));
1400 return false;
1401 }
1402
1403 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001404 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001405 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1406 if (request == null) {
1407 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1408 return false;
1409 }
1410
1411 // Deal with the discovery sent callback
1412 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1413 request.onQuerySent();
1414 return true;
1415 }
1416
1417 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001418 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1419 // Errors are already logged if null
1420 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001421 mServiceLogs.log(String.format(
1422 "MdnsDiscoveryManager event code=%s transactionId=%d",
1423 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001424 switch (code) {
1425 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001426 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001427 break;
1428 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001429 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001430 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001431 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1432 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001433 info.setPort(serviceInfo.getPort());
1434
1435 Map<String, String> attrs = serviceInfo.getAttributes();
1436 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1437 final String key = kv.getKey();
1438 try {
1439 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1440 } catch (IllegalArgumentException e) {
1441 Log.e(TAG, "Invalid attribute", e);
1442 }
1443 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001444 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001445 if (addresses.size() != 0) {
1446 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001447 request.setServiceFromCache(event.mIsServiceFromCache);
1448 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001449 } else {
1450 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001451 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001452 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1453 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001454 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001455 }
1456
1457 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001458 if (!(request instanceof DiscoveryManagerRequest)) {
1459 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1460 break;
1461 }
Paul Hud44e1b72023-06-16 02:07:42 +00001462 stopDiscoveryManagerRequest(
1463 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001464 break;
1465 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001466 case NsdManager.SERVICE_UPDATED: {
1467 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1468 info.setPort(serviceInfo.getPort());
1469
1470 Map<String, String> attrs = serviceInfo.getAttributes();
1471 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1472 final String key = kv.getKey();
1473 try {
1474 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1475 } catch (IllegalArgumentException e) {
1476 Log.e(TAG, "Invalid attribute", e);
1477 }
1478 }
1479
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001480 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001481 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001482 clientInfo.onServiceUpdated(clientRequestId, info, request);
1483 // Set the ServiceFromCache flag only if the service is actually being
1484 // retrieved from the cache. This flag should not be overridden by later
1485 // service updates, which may not be cached.
1486 if (event.mIsServiceFromCache) {
1487 request.setServiceFromCache(true);
1488 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001489 break;
1490 }
1491 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001492 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001493 break;
Paul Hu019621e2023-01-13 23:26:49 +08001494 default:
1495 return false;
1496 }
1497 return true;
1498 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001499 }
1500 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001501
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001502 @NonNull
1503 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1504 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1505 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1506 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1507 for (String ipv4Address : v4Addrs) {
1508 try {
1509 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1510 } catch (IllegalArgumentException e) {
1511 Log.wtf(TAG, "Invalid ipv4 address", e);
1512 }
1513 }
1514 for (String ipv6Address : v6Addrs) {
1515 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001516 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1517 ipv6Address);
1518 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1519 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001520 Log.wtf(TAG, "Invalid ipv6 address", e);
1521 }
1522 }
1523 return addresses;
1524 }
1525
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001526 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1527 switch (netId) {
1528 case NETID_UNSET:
1529 info.setNetwork(null);
1530 break;
1531 case INetd.LOCAL_NET_ID:
1532 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1533 // visible / usable for apps, so do not return it. Store the interface
1534 // index instead, so at least if the client tries to resolve the service
1535 // with that NsdServiceInfo, it will be done on the same interface.
1536 // If they recreate the NsdServiceInfo themselves, resolution would be
1537 // done on all interfaces as before T, which should also work.
1538 info.setNetwork(null);
1539 info.setInterfaceIndex(ifaceIdx);
1540 break;
1541 default:
1542 info.setNetwork(new Network(netId));
1543 }
1544 }
1545
paulhube186602022-04-12 07:18:23 +00001546 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1547 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1548 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1549 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1550 private String unescape(String s) {
1551 StringBuilder sb = new StringBuilder(s.length());
1552 for (int i = 0; i < s.length(); ++i) {
1553 char c = s.charAt(i);
1554 if (c == '\\') {
1555 if (++i >= s.length()) {
1556 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1557 break;
1558 }
1559 c = s.charAt(i);
1560 if (c != '.' && c != '\\') {
1561 if (i + 2 >= s.length()) {
1562 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1563 break;
1564 }
1565 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1566 + (s.charAt(i + 2) - '0'));
1567 i += 2;
1568 }
1569 }
1570 sb.append(c);
1571 }
1572 return sb.toString();
1573 }
1574
Paul Hu7445e3d2023-03-03 15:14:00 +08001575 /**
1576 * Check the given service type is valid and construct it to a service type
1577 * which can use for discovery / resolution service.
1578 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001579 * <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 +08001580 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1581 * underscore; they are alphanumerical characters or dashes or underscore, except the
1582 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1583 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001584 * <p>The subtype may also be specified with a comma after the service type, for example
1585 * _type._tcp,_subtype.
1586 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001587 * @param serviceType the request service type for discovery / resolution service
1588 * @return constructed service type or null if the given service type is invalid.
1589 */
1590 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001591 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001592 if (TextUtils.isEmpty(serviceType)) return null;
1593
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001594 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001595 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001596 // Optional leading subtype (_subtype._type._tcp)
1597 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1598 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1599 // Actual type (_type._tcp.local)
1600 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001601 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001602 // e.g. allow "_type._tcp.local."
1603 + "\\.?"
1604 // Optional subtype after comma, for "_type._tcp,_subtype" format
1605 + "(?:,(" + typeOrSubtypePattern + "))?"
1606 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001607 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1608 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001609 // Use the subtype either at the beginning or after the comma
1610 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1611 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001612 }
1613
Hugo Benichi803a2f02017-04-24 11:35:06 +09001614 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001615 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001616 this(ctx, handler, cleanupDelayMs, new Dependencies());
1617 }
1618
1619 @VisibleForTesting
1620 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001621 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001622 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001623 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001624 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001625 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1626 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001627 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001628
Paul Hu14667de2023-04-17 22:42:47 +08001629 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001630 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001631 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001632 // address events are received. When the netlink monitor starts, any IP addresses already
1633 // on the interfaces will not be seen. In practice, the network will not connect at boot
1634 // time As a result, all the netlink message should be observed if the netlink monitor
1635 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001636 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001637
1638 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1639 // startBootstrapServices).
1640 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1641 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1642 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1643 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1644 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1645 mRunningAppActiveImportanceCutoff);
1646
Paul Huf3fe3332023-10-16 17:13:25 +08001647 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1648 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1649 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1650 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1651 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001652 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1653 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001654 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1655 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001656 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001657 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001658 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001659 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001660 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001661 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001662 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1663 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001664 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001665 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001666 }
1667
1668 /**
1669 * Dependencies of NsdService, for injection in tests.
1670 */
1671 @VisibleForTesting
1672 public static class Dependencies {
1673 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001674 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001675 *
1676 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001677 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001678 */
1679 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001680 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001681 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001682 }
1683
1684 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001685 * Check whether the MdnsAdvertiser feature is enabled.
1686 *
1687 * @param context The global context information about an app environment.
1688 * @return true if the MdnsAdvertiser feature is enabled.
1689 */
1690 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001691 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001692 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001693 }
1694
1695 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001696 * Get the type allowlist flag value.
1697 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1698 */
1699 @Nullable
1700 public String getTypeAllowlistFlags() {
1701 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1702 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1703 }
1704
1705 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001706 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001707 */
1708 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001709 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001710 }
1711
1712 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001713 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1714 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001715 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1716 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001717 }
1718
1719 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001720 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1721 */
1722 public boolean isTrunkStableFeatureEnabled(String feature) {
1723 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1724 }
1725
1726 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001727 * @see MdnsDiscoveryManager
1728 */
1729 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001730 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001731 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1732 @NonNull MdnsFeatureFlags featureFlags) {
1733 return new MdnsDiscoveryManager(
1734 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001735 }
1736
1737 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001738 * @see MdnsAdvertiser
1739 */
1740 public MdnsAdvertiser makeMdnsAdvertiser(
1741 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001742 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1743 MdnsFeatureFlags featureFlags) {
1744 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001745 }
1746
1747 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001748 * @see MdnsSocketProvider
1749 */
Paul Hu14667de2023-04-17 22:42:47 +08001750 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001751 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1752 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1753 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1754 }
1755
1756 /**
1757 * @see DeviceConfig#getInt(String, String, int)
1758 */
1759 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1760 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1761 }
1762
1763 /**
1764 * @see Binder#getCallingUid()
1765 */
1766 public int getCallingUid() {
1767 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001768 }
Paul Hu777ed052023-06-19 13:35:15 +00001769
1770 /**
1771 * @see NetworkNsdReportedMetrics
1772 */
Paul Hu508a0122023-09-11 15:31:33 +08001773 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1774 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001775 }
1776
1777 /**
1778 * @see MdnsUtils.Clock
1779 */
1780 public Clock makeClock() {
1781 return new Clock();
1782 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001783 }
1784
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001785 /**
1786 * Return whether a type is allowlisted to use the Java backend.
1787 * @param type The service type
1788 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1789 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1790 */
1791 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1792 @NonNull String flagPrefix) {
1793 if (type == null) return false;
1794 final String typesConfig = mDeps.getTypeAllowlistFlags();
1795 if (TextUtils.isEmpty(typesConfig)) return false;
1796
1797 final String mappingPrefix = type + ":";
1798 String mappedFlag = null;
1799 for (String mapping : TextUtils.split(typesConfig, ",")) {
1800 if (mapping.startsWith(mappingPrefix)) {
1801 mappedFlag = mapping.substring(mappingPrefix.length());
1802 break;
1803 }
1804 }
1805
1806 if (mappedFlag == null) return false;
1807
1808 return mDeps.isFeatureEnabled(mContext,
1809 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1810 }
1811
1812 private boolean useDiscoveryManagerForType(@Nullable String type) {
1813 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1814 }
1815
1816 private boolean useAdvertiserForType(@Nullable String type) {
1817 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1818 }
1819
paulhu1b35e822022-04-08 14:48:41 +08001820 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001821 HandlerThread thread = new HandlerThread(TAG);
1822 thread.start();
1823 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001824 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001825 return service;
1826 }
1827
paulhu2b9ed952022-02-10 21:58:32 +08001828 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1829 private final StateMachine mStateMachine;
1830
1831 MDnsEventCallback(StateMachine sm) {
1832 mStateMachine = sm;
1833 }
1834
1835 @Override
1836 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1837 mStateMachine.sendMessage(
1838 MDNS_SERVICE_EVENT, status.result, status.id, status);
1839 }
1840
1841 @Override
1842 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1843 mStateMachine.sendMessage(
1844 MDNS_SERVICE_EVENT, status.result, status.id, status);
1845 }
1846
1847 @Override
1848 public void onServiceResolutionStatus(final ResolutionInfo status) {
1849 mStateMachine.sendMessage(
1850 MDNS_SERVICE_EVENT, status.result, status.id, status);
1851 }
1852
1853 @Override
1854 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1855 mStateMachine.sendMessage(
1856 MDNS_SERVICE_EVENT, status.result, status.id, status);
1857 }
1858
1859 @Override
1860 public int getInterfaceVersion() throws RemoteException {
1861 return this.VERSION;
1862 }
1863
1864 @Override
1865 public String getInterfaceHash() throws RemoteException {
1866 return this.HASH;
1867 }
1868 }
1869
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001870 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1871 final String targetInterface = offloadEngineInfo.mInterfaceName;
1872 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1873 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1874 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1875 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1876 try {
1877 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1878 } catch (RemoteException e) {
1879 // Can happen in regular cases, do not log a stacktrace
1880 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1881 }
1882 }
1883 }
1884
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001885 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1886 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1887 final int count = mOffloadEngines.beginBroadcast();
1888 try {
1889 for (int i = 0; i < count; i++) {
1890 final OffloadEngineInfo offloadEngineInfo =
1891 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1892 final String interfaceName = offloadEngineInfo.mInterfaceName;
1893 if (!targetInterfaceName.equals(interfaceName)
1894 || ((offloadEngineInfo.mOffloadType
1895 & offloadServiceInfo.getOffloadType()) == 0)) {
1896 continue;
1897 }
1898 try {
1899 if (isRemove) {
1900 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1901 offloadServiceInfo);
1902 } else {
1903 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1904 offloadServiceInfo);
1905 }
1906 } catch (RemoteException e) {
1907 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001908 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001909 }
1910 }
1911 } finally {
1912 mOffloadEngines.finishBroadcast();
1913 }
1914 }
1915
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001916 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001917 // TODO: add a callback to notify when a service is being added on each interface (as soon
1918 // as probing starts), and call mOffloadCallbacks. This callback is for
1919 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1920
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001921 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001922 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1923 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1924 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001925 if (clientInfo == null) return;
1926
Paul Hud44e1b72023-06-16 02:07:42 +00001927 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1928 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001929
1930 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1931 // historical behavior.
1932 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001933 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001934 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001935 }
1936
1937 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001938 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1939 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001940 if (clientInfo == null) return;
1941
Paul Hud44e1b72023-06-16 02:07:42 +00001942 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1943 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001944 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001945 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1946 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001947 }
1948
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001949 @Override
1950 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1951 @NonNull OffloadServiceInfo offloadServiceInfo) {
1952 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1953 }
1954
1955 @Override
1956 public void onOffloadStop(@NonNull String interfaceName,
1957 @NonNull OffloadServiceInfo offloadServiceInfo) {
1958 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1959 }
1960
Paul Hud44e1b72023-06-16 02:07:42 +00001961 private ClientInfo getClientInfoOrLog(int transactionId) {
1962 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001963 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001964 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001965 }
1966 return clientInfo;
1967 }
1968
Paul Hud44e1b72023-06-16 02:07:42 +00001969 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1970 final int clientRequestId = info.getClientRequestId(transactionId);
1971 if (clientRequestId < 0) {
1972 Log.e(TAG, String.format(
1973 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001974 }
Paul Hud44e1b72023-06-16 02:07:42 +00001975 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001976 }
1977 }
1978
Paul Hu2e0a88c2023-03-09 16:05:01 +08001979 private static class ConnectorArgs {
1980 @NonNull public final NsdServiceConnector connector;
1981 @NonNull public final INsdManagerCallback callback;
1982 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001983 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001984
1985 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001986 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001987 this.connector = connector;
1988 this.callback = callback;
1989 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001990 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001991 }
1992 }
1993
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001994 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001995 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001996 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001997 final int uid = mDeps.getCallingUid();
1998 if (cb == null) {
1999 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2000 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002001 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002002 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002003 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002004 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002005 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002006 }
2007
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002008 private static class ListenerArgs {
2009 public final NsdServiceConnector connector;
2010 public final NsdServiceInfo serviceInfo;
2011 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2012 this.connector = connector;
2013 this.serviceInfo = serviceInfo;
2014 }
2015 }
2016
2017 private class NsdServiceConnector extends INsdServiceConnector.Stub
2018 implements IBinder.DeathRecipient {
2019 @Override
2020 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2021 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2022 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2023 new ListenerArgs(this, serviceInfo)));
2024 }
2025
2026 @Override
2027 public void unregisterService(int listenerKey) {
2028 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2029 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2030 new ListenerArgs(this, null)));
2031 }
2032
2033 @Override
2034 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2035 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2036 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2037 new ListenerArgs(this, serviceInfo)));
2038 }
2039
2040 @Override
2041 public void stopDiscovery(int listenerKey) {
2042 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2043 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2044 }
2045
2046 @Override
2047 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2048 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2049 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2050 new ListenerArgs(this, serviceInfo)));
2051 }
2052
2053 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002054 public void stopResolution(int listenerKey) {
2055 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2056 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2057 }
2058
2059 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002060 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2061 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2062 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2063 new ListenerArgs(this, serviceInfo)));
2064 }
2065
2066 @Override
2067 public void unregisterServiceInfoCallback(int listenerKey) {
2068 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2069 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2070 new ListenerArgs(this, null)));
2071 }
2072
2073 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002074 public void startDaemon() {
2075 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2076 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2077 }
2078
2079 @Override
2080 public void binderDied() {
2081 mNsdStateMachine.sendMessage(
2082 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002083
2084 }
2085
2086 @Override
2087 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2088 @OffloadEngine.OffloadCapability long offloadCapabilities,
2089 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002090 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002091 Objects.requireNonNull(ifaceName);
2092 Objects.requireNonNull(cb);
2093 mNsdStateMachine.sendMessage(
2094 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2095 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2096 offloadTypes)));
2097 }
2098
2099 @Override
2100 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002101 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002102 Objects.requireNonNull(cb);
2103 mNsdStateMachine.sendMessage(
2104 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002105 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002106
2107 private static void checkOffloadEnginePermission(Context context) {
2108 if (!SdkLevel.isAtLeastT()) {
2109 throw new SecurityException("API is not available in before API level 33");
2110 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002111
2112 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2113 if (SdkLevel.isAtLeastV() && PermissionUtils.checkAnyPermissionOf(context,
2114 REGISTER_NSD_OFFLOAD_ENGINE)) {
2115 return;
2116 }
2117
2118 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2119 // permission instead.
2120 if (!SdkLevel.isAtLeastV() && SdkLevel.isAtLeastU()
2121 && PermissionUtils.checkAnyPermissionOf(context, DEVICE_POWER)) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002122 return;
2123 }
2124 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2125 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2126 return;
2127 }
2128 throw new SecurityException("Requires one of the following permissions: "
2129 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2130 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2131 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002132 }
2133
Hugo Benichi912db992017-04-24 16:41:03 +09002134 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002135 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002136 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002137 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2138 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002139 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002140 }
2141
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002142 private int getUniqueId() {
2143 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2144 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002145 }
2146
Paul Hud44e1b72023-06-16 02:07:42 +00002147 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002148 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002149 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002150 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002151 String name = service.getServiceName();
2152 String type = service.getServiceType();
2153 int port = service.getPort();
2154 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002155 final int registerInterface = getNetworkInterfaceIndex(service);
2156 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002157 Log.e(TAG, "Interface to register service on not found");
2158 return false;
2159 }
Paul Hud44e1b72023-06-16 02:07:42 +00002160 return mMDnsManager.registerService(
2161 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002162 }
2163
Paul Hud44e1b72023-06-16 02:07:42 +00002164 private boolean unregisterService(int transactionId) {
2165 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002166 }
2167
Paul Hud44e1b72023-06-16 02:07:42 +00002168 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002169 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002170 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2171 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002172 Log.e(TAG, "Interface to discover service on not found");
2173 return false;
2174 }
Paul Hud44e1b72023-06-16 02:07:42 +00002175 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002176 }
2177
Paul Hud44e1b72023-06-16 02:07:42 +00002178 private boolean stopServiceDiscovery(int transactionId) {
2179 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002180 }
2181
Paul Hud44e1b72023-06-16 02:07:42 +00002182 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002183 final String name = service.getServiceName();
2184 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002185 final int resolveInterface = getNetworkInterfaceIndex(service);
2186 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002187 Log.e(TAG, "Interface to resolve service on not found");
2188 return false;
2189 }
Paul Hud44e1b72023-06-16 02:07:42 +00002190 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002191 }
2192
2193 /**
2194 * Guess the interface to use to resolve or discover a service on a specific network.
2195 *
2196 * This is an imperfect guess, as for example the network may be gone or not yet fully
2197 * registered. This is fine as failing is correct if the network is gone, and a client
2198 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2199 * this is to support the legacy mdnsresponder implementation, which historically resolved
2200 * services on an unspecified network.
2201 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002202 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2203 final Network network = serviceInfo.getNetwork();
2204 if (network == null) {
2205 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2206 // provided by NsdService from discovery results, and the service was found on an
2207 // interface that has no app-usable Network).
2208 if (serviceInfo.getInterfaceIndex() != 0) {
2209 return serviceInfo.getInterfaceIndex();
2210 }
2211 return IFACE_IDX_ANY;
2212 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002213
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002214 String interfaceName = getNetworkInterfaceName(network);
2215 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002216 return IFACE_IDX_ANY;
2217 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002218 return getNetworkInterfaceIndexByName(interfaceName);
2219 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002220
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002221 private String getNetworkInterfaceName(@Nullable Network network) {
2222 if (network == null) {
2223 return null;
2224 }
2225 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2226 if (cm == null) {
2227 Log.wtf(TAG, "No ConnectivityManager");
2228 return null;
2229 }
2230 final LinkProperties lp = cm.getLinkProperties(network);
2231 if (lp == null) {
2232 return null;
2233 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002234 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002235 return lp.getInterfaceName();
2236 }
2237
2238 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002239 final NetworkInterface iface;
2240 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002241 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002242 } catch (SocketException e) {
2243 Log.e(TAG, "Error querying interface", e);
2244 return IFACE_IDX_ANY;
2245 }
2246
2247 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002248 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002249 return IFACE_IDX_ANY;
2250 }
2251
2252 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002253 }
2254
Paul Hud44e1b72023-06-16 02:07:42 +00002255 private boolean stopResolveService(int transactionId) {
2256 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002257 }
2258
Paul Hud44e1b72023-06-16 02:07:42 +00002259 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2260 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002261 }
2262
Paul Hud44e1b72023-06-16 02:07:42 +00002263 private boolean stopGetAddrInfo(int transactionId) {
2264 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002265 }
2266
2267 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002268 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2269 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002270
Paul Hub2e67d32023-04-18 05:50:14 +00002271 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2272 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002273 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002274
2275 // Dump service and clients logs
2276 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002277 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002278 pw.increaseIndent();
2279 mServiceLogs.reverseDump(pw);
2280 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002281 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002282
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002283 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002284 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002285 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002286 private int mFoundServiceCount = 0;
2287 private int mLostServiceCount = 0;
2288 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002289 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002290 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002291
Paul Hu812e9212023-06-20 06:24:53 +00002292 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002293 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002294 mStartTimeMs = startTimeMs;
2295 }
2296
Paul Hu812e9212023-06-20 06:24:53 +00002297 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002298 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002299 }
Paul Hu812e9212023-06-20 06:24:53 +00002300
2301 public void onServiceFound(String serviceName) {
2302 mFoundServiceCount++;
2303 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2304 mServices.add(serviceName);
2305 }
2306 }
2307
2308 public void onServiceLost() {
2309 mLostServiceCount++;
2310 }
2311
2312 public int getFoundServiceCount() {
2313 return mFoundServiceCount;
2314 }
2315
2316 public int getLostServiceCount() {
2317 return mLostServiceCount;
2318 }
2319
2320 public int getServicesCount() {
2321 return mServices.size();
2322 }
Paul Hua6bc4632023-06-26 01:18:29 +00002323
2324 public void setServiceFromCache(boolean isServiceFromCache) {
2325 mIsServiceFromCache = isServiceFromCache;
2326 }
2327
2328 public boolean isServiceFromCache() {
2329 return mIsServiceFromCache;
2330 }
Paul Hubad6fe92023-07-24 21:25:22 +08002331
2332 public void onQuerySent() {
2333 mSentQueryCount++;
2334 }
2335
2336 public int getSentQueryCount() {
2337 return mSentQueryCount;
2338 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002339 }
2340
2341 private static class LegacyClientRequest extends ClientRequest {
2342 private final int mRequestCode;
2343
Paul Hu812e9212023-06-20 06:24:53 +00002344 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2345 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002346 mRequestCode = requestCode;
2347 }
2348 }
2349
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002350 private abstract static class JavaBackendClientRequest extends ClientRequest {
2351 @Nullable
2352 private final Network mRequestedNetwork;
2353
Paul Hu777ed052023-06-19 13:35:15 +00002354 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002355 long startTimeMs) {
2356 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002357 mRequestedNetwork = requestedNetwork;
2358 }
2359
2360 @Nullable
2361 public Network getRequestedNetwork() {
2362 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002363 }
2364 }
2365
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002366 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002367 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002368 long startTimeMs) {
2369 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002370 }
2371 }
2372
2373 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002374 @NonNull
2375 private final MdnsListener mListener;
2376
Paul Hud44e1b72023-06-16 02:07:42 +00002377 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002378 @Nullable Network requestedNetwork, long startTimeMs) {
2379 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002380 mListener = listener;
2381 }
2382 }
2383
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002384 /* Information tracked per client */
2385 private class ClientInfo {
2386
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002387 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002388 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002389 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002390 private NsdServiceInfo mResolvedService;
2391
Paul Hud44e1b72023-06-16 02:07:42 +00002392 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002393 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002394
Luke Huangf7277ed2021-07-12 21:15:10 +08002395 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002396 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002397 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002398 // The flag of using java backend if the client's target SDK >= U
2399 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002400 // Store client logs
2401 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002402 // Report the nsd metrics data
2403 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002404
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002405 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002406 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002407 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002408 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002409 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002410 mClientLogs = sharedLog;
2411 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002412 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002413 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002414
2415 @Override
2416 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002417 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002418 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002419 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002420 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2421 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002422 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002423 int clientRequestId = mClientRequests.keyAt(i);
2424 sb.append("clientRequestId ")
2425 .append(clientRequestId)
2426 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002427 .append(" type ").append(
2428 mClientRequests.valueAt(i).getClass().getSimpleName())
2429 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002430 }
2431 return sb.toString();
2432 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002433
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002434 private boolean isPreSClient() {
2435 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002436 }
2437
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002438 private void setPreSClient() {
2439 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002440 }
2441
Paul Hu812e9212023-06-20 06:24:53 +00002442 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002443 final MdnsListener listener =
2444 ((DiscoveryManagerRequest) request).mListener;
2445 mMdnsDiscoveryManager.unregisterListener(
2446 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002447 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002448 }
2449
Dave Plattfeff2af2014-03-07 14:48:22 -08002450 // Remove any pending requests from the global map when we get rid of a client,
2451 // and send cancellations to the daemon.
2452 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002453 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002454 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002455 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002456 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002457 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002458 final int transactionId = request.mTransactionId;
2459 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002460 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002461 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2462 + " transactionId " + transactionId
2463 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002464 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002465
2466 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002467 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2468 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002469 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002470 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2471 request.getFoundServiceCount(),
2472 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002473 request.getServicesCount(),
2474 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002475 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002476 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002477 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002478 } else if (listener instanceof ServiceInfoListener) {
2479 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2480 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2481 request.getFoundServiceCount(),
2482 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002483 request.isServiceFromCache(),
2484 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002485 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002486 continue;
2487 }
2488
2489 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002490 final AdvertiserMetrics metrics =
2491 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002492 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002493 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002494 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2495 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2496 metrics.mConflictDuringProbingCount,
2497 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002498 continue;
2499 }
2500
2501 if (!(request instanceof LegacyClientRequest)) {
2502 throw new IllegalStateException("Unknown request type: " + request.getClass());
2503 }
2504
2505 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002506 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002507 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002508 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002509 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2510 request.getFoundServiceCount(),
2511 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002512 request.getServicesCount(),
2513 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002514 break;
2515 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002516 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002517 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002518 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002519 break;
2520 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002521 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002522 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002523 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2524 NO_PACKET /* repliedRequestsCount */,
2525 NO_PACKET /* sentPacketCount */,
2526 0 /* conflictDuringProbingCount */,
2527 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002528 break;
2529 default:
2530 break;
2531 }
2532 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002533 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002534 updateMulticastLock();
2535 }
2536
2537 /**
2538 * Returns true if this client has any Java backend request that requests one of the given
2539 * networks.
2540 */
2541 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2542 for (int i = 0; i < mClientRequests.size(); i++) {
2543 final ClientRequest req = mClientRequests.valueAt(i);
2544 if (!(req instanceof JavaBackendClientRequest)) {
2545 continue;
2546 }
2547 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2548 .getRequestedNetwork();
2549 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2550 return true;
2551 }
2552 }
2553 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002554 }
2555
Paul Hud44e1b72023-06-16 02:07:42 +00002556 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2557 // transaction id, return the corresponding client request id.
2558 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002559 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002560 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002561 return mClientRequests.keyAt(i);
2562 }
Christopher Lane74411222014-04-25 18:39:07 -07002563 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002564 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002565 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002566
Paul Hub2e67d32023-04-18 05:50:14 +00002567 private void log(String message) {
2568 mClientLogs.log(message);
2569 }
2570
Paul Hu508a0122023-09-11 15:31:33 +08002571 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2572 return !(request instanceof DiscoveryManagerRequest)
2573 && !(request instanceof AdvertiserClientRequest);
2574 }
2575
2576 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2577 ClientRequest request) {
2578 mMetrics.reportServiceDiscoveryStarted(
2579 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002580 try {
2581 mCb.onDiscoverServicesStarted(listenerKey, info);
2582 } catch (RemoteException e) {
2583 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2584 }
2585 }
Paul Hu508a0122023-09-11 15:31:33 +08002586 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2587 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2588 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002589 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002590
Paul Hu508a0122023-09-11 15:31:33 +08002591 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2592 int transactionId, long durationMs) {
2593 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002594 try {
2595 mCb.onDiscoverServicesFailed(listenerKey, error);
2596 } catch (RemoteException e) {
2597 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2598 }
2599 }
2600
Paul Hu812e9212023-06-20 06:24:53 +00002601 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2602 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002603 try {
2604 mCb.onServiceFound(listenerKey, info);
2605 } catch (RemoteException e) {
2606 Log.e(TAG, "Error calling onServiceFound(", e);
2607 }
2608 }
2609
Paul Hu812e9212023-06-20 06:24:53 +00002610 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2611 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002612 try {
2613 mCb.onServiceLost(listenerKey, info);
2614 } catch (RemoteException e) {
2615 Log.e(TAG, "Error calling onServiceLost(", e);
2616 }
2617 }
2618
2619 void onStopDiscoveryFailed(int listenerKey, int error) {
2620 try {
2621 mCb.onStopDiscoveryFailed(listenerKey, error);
2622 } catch (RemoteException e) {
2623 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2624 }
2625 }
2626
Paul Hu812e9212023-06-20 06:24:53 +00002627 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2628 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002629 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002630 request.mTransactionId,
2631 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2632 request.getFoundServiceCount(),
2633 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002634 request.getServicesCount(),
2635 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002636 try {
2637 mCb.onStopDiscoverySucceeded(listenerKey);
2638 } catch (RemoteException e) {
2639 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2640 }
2641 }
2642
Paul Hu508a0122023-09-11 15:31:33 +08002643 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2644 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2645 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002646 }
2647
Paul Hu508a0122023-09-11 15:31:33 +08002648 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2649 int transactionId, long durationMs) {
2650 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002651 try {
2652 mCb.onRegisterServiceFailed(listenerKey, error);
2653 } catch (RemoteException e) {
2654 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2655 }
2656 }
2657
Paul Hu508a0122023-09-11 15:31:33 +08002658 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2659 ClientRequest request) {
2660 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2661 request.mTransactionId,
2662 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002663 try {
2664 mCb.onRegisterServiceSucceeded(listenerKey, info);
2665 } catch (RemoteException e) {
2666 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2667 }
2668 }
2669
2670 void onUnregisterServiceFailed(int listenerKey, int error) {
2671 try {
2672 mCb.onUnregisterServiceFailed(listenerKey, error);
2673 } catch (RemoteException e) {
2674 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2675 }
2676 }
2677
Paul Hu508a0122023-09-11 15:31:33 +08002678 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002679 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002680 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2681 request.mTransactionId,
2682 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002683 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2684 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002685 try {
2686 mCb.onUnregisterServiceSucceeded(listenerKey);
2687 } catch (RemoteException e) {
2688 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2689 }
2690 }
2691
Paul Hu508a0122023-09-11 15:31:33 +08002692 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2693 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2694 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002695 }
2696
Paul Hu508a0122023-09-11 15:31:33 +08002697 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2698 int transactionId, long durationMs) {
2699 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002700 try {
2701 mCb.onResolveServiceFailed(listenerKey, error);
2702 } catch (RemoteException e) {
2703 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2704 }
2705 }
2706
Paul Hua6bc4632023-06-26 01:18:29 +00002707 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2708 ClientRequest request) {
2709 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002710 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002711 request.mTransactionId,
2712 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002713 request.isServiceFromCache(),
2714 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002715 try {
2716 mCb.onResolveServiceSucceeded(listenerKey, info);
2717 } catch (RemoteException e) {
2718 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2719 }
2720 }
Paul Hub58deb72022-12-26 09:24:42 +00002721
2722 void onStopResolutionFailed(int listenerKey, int error) {
2723 try {
2724 mCb.onStopResolutionFailed(listenerKey, error);
2725 } catch (RemoteException e) {
2726 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2727 }
2728 }
2729
Paul Hu60149052023-07-31 14:26:08 +08002730 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2731 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002732 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002733 request.mTransactionId,
2734 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002735 try {
2736 mCb.onStopResolutionSucceeded(listenerKey);
2737 } catch (RemoteException e) {
2738 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2739 }
2740 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002741
2742 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002743 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002744 try {
2745 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2746 } catch (RemoteException e) {
2747 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2748 }
2749 }
2750
Paul Huddce5912023-08-01 10:26:49 +08002751 void onServiceInfoCallbackRegistered(int transactionId) {
2752 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2753 }
2754
2755 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2756 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002757 try {
2758 mCb.onServiceUpdated(listenerKey, info);
2759 } catch (RemoteException e) {
2760 Log.e(TAG, "Error calling onServiceUpdated", e);
2761 }
2762 }
2763
Paul Huddce5912023-08-01 10:26:49 +08002764 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2765 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002766 try {
2767 mCb.onServiceUpdatedLost(listenerKey);
2768 } catch (RemoteException e) {
2769 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2770 }
2771 }
2772
Paul Huddce5912023-08-01 10:26:49 +08002773 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2774 mMetrics.reportServiceInfoCallbackUnregistered(
2775 request.mTransactionId,
2776 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2777 request.getFoundServiceCount(),
2778 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002779 request.isServiceFromCache(),
2780 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002781 try {
2782 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2783 } catch (RemoteException e) {
2784 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2785 }
2786 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002787 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002788}