blob: 468d7bd76f543acad8903d539509380fe28200a4 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yuyang Huang33fa4d22023-02-14 22:59:37 +090019import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090020import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090022import static android.net.NetworkCapabilities.TRANSPORT_VPN;
23import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090024import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080025import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080026import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090027import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090028import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090030import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080031import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
32import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090033import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000034import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090035
Paul Hu23fa2022023-01-13 22:57:24 +080036import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080037import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090038import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090039import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080040import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070041import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090042import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090043import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080044import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090045import android.net.LinkProperties;
46import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080047import android.net.mdns.aidl.DiscoveryInfo;
48import android.net.mdns.aidl.GetAddressInfo;
49import android.net.mdns.aidl.IMDnsEventListener;
50import android.net.mdns.aidl.RegistrationInfo;
51import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.net.nsd.INsdManagerCallback;
54import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090055import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080056import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080058import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090059import android.net.nsd.OffloadEngine;
60import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090061import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000062import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090063import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090064import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080065import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090066import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080067import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070068import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090069import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090070import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070071import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090072import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080073import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090075import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090076import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070077import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070078
paulhua262cc12019-08-12 16:25:11 +080079import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000080import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.util.State;
82import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000083import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090084import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090085import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080086import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090087import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080088import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000089import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080090import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090091import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090093import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090094import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080096import com.android.server.connectivity.mdns.MdnsSearchOptions;
97import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
98import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080099import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900100import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800101
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700102import java.io.FileDescriptor;
103import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900104import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700105import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900106import java.net.NetworkInterface;
107import java.net.SocketException;
108import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800109import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900110import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700111import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800112import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800113import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900114import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000115import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800116import java.util.regex.Matcher;
117import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700118
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700119/**
120 * Network Service Discovery Service handles remote service discovery operation requests by
121 * implementing the INsdManager interface.
122 *
123 * @hide
124 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900125@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700126public class NsdService extends INsdManager.Stub {
127 private static final String TAG = "NsdService";
128 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900129 /**
130 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
131 * implementation.
132 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800133 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800134 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700135
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900136 /**
137 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
138 * implementation.
139 */
140 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
141
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900142 /**
143 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
144 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
145 *
146 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
147 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
148 *
149 * In which case the flags:
150 * "mdns_discovery_manager_allowlist_mytype_version",
151 * "mdns_advertiser_allowlist_mytype_version",
152 * "mdns_discovery_manager_allowlist_othertype_version",
153 * "mdns_advertiser_allowlist_othertype_version"
154 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
155 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900156 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900157 *
158 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
159 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
160 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
161 */
162 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
163
164 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
165 "mdns_discovery_manager_allowlist_";
166 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
167 "mdns_advertiser_allowlist_";
168 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
169
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900170 @VisibleForTesting
171 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
172 "mdns_config_running_app_active_importance_cutoff";
173 @VisibleForTesting
174 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
175 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
176 private final int mRunningAppActiveImportanceCutoff;
177
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900178 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000179 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900180 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000181 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
182 @VisibleForTesting
183 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800184 private static final int NO_SENT_QUERY_COUNT = 0;
185 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800186 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700187
Hugo Benichi32be63d2017-04-05 14:06:11 +0900188 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900189 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800190 private final MDnsManager mMDnsManager;
191 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900192 @NonNull
193 private final Dependencies mDeps;
194 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800195 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900196 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800197 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900198 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800199 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900200 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900201 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000202 @NonNull
203 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800204 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800205 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800206 // state machine thread. If change this outside state machine, it will need to introduce
207 // synchronization.
208 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800209 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700210
211 /**
212 * Clients receiving asynchronous messages
213 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900214 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700215
Paul Hud44e1b72023-06-16 02:07:42 +0000216 /* A map from transaction(unique) id to client info */
217 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700218
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900219 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
220 @Nullable
221 private WifiManager.MulticastLock mHeldMulticastLock;
222 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
223 // (non-null), value is the requested Network (nullable)
224 @NonNull
225 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
226 @NonNull
227 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
228
Luke Huang05298582021-06-13 16:52:05 +0000229 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700230
Hugo Benichi32be63d2017-04-05 14:06:11 +0900231 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700232 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800233 // The count of the connected legacy clients.
234 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000235 // The number of client that ever connected.
236 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700237
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900238 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
239 new RemoteCallbackList<>();
240
241 private static class OffloadEngineInfo {
242 @NonNull final String mInterfaceName;
243 final long mOffloadCapabilities;
244 final long mOffloadType;
245 @NonNull final IOffloadEngine mOffloadEngine;
246
247 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
248 @NonNull String interfaceName, long capabilities, long offloadType) {
249 this.mOffloadEngine = offloadEngine;
250 this.mInterfaceName = interfaceName;
251 this.mOffloadCapabilities = capabilities;
252 this.mOffloadType = offloadType;
253 }
254 }
255
Paul Hu812e9212023-06-20 06:24:53 +0000256 @VisibleForTesting
257 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000258 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800259 protected final int mTransactionId;
260 @NonNull
261 protected final NsdServiceInfo mReqServiceInfo;
262 @NonNull
263 protected final String mListenedServiceType;
264
Paul Hud44e1b72023-06-16 02:07:42 +0000265 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800266 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000267 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800268 mTransactionId = transactionId;
269 mReqServiceInfo = reqServiceInfo;
270 mListenedServiceType = listenedServiceType;
271 }
272
273 @NonNull
274 public String getListenedServiceType() {
275 return mListenedServiceType;
276 }
277
278 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000279 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
280 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800281
282 @Override
283 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
284
285 @Override
286 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
287
288 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000289 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
290 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800291
292 @Override
293 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
294
295 @Override
296 public void onSearchStoppedWithError(int error) { }
297
298 @Override
299 public void onSearchFailedToStart() { }
300
301 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800302 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
303 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800304
305 @Override
306 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
307 }
308
309 private class DiscoveryListener extends MdnsListener {
310
Paul Hud44e1b72023-06-16 02:07:42 +0000311 DiscoveryListener(int clientRequestId, int transactionId,
312 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
313 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800314 }
315
316 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000317 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
318 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800319 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
320 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000321 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800322 }
323
324 @Override
325 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800326 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
327 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000328 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800329 }
Paul Hubad6fe92023-07-24 21:25:22 +0800330
331 @Override
332 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
333 int sentQueryTransactionId) {
334 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
335 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
336 }
Paul Hu23fa2022023-01-13 22:57:24 +0800337 }
338
Paul Hu75069ed2023-01-14 00:31:09 +0800339 private class ResolutionListener extends MdnsListener {
340
Paul Hud44e1b72023-06-16 02:07:42 +0000341 ResolutionListener(int clientRequestId, int transactionId,
342 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
343 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800344 }
345
346 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000347 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800348 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
349 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000350 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800351 }
Paul Hubad6fe92023-07-24 21:25:22 +0800352
353 @Override
354 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
355 int sentQueryTransactionId) {
356 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
357 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
358 }
Paul Hu75069ed2023-01-14 00:31:09 +0800359 }
360
Paul Hu30bd70d2023-02-07 13:20:56 +0000361 private class ServiceInfoListener extends MdnsListener {
362
Paul Hud44e1b72023-06-16 02:07:42 +0000363 ServiceInfoListener(int clientRequestId, int transactionId,
364 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
365 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000366 }
367
368 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000369 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
370 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000371 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
372 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000373 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000374 }
375
376 @Override
377 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
378 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
379 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000380 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000381 }
382
383 @Override
384 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
385 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
386 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000387 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000388 }
Paul Hubad6fe92023-07-24 21:25:22 +0800389
390 @Override
391 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
392 int sentQueryTransactionId) {
393 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
394 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
395 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000396 }
397
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900398 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
399 @Override
400 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
401 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
402 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
403 // filtering on such interfaces, so taking the multicast lock is not necessary to
404 // disable APF filtering of multicast.
405 if (socketNetwork == null
406 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
407 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
408 return;
409 }
410
411 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
412 updateMulticastLock();
413 }
414 }
415
416 @Override
417 public void onSocketDestroyed(@Nullable Network socketNetwork,
418 @NonNull MdnsInterfaceSocket socket) {
419 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
420 updateMulticastLock();
421 }
422 }
423 }
424
425 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
426 private final Handler mHandler;
427
428 private UidImportanceListener(Handler handler) {
429 mHandler = handler;
430 }
431
432 @Override
433 public void onUidImportance(int uid, int importance) {
434 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
435 }
436 }
437
438 private void handleUidImportanceChanged(int uid, int importance) {
439 // Lower importance values are more "important"
440 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
441 ? mRunningAppActiveUids.add(uid)
442 : mRunningAppActiveUids.remove(uid);
443 if (modified) {
444 updateMulticastLock();
445 }
446 }
447
448 /**
449 * Take or release the lock based on updated internal state.
450 *
451 * This determines whether the lock needs to be held based on
452 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
453 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
454 * updated.
455 */
456 private void updateMulticastLock() {
457 final int needsLockUid = getMulticastLockNeededUid();
458 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
459 final WifiManager wm = mContext.getSystemService(WifiManager.class);
460 if (wm == null) {
461 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
462 return;
463 }
464 mHeldMulticastLock = wm.createMulticastLock(TAG);
465 mHeldMulticastLock.acquire();
466 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
467 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
468 mHeldMulticastLock.release();
469 mHeldMulticastLock = null;
470 mServiceLogs.log("Released multicast lock");
471 }
472 }
473
474 /**
475 * @return The UID of an app requiring the multicast lock, or -1 if none.
476 */
477 private int getMulticastLockNeededUid() {
478 if (mWifiLockRequiredNetworks.size() == 0) {
479 // Return early if NSD is not active, or not on any relevant network
480 return -1;
481 }
Paul Hud44e1b72023-06-16 02:07:42 +0000482 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
483 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900484 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
485 // Ignore non-active UIDs
486 continue;
487 }
488
489 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
490 return clientInfo.mUid;
491 }
492 }
493 return -1;
494 }
495
Paul Hu019621e2023-01-13 23:26:49 +0800496 /**
497 * Data class of mdns service callback information.
498 */
499 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000500 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800501 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800502 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000503 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800504
Paul Hubad6fe92023-07-24 21:25:22 +0800505 MdnsEvent(int clientRequestId) {
506 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
507 }
508
509 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000510 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
511 }
512
Paul Hubad6fe92023-07-24 21:25:22 +0800513 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000514 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000515 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800516 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000517 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800518 }
519 }
520
Irfan Sheriff75006652012-04-17 23:15:29 -0700521 private class NsdStateMachine extends StateMachine {
522
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700523 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700524 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700525
526 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700527 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900528 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700529 }
530
Luke Huang92860f92021-06-23 06:29:30 +0000531 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800532 if (mIsDaemonStarted) {
533 if (DBG) Log.d(TAG, "Daemon is already started.");
534 return;
535 }
536 mMDnsManager.registerEventListener(mMDnsEventCallback);
537 mMDnsManager.startDaemon();
538 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000539 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000540 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000541 }
542
paulhu2b9ed952022-02-10 21:58:32 +0800543 private void maybeStopDaemon() {
544 if (!mIsDaemonStarted) {
545 if (DBG) Log.d(TAG, "Daemon has not been started.");
546 return;
547 }
548 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
549 mMDnsManager.stopDaemon();
550 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000551 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800552 }
553
Luke Huang92860f92021-06-23 06:29:30 +0000554 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000555 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000556 }
557
558 private void scheduleStop() {
559 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
560 }
561 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800562 // The native daemon should stay alive and can't be cleanup
563 // if any legacy client connected.
564 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000565 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000566 }
567 }
568
Luke Huang92860f92021-06-23 06:29:30 +0000569 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000570 this.removeMessages(NsdManager.DAEMON_CLEANUP);
571 }
572
Paul Hu23fa2022023-01-13 22:57:24 +0800573 private void maybeStartMonitoringSockets() {
574 if (mIsMonitoringSocketsStarted) {
575 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
576 return;
577 }
578
579 mMdnsSocketProvider.startMonitoringSockets();
580 mIsMonitoringSocketsStarted = true;
581 }
582
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900583 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
584 if (!mIsMonitoringSocketsStarted) return;
585 if (isAnyRequestActive()) return;
586
Paul Hu58f20602023-02-18 11:41:07 +0800587 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800588 mIsMonitoringSocketsStarted = false;
589 }
590
Hugo Benichi803a2f02017-04-24 11:35:06 +0900591 NsdStateMachine(String name, Handler handler) {
592 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700594 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800595 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900596 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700597 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 }
599
600 class DefaultState extends State {
601 @Override
602 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000604 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800607 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
608 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900609 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800610 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000611 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000612 final NetworkNsdReportedMetrics metrics =
613 mDeps.makeNetworkNsdReportedMetrics(
Paul Hu508a0122023-09-11 15:31:33 +0800614 (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900615 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000616 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800617 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900618 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000619 Log.w(TAG, "Client request id " + clientRequestId
620 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700621 }
622 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900623 case NsdManager.UNREGISTER_CLIENT:
624 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
625 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800626 if (cInfo != null) {
627 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900628 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800629 mLegacyClientCount -= 1;
630 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800631 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900632 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800633 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700634 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700635 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900636 cInfo = getClientInfoForReply(msg);
637 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800638 cInfo.onDiscoverServicesFailedImmediately(clientRequestId,
639 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900640 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700641 break;
642 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900643 cInfo = getClientInfoForReply(msg);
644 if (cInfo != null) {
645 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000646 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 break;
649 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900650 cInfo = getClientInfoForReply(msg);
651 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800652 cInfo.onRegisterServiceFailedImmediately(clientRequestId,
653 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700655 break;
656 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900657 cInfo = getClientInfoForReply(msg);
658 if (cInfo != null) {
659 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000660 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900661 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700662 break;
663 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900664 cInfo = getClientInfoForReply(msg);
665 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800666 cInfo.onResolveServiceFailedImmediately(clientRequestId,
667 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900668 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 break;
Paul Hub58deb72022-12-26 09:24:42 +0000670 case NsdManager.STOP_RESOLUTION:
671 cInfo = getClientInfoForReply(msg);
672 if (cInfo != null) {
673 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000674 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000675 }
676 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000677 case NsdManager.REGISTER_SERVICE_CALLBACK:
678 cInfo = getClientInfoForReply(msg);
679 if (cInfo != null) {
680 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000681 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000682 }
683 break;
Luke Huang05298582021-06-13 16:52:05 +0000684 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800685 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000686 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800687 // This event should be only sent by the legacy (target SDK < S) clients.
688 // Mark the sending client as legacy.
689 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900690 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800691 if (cInfo != null) {
692 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900693 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800694 mLegacyClientCount += 1;
695 maybeStartDaemon();
696 }
697 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700698 default:
paulhub2225702021-11-17 09:35:33 +0800699 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700700 return NOT_HANDLED;
701 }
702 return HANDLED;
703 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900704
705 private ClientInfo getClientInfoForReply(Message msg) {
706 final ListenerArgs args = (ListenerArgs) msg.obj;
707 return mClients.get(args.connector);
708 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700709 }
710
Irfan Sheriff75006652012-04-17 23:15:29 -0700711 class EnabledState extends State {
712 @Override
713 public void enter() {
714 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700715 }
716
717 @Override
718 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000719 // TODO: it is incorrect to stop the daemon without expunging all requests
720 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000721 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700722 }
723
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700724 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900725 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800726 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700727 return true;
728 }
729 return false;
730 }
731
Paul Hu508a0122023-09-11 15:31:33 +0800732 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000733 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800734 final LegacyClientRequest request =
735 new LegacyClientRequest(transactionId, what, startTimeMs);
736 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000737 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000738 // Remove the cleanup event because here comes a new request.
739 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800740 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700741 }
742
Paul Hud44e1b72023-06-16 02:07:42 +0000743 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900744 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000745 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000746 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000747 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900748 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800749 }
750
Paul Hud44e1b72023-06-16 02:07:42 +0000751 private void removeRequestMap(
752 int clientRequestId, int transactionId, ClientInfo clientInfo) {
753 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900754 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000755 clientInfo.mClientRequests.remove(clientRequestId);
756 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900757
758 if (existing instanceof LegacyClientRequest) {
759 maybeScheduleStop();
760 } else {
761 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900762 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900763 }
764 }
765
Paul Hu508a0122023-09-11 15:31:33 +0800766 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
767 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900768 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800769 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
770 listener, requestedNetwork, mClock.elapsedRealtime());
771 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000772 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900773 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800774 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800775 }
776
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900777 /**
778 * Truncate a service name to up to 63 UTF-8 bytes.
779 *
780 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
781 * names used in registerService follows historical behavior (see mdnsresponder
782 * handle_regservice_request).
783 */
784 @NonNull
785 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900786 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800787 }
788
Paul Hud44e1b72023-06-16 02:07:42 +0000789 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
790 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800791 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000792 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800793 }
794
Irfan Sheriff75006652012-04-17 23:15:29 -0700795 @Override
796 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900797 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000798 final int transactionId;
799 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900800 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900801 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700802 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800803 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800804 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900805 args = (ListenerArgs) msg.obj;
806 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000807 // If the binder death notification for a INsdManagerCallback was received
808 // before any calls are received by NsdService, the clientInfo would be
809 // cleared and cause NPE. Add a null check here to prevent this corner case.
810 if (clientInfo == null) {
811 Log.e(TAG, "Unknown connector in discovery");
812 break;
813 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700814
815 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800816 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
817 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700818 break;
819 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700820
Paul Hu23fa2022023-01-13 22:57:24 +0800821 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000822 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900823 final Pair<String, String> typeAndSubtype =
824 parseTypeAndSubtype(info.getServiceType());
825 final String serviceType = typeAndSubtype == null
826 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800827 if (clientInfo.mUseJavaBackend
828 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900829 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800830 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800831 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
832 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800833 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700834 }
Paul Hu23fa2022023-01-13 22:57:24 +0800835
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900836 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800837 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000838 final MdnsListener listener = new DiscoveryListener(clientRequestId,
839 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900840 final MdnsSearchOptions.Builder optionsBuilder =
841 MdnsSearchOptions.newBuilder()
842 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900843 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900844 .setIsPassiveMode(true);
845 if (typeAndSubtype.second != null) {
846 // The parsing ensures subtype starts with an underscore.
847 // MdnsSearchOptions expects the underscore to not be present.
848 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
849 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900850 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900851 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800852 final ClientRequest request = storeDiscoveryManagerRequestMap(
853 clientRequestId, transactionId, listener, clientInfo,
854 info.getNetwork());
855 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000856 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000857 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700858 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800859 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000860 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800861 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000862 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800863 + info.getServiceType());
864 }
Paul Hu508a0122023-09-11 15:31:33 +0800865 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
866 transactionId, clientInfo, msg.what,
867 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000868 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800869 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800870 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000871 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800872 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
873 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800874 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700875 }
876 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800877 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900878 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800879 if (DBG) Log.d(TAG, "Stop service discovery");
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.
885 if (clientInfo == null) {
886 Log.e(TAG, "Unknown connector in stop discovery");
887 break;
888 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700889
Paul Hud44e1b72023-06-16 02:07:42 +0000890 final ClientRequest request =
891 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900892 if (request == null) {
893 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700894 break;
895 }
Paul Hud44e1b72023-06-16 02:07:42 +0000896 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900897 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
898 // point, so this needs to check the type of the original request to
899 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900900 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000901 stopDiscoveryManagerRequest(
902 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000903 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000904 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700905 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000906 removeRequestMap(clientRequestId, transactionId, clientInfo);
907 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000908 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800909 } else {
910 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000911 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800912 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700913 }
914 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900915 }
916 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800917 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900918 args = (ListenerArgs) msg.obj;
919 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000920 // If the binder death notification for a INsdManagerCallback was received
921 // before any calls are received by NsdService, the clientInfo would be
922 // cleared and cause NPE. Add a null check here to prevent this corner case.
923 if (clientInfo == null) {
924 Log.e(TAG, "Unknown connector in registration");
925 break;
926 }
927
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700928 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800929 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
930 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700931 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700932 }
933
Paul Hud44e1b72023-06-16 02:07:42 +0000934 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900935 final NsdServiceInfo serviceInfo = args.serviceInfo;
936 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900937 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
938 final String registerServiceType = typeSubtype == null
939 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800940 if (clientInfo.mUseJavaBackend
941 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900942 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900943 if (registerServiceType == null) {
944 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800945 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
946 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900947 break;
948 }
949 serviceInfo.setServiceType(registerServiceType);
950 serviceInfo.setServiceName(truncateServiceName(
951 serviceInfo.getServiceName()));
952
953 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900954 // TODO: pass in the subtype as well. Including the subtype in the
955 // service type would generate service instance names like
956 // Name._subtype._sub._type._tcp, which is incorrect
957 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000958 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
959 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900960 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700961 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900962 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000963 if (registerService(transactionId, serviceInfo)) {
964 if (DBG) {
965 Log.d(TAG, "Register " + clientRequestId
966 + " " + transactionId);
967 }
Paul Hua6bc4632023-06-26 01:18:29 +0000968 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
969 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900970 // Return success after mDns reports success
971 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000972 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800973 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
974 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900975 }
976
Irfan Sheriff75006652012-04-17 23:15:29 -0700977 }
978 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900979 }
980 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800981 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900982 args = (ListenerArgs) msg.obj;
983 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000984 // If the binder death notification for a INsdManagerCallback was received
985 // before any calls are received by NsdService, the clientInfo would be
986 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900987 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800988 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700989 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700990 }
Paul Hud44e1b72023-06-16 02:07:42 +0000991 final ClientRequest request =
992 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900993 if (request == null) {
994 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
995 break;
996 }
Paul Hud44e1b72023-06-16 02:07:42 +0000997 transactionId = request.mTransactionId;
998 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900999
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001000 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
1001 // so this needs to check the type of the original request to unregister
1002 // instead of looking at the flag value.
1003 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001004 final AdvertiserMetrics metrics =
1005 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001006 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001007 clientInfo.onUnregisterServiceSucceeded(
1008 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001009 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001010 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001011 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001012 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1013 NO_PACKET /* sentPacketCount */,
1014 0 /* conflictDuringProbingCount */,
1015 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001016 } else {
1017 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001018 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001019 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001020 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001021 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001022 }
Paul Hu75069ed2023-01-14 00:31:09 +08001023 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001024 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001025 args = (ListenerArgs) msg.obj;
1026 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001027 // If the binder death notification for a INsdManagerCallback was received
1028 // before any calls are received by NsdService, the clientInfo would be
1029 // cleared and cause NPE. Add a null check here to prevent this corner case.
1030 if (clientInfo == null) {
1031 Log.e(TAG, "Unknown connector in resolution");
1032 break;
1033 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001034
Paul Hu75069ed2023-01-14 00:31:09 +08001035 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001036 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001037 final Pair<String, String> typeSubtype =
1038 parseTypeAndSubtype(info.getServiceType());
1039 final String serviceType = typeSubtype == null
1040 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001041 if (clientInfo.mUseJavaBackend
1042 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001043 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001044 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001045 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1046 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001047 break;
1048 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001049 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001050
1051 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001052 final MdnsListener listener = new ResolutionListener(clientRequestId,
1053 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001054 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1055 .setNetwork(info.getNetwork())
1056 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001057 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001058 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001059 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001060 mMdnsDiscoveryManager.registerListener(
1061 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001062 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1063 listener, clientInfo, info.getNetwork());
1064 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001065 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001066 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001067 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001068 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1069 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001070 break;
1071 }
1072
1073 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001074 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001075 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001076 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1077 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001078 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001079 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1080 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001081 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001082 }
1083 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001084 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001085 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001086 if (DBG) Log.d(TAG, "Stop service resolution");
1087 args = (ListenerArgs) msg.obj;
1088 clientInfo = mClients.get(args.connector);
1089 // If the binder death notification for a INsdManagerCallback was received
1090 // before any calls are received by NsdService, the clientInfo would be
1091 // cleared and cause NPE. Add a null check here to prevent this corner case.
1092 if (clientInfo == null) {
1093 Log.e(TAG, "Unknown connector in stop resolution");
1094 break;
1095 }
1096
Paul Hud44e1b72023-06-16 02:07:42 +00001097 final ClientRequest request =
1098 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001099 if (request == null) {
1100 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1101 break;
1102 }
Paul Hud44e1b72023-06-16 02:07:42 +00001103 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001104 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1105 // point, so this needs to check the type of the original request to
1106 // unregister instead of looking at the flag value.
1107 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001108 stopDiscoveryManagerRequest(
1109 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001110 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001111 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001112 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001113 removeRequestMap(clientRequestId, transactionId, clientInfo);
1114 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001115 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001116 } else {
1117 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001118 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001119 }
1120 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001121 }
Paul Hub58deb72022-12-26 09:24:42 +00001122 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001123 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001124 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001125 if (DBG) Log.d(TAG, "Register a service callback");
1126 args = (ListenerArgs) msg.obj;
1127 clientInfo = mClients.get(args.connector);
1128 // If the binder death notification for a INsdManagerCallback was received
1129 // before any calls are received by NsdService, the clientInfo would be
1130 // cleared and cause NPE. Add a null check here to prevent this corner case.
1131 if (clientInfo == null) {
1132 Log.e(TAG, "Unknown connector in callback registration");
1133 break;
1134 }
1135
Paul Hu30bd70d2023-02-07 13:20:56 +00001136 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001137 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001138 final Pair<String, String> typeAndSubtype =
1139 parseTypeAndSubtype(info.getServiceType());
1140 final String serviceType = typeAndSubtype == null
1141 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001142 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001143 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001145 break;
1146 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001147 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001148
Paul Hu30bd70d2023-02-07 13:20:56 +00001149 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001150 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1151 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001152 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1153 .setNetwork(info.getNetwork())
1154 .setIsPassiveMode(true)
1155 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001156 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001157 .build();
1158 mMdnsDiscoveryManager.registerListener(
1159 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001160 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1161 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001162 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001163 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001164 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001165 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001166 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001167 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001168 if (DBG) Log.d(TAG, "Unregister a service callback");
1169 args = (ListenerArgs) msg.obj;
1170 clientInfo = mClients.get(args.connector);
1171 // If the binder death notification for a INsdManagerCallback was received
1172 // before any calls are received by NsdService, the clientInfo would be
1173 // cleared and cause NPE. Add a null check here to prevent this corner case.
1174 if (clientInfo == null) {
1175 Log.e(TAG, "Unknown connector in callback unregistration");
1176 break;
1177 }
1178
Paul Hud44e1b72023-06-16 02:07:42 +00001179 final ClientRequest request =
1180 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001181 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001182 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001183 break;
1184 }
Paul Hud44e1b72023-06-16 02:07:42 +00001185 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001186 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001187 stopDiscoveryManagerRequest(
1188 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001189 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001190 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001191 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001192 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001193 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001194 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001195 }
paulhu2b9ed952022-02-10 21:58:32 +08001196 case MDNS_SERVICE_EVENT:
1197 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001198 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001199 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001200 break;
Paul Hu019621e2023-01-13 23:26:49 +08001201 case MDNS_DISCOVERY_MANAGER_EVENT:
1202 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1203 return NOT_HANDLED;
1204 }
1205 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001206 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1207 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1208 // TODO: Limits the number of registrations created by a given class.
1209 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1210 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001211 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001212 break;
1213 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1214 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1215 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001216 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001217 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001218 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001219 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001220 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001221
Paul Hud44e1b72023-06-16 02:07:42 +00001222 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001223 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001224 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001225 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001226 Log.e(TAG, String.format(
1227 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001228 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001229 }
1230
1231 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001232 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1233 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001234 // This can happen because of race conditions. For example,
1235 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1236 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001237 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1238 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001239 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001240 }
Paul Hu812e9212023-06-20 06:24:53 +00001241 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1242 if (request == null) {
1243 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1244 return false;
1245 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001246 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001247 Log.d(TAG, String.format(
1248 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001249 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001250 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001251 case IMDnsEventListener.SERVICE_FOUND: {
1252 final DiscoveryInfo info = (DiscoveryInfo) obj;
1253 final String name = info.serviceName;
1254 final String type = info.registrationType;
1255 servInfo = new NsdServiceInfo(name, type);
1256 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001257 if (foundNetId == 0L) {
1258 // Ignore services that do not have a Network: they are not usable
1259 // by apps, as they would need privileged permissions to use
1260 // interfaces that do not have an associated Network.
1261 break;
1262 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001263 if (foundNetId == INetd.DUMMY_NET_ID) {
1264 // Ignore services on the dummy0 interface: they are only seen when
1265 // discovering locally advertised services, and are not reachable
1266 // through that interface.
1267 break;
1268 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001269 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001270
1271 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001272 break;
paulhu2b9ed952022-02-10 21:58:32 +08001273 }
1274 case IMDnsEventListener.SERVICE_LOST: {
1275 final DiscoveryInfo info = (DiscoveryInfo) obj;
1276 final String name = info.serviceName;
1277 final String type = info.registrationType;
1278 final int lostNetId = info.netId;
1279 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001280 // The network could be set to null (netId 0) if it was torn down when the
1281 // service is lost
1282 // TODO: avoid returning null in that case, possibly by remembering
1283 // found services on the same interface index and their network at the time
1284 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001285 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001286 break;
paulhu2b9ed952022-02-10 21:58:32 +08001287 }
1288 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001289 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001290 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1291 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001292 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001293 break;
paulhu2b9ed952022-02-10 21:58:32 +08001294 case IMDnsEventListener.SERVICE_REGISTERED: {
1295 final RegistrationInfo info = (RegistrationInfo) obj;
1296 final String name = info.serviceName;
1297 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001298 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001299 break;
paulhu2b9ed952022-02-10 21:58:32 +08001300 }
1301 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001302 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001303 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1304 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001305 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001306 break;
paulhu2b9ed952022-02-10 21:58:32 +08001307 case IMDnsEventListener.SERVICE_RESOLVED: {
1308 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001309 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001310 final String fullName = info.serviceFullName;
1311 while (index < fullName.length() && fullName.charAt(index) != '.') {
1312 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001313 ++index;
1314 }
1315 ++index;
1316 }
paulhu2b9ed952022-02-10 21:58:32 +08001317 if (index >= fullName.length()) {
1318 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001319 break;
1320 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001321
paulhube186602022-04-12 07:18:23 +00001322 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001323 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001324 String type = rest.replace(".local.", "");
1325
Paul Hu30bd70d2023-02-07 13:20:56 +00001326 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001327 serviceInfo.setServiceName(name);
1328 serviceInfo.setServiceType(type);
1329 serviceInfo.setPort(info.port);
1330 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001331 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001332
Paul Hud44e1b72023-06-16 02:07:42 +00001333 stopResolveService(transactionId);
1334 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001335
Paul Hud44e1b72023-06-16 02:07:42 +00001336 final int transactionId2 = getUniqueId();
1337 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1338 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001339 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001340 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001341 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001342 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1343 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001344 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001345 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001346 }
1347 break;
paulhu2b9ed952022-02-10 21:58:32 +08001348 }
1349 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001350 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001351 stopResolveService(transactionId);
1352 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001353 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001354 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1355 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001356 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001357 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001358 break;
paulhu2b9ed952022-02-10 21:58:32 +08001359 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001360 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001361 stopGetAddrInfo(transactionId);
1362 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001363 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001364 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1365 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001366 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001367 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001368 break;
paulhu2b9ed952022-02-10 21:58:32 +08001369 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001370 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001371 final GetAddressInfo info = (GetAddressInfo) obj;
1372 final String address = info.address;
1373 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001374 InetAddress serviceHost = null;
1375 try {
paulhu2b9ed952022-02-10 21:58:32 +08001376 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001377 } catch (UnknownHostException e) {
1378 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1379 }
1380
1381 // If the resolved service is on an interface without a network, consider it
1382 // as a failure: it would not be usable by apps as they would need
1383 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001384 if (netId != NETID_UNSET && serviceHost != null) {
1385 clientInfo.mResolvedService.setHost(serviceHost);
1386 setServiceNetworkForCallback(clientInfo.mResolvedService,
1387 netId, info.interfaceIdx);
1388 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001389 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001390 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001391 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001392 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1393 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001394 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001395 }
Paul Hud44e1b72023-06-16 02:07:42 +00001396 stopGetAddrInfo(transactionId);
1397 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001398 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001399 break;
paulhu2b9ed952022-02-10 21:58:32 +08001400 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001401 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001402 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001403 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001404 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001405 }
Paul Hu019621e2023-01-13 23:26:49 +08001406
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001407 @Nullable
1408 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1409 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001410 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001411 final String[] typeArray = serviceInfo.getServiceType();
1412 final String joinedType;
1413 if (typeArray.length == 0
1414 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1415 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1416 + Arrays.toString(typeArray));
1417 return null;
1418 } else {
1419 joinedType = TextUtils.join(".",
1420 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1421 }
1422 final String serviceType;
1423 switch (code) {
1424 case NsdManager.SERVICE_FOUND:
1425 case NsdManager.SERVICE_LOST:
1426 // For consistency with historical behavior, discovered service types have
1427 // a dot at the end.
1428 serviceType = joinedType + ".";
1429 break;
1430 case RESOLVE_SERVICE_SUCCEEDED:
1431 // For consistency with historical behavior, resolved service types have
1432 // a dot at the beginning.
1433 serviceType = "." + joinedType;
1434 break;
1435 default:
1436 serviceType = joinedType;
1437 break;
1438 }
Paul Hu019621e2023-01-13 23:26:49 +08001439 final String serviceName = serviceInfo.getServiceInstanceName();
1440 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1441 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001442 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1443 // network for Tethering interface. In other words, the network == null means the
1444 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001445 setServiceNetworkForCallback(
1446 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001447 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001448 serviceInfo.getInterfaceIndex());
1449 return servInfo;
1450 }
1451
1452 private boolean handleMdnsDiscoveryManagerEvent(
1453 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001454 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001455 if (clientInfo == null) {
1456 Log.e(TAG, String.format(
1457 "id %d for %d has no client mapping", transactionId, code));
1458 return false;
1459 }
1460
1461 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001462 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001463 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1464 if (request == null) {
1465 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1466 return false;
1467 }
1468
1469 // Deal with the discovery sent callback
1470 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1471 request.onQuerySent();
1472 return true;
1473 }
1474
1475 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001476 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1477 // Errors are already logged if null
1478 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001479 mServiceLogs.log(String.format(
1480 "MdnsDiscoveryManager event code=%s transactionId=%d",
1481 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001482 switch (code) {
1483 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001484 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001485 break;
1486 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001487 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001488 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001489 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1490 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001491 info.setPort(serviceInfo.getPort());
1492
1493 Map<String, String> attrs = serviceInfo.getAttributes();
1494 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1495 final String key = kv.getKey();
1496 try {
1497 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1498 } catch (IllegalArgumentException e) {
1499 Log.e(TAG, "Invalid attribute", e);
1500 }
1501 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001502 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001503 if (addresses.size() != 0) {
1504 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001505 request.setServiceFromCache(event.mIsServiceFromCache);
1506 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001507 } else {
1508 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001509 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001510 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1511 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001512 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001513 }
1514
1515 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001516 if (!(request instanceof DiscoveryManagerRequest)) {
1517 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1518 break;
1519 }
Paul Hud44e1b72023-06-16 02:07:42 +00001520 stopDiscoveryManagerRequest(
1521 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001522 break;
1523 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001524 case NsdManager.SERVICE_UPDATED: {
1525 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1526 info.setPort(serviceInfo.getPort());
1527
1528 Map<String, String> attrs = serviceInfo.getAttributes();
1529 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1530 final String key = kv.getKey();
1531 try {
1532 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1533 } catch (IllegalArgumentException e) {
1534 Log.e(TAG, "Invalid attribute", e);
1535 }
1536 }
1537
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001538 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001539 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001540 clientInfo.onServiceUpdated(clientRequestId, info, request);
1541 // Set the ServiceFromCache flag only if the service is actually being
1542 // retrieved from the cache. This flag should not be overridden by later
1543 // service updates, which may not be cached.
1544 if (event.mIsServiceFromCache) {
1545 request.setServiceFromCache(true);
1546 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001547 break;
1548 }
1549 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001550 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001551 break;
Paul Hu019621e2023-01-13 23:26:49 +08001552 default:
1553 return false;
1554 }
1555 return true;
1556 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001557 }
1558 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001559
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001560 @NonNull
1561 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1562 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1563 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1564 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1565 for (String ipv4Address : v4Addrs) {
1566 try {
1567 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1568 } catch (IllegalArgumentException e) {
1569 Log.wtf(TAG, "Invalid ipv4 address", e);
1570 }
1571 }
1572 for (String ipv6Address : v6Addrs) {
1573 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001574 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1575 ipv6Address);
1576 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1577 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001578 Log.wtf(TAG, "Invalid ipv6 address", e);
1579 }
1580 }
1581 return addresses;
1582 }
1583
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001584 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1585 switch (netId) {
1586 case NETID_UNSET:
1587 info.setNetwork(null);
1588 break;
1589 case INetd.LOCAL_NET_ID:
1590 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1591 // visible / usable for apps, so do not return it. Store the interface
1592 // index instead, so at least if the client tries to resolve the service
1593 // with that NsdServiceInfo, it will be done on the same interface.
1594 // If they recreate the NsdServiceInfo themselves, resolution would be
1595 // done on all interfaces as before T, which should also work.
1596 info.setNetwork(null);
1597 info.setInterfaceIndex(ifaceIdx);
1598 break;
1599 default:
1600 info.setNetwork(new Network(netId));
1601 }
1602 }
1603
paulhube186602022-04-12 07:18:23 +00001604 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1605 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1606 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1607 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1608 private String unescape(String s) {
1609 StringBuilder sb = new StringBuilder(s.length());
1610 for (int i = 0; i < s.length(); ++i) {
1611 char c = s.charAt(i);
1612 if (c == '\\') {
1613 if (++i >= s.length()) {
1614 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1615 break;
1616 }
1617 c = s.charAt(i);
1618 if (c != '.' && c != '\\') {
1619 if (i + 2 >= s.length()) {
1620 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1621 break;
1622 }
1623 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1624 + (s.charAt(i + 2) - '0'));
1625 i += 2;
1626 }
1627 }
1628 sb.append(c);
1629 }
1630 return sb.toString();
1631 }
1632
Paul Hu7445e3d2023-03-03 15:14:00 +08001633 /**
1634 * Check the given service type is valid and construct it to a service type
1635 * which can use for discovery / resolution service.
1636 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001637 * <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 +08001638 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1639 * underscore; they are alphanumerical characters or dashes or underscore, except the
1640 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1641 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001642 * <p>The subtype may also be specified with a comma after the service type, for example
1643 * _type._tcp,_subtype.
1644 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001645 * @param serviceType the request service type for discovery / resolution service
1646 * @return constructed service type or null if the given service type is invalid.
1647 */
1648 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001649 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001650 if (TextUtils.isEmpty(serviceType)) return null;
1651
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001652 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001653 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001654 // Optional leading subtype (_subtype._type._tcp)
1655 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1656 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1657 // Actual type (_type._tcp.local)
1658 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001659 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001660 // e.g. allow "_type._tcp.local."
1661 + "\\.?"
1662 // Optional subtype after comma, for "_type._tcp,_subtype" format
1663 + "(?:,(" + typeOrSubtypePattern + "))?"
1664 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001665 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1666 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001667 // Use the subtype either at the beginning or after the comma
1668 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1669 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001670 }
1671
Hugo Benichi803a2f02017-04-24 11:35:06 +09001672 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001673 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001674 this(ctx, handler, cleanupDelayMs, new Dependencies());
1675 }
1676
1677 @VisibleForTesting
1678 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001679 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001680 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001681 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001682 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001683 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1684 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001685 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001686
Paul Hu14667de2023-04-17 22:42:47 +08001687 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001688 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001689 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001690 // address events are received. When the netlink monitor starts, any IP addresses already
1691 // on the interfaces will not be seen. In practice, the network will not connect at boot
1692 // time As a result, all the netlink message should be observed if the netlink monitor
1693 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001694 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001695
1696 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1697 // startBootstrapServices).
1698 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1699 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1700 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1701 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1702 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1703 mRunningAppActiveImportanceCutoff);
1704
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001705 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001706 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1707 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001708 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001709 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001710 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
Yuyang Huangb96a0712023-09-07 15:13:15 +09001711 MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder().setIsMdnsOffloadFeatureEnabled(
1712 mDeps.isTetheringFeatureNotChickenedOut(
1713 MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD)).build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001714 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001715 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001716 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001717 }
1718
1719 /**
1720 * Dependencies of NsdService, for injection in tests.
1721 */
1722 @VisibleForTesting
1723 public static class Dependencies {
1724 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001725 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001726 *
1727 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001728 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001729 */
1730 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001731 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001732 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001733 }
1734
1735 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001736 * Check whether the MdnsAdvertiser feature is enabled.
1737 *
1738 * @param context The global context information about an app environment.
1739 * @return true if the MdnsAdvertiser feature is enabled.
1740 */
1741 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001742 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001743 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001744 }
1745
1746 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001747 * Get the type allowlist flag value.
1748 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1749 */
1750 @Nullable
1751 public String getTypeAllowlistFlags() {
1752 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1753 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1754 }
1755
1756 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001757 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001758 */
1759 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001760 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001761 }
1762
1763 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001764 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1765 */
1766 public boolean isTetheringFeatureNotChickenedOut(String feature) {
1767 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(feature);
1768 }
1769
1770 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001771 * @see MdnsDiscoveryManager
1772 */
1773 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001774 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001775 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1776 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001777 }
1778
1779 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001780 * @see MdnsAdvertiser
1781 */
1782 public MdnsAdvertiser makeMdnsAdvertiser(
1783 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001784 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1785 MdnsFeatureFlags featureFlags) {
1786 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001787 }
1788
1789 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001790 * @see MdnsSocketProvider
1791 */
Paul Hu14667de2023-04-17 22:42:47 +08001792 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001793 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1794 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1795 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1796 }
1797
1798 /**
1799 * @see DeviceConfig#getInt(String, String, int)
1800 */
1801 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1802 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1803 }
1804
1805 /**
1806 * @see Binder#getCallingUid()
1807 */
1808 public int getCallingUid() {
1809 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001810 }
Paul Hu777ed052023-06-19 13:35:15 +00001811
1812 /**
1813 * @see NetworkNsdReportedMetrics
1814 */
Paul Hu508a0122023-09-11 15:31:33 +08001815 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1816 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001817 }
1818
1819 /**
1820 * @see MdnsUtils.Clock
1821 */
1822 public Clock makeClock() {
1823 return new Clock();
1824 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001825 }
1826
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001827 /**
1828 * Return whether a type is allowlisted to use the Java backend.
1829 * @param type The service type
1830 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1831 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1832 */
1833 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1834 @NonNull String flagPrefix) {
1835 if (type == null) return false;
1836 final String typesConfig = mDeps.getTypeAllowlistFlags();
1837 if (TextUtils.isEmpty(typesConfig)) return false;
1838
1839 final String mappingPrefix = type + ":";
1840 String mappedFlag = null;
1841 for (String mapping : TextUtils.split(typesConfig, ",")) {
1842 if (mapping.startsWith(mappingPrefix)) {
1843 mappedFlag = mapping.substring(mappingPrefix.length());
1844 break;
1845 }
1846 }
1847
1848 if (mappedFlag == null) return false;
1849
1850 return mDeps.isFeatureEnabled(mContext,
1851 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1852 }
1853
1854 private boolean useDiscoveryManagerForType(@Nullable String type) {
1855 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1856 }
1857
1858 private boolean useAdvertiserForType(@Nullable String type) {
1859 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1860 }
1861
paulhu1b35e822022-04-08 14:48:41 +08001862 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001863 HandlerThread thread = new HandlerThread(TAG);
1864 thread.start();
1865 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001866 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001867 return service;
1868 }
1869
paulhu2b9ed952022-02-10 21:58:32 +08001870 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1871 private final StateMachine mStateMachine;
1872
1873 MDnsEventCallback(StateMachine sm) {
1874 mStateMachine = sm;
1875 }
1876
1877 @Override
1878 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1879 mStateMachine.sendMessage(
1880 MDNS_SERVICE_EVENT, status.result, status.id, status);
1881 }
1882
1883 @Override
1884 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1885 mStateMachine.sendMessage(
1886 MDNS_SERVICE_EVENT, status.result, status.id, status);
1887 }
1888
1889 @Override
1890 public void onServiceResolutionStatus(final ResolutionInfo status) {
1891 mStateMachine.sendMessage(
1892 MDNS_SERVICE_EVENT, status.result, status.id, status);
1893 }
1894
1895 @Override
1896 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1897 mStateMachine.sendMessage(
1898 MDNS_SERVICE_EVENT, status.result, status.id, status);
1899 }
1900
1901 @Override
1902 public int getInterfaceVersion() throws RemoteException {
1903 return this.VERSION;
1904 }
1905
1906 @Override
1907 public String getInterfaceHash() throws RemoteException {
1908 return this.HASH;
1909 }
1910 }
1911
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001912 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1913 final String targetInterface = offloadEngineInfo.mInterfaceName;
1914 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1915 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1916 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1917 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1918 try {
1919 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1920 } catch (RemoteException e) {
1921 // Can happen in regular cases, do not log a stacktrace
1922 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1923 }
1924 }
1925 }
1926
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001927 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1928 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1929 final int count = mOffloadEngines.beginBroadcast();
1930 try {
1931 for (int i = 0; i < count; i++) {
1932 final OffloadEngineInfo offloadEngineInfo =
1933 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1934 final String interfaceName = offloadEngineInfo.mInterfaceName;
1935 if (!targetInterfaceName.equals(interfaceName)
1936 || ((offloadEngineInfo.mOffloadType
1937 & offloadServiceInfo.getOffloadType()) == 0)) {
1938 continue;
1939 }
1940 try {
1941 if (isRemove) {
1942 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1943 offloadServiceInfo);
1944 } else {
1945 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1946 offloadServiceInfo);
1947 }
1948 } catch (RemoteException e) {
1949 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001950 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001951 }
1952 }
1953 } finally {
1954 mOffloadEngines.finishBroadcast();
1955 }
1956 }
1957
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001958 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001959 // TODO: add a callback to notify when a service is being added on each interface (as soon
1960 // as probing starts), and call mOffloadCallbacks. This callback is for
1961 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1962
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001963 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001964 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1965 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1966 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001967 if (clientInfo == null) return;
1968
Paul Hud44e1b72023-06-16 02:07:42 +00001969 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1970 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001971
1972 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1973 // historical behavior.
1974 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001975 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001976 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001977 }
1978
1979 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001980 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1981 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001982 if (clientInfo == null) return;
1983
Paul Hud44e1b72023-06-16 02:07:42 +00001984 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1985 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001986 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001987 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1988 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001989 }
1990
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001991 @Override
1992 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1993 @NonNull OffloadServiceInfo offloadServiceInfo) {
1994 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1995 }
1996
1997 @Override
1998 public void onOffloadStop(@NonNull String interfaceName,
1999 @NonNull OffloadServiceInfo offloadServiceInfo) {
2000 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2001 }
2002
Paul Hud44e1b72023-06-16 02:07:42 +00002003 private ClientInfo getClientInfoOrLog(int transactionId) {
2004 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002005 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002006 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002007 }
2008 return clientInfo;
2009 }
2010
Paul Hud44e1b72023-06-16 02:07:42 +00002011 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2012 final int clientRequestId = info.getClientRequestId(transactionId);
2013 if (clientRequestId < 0) {
2014 Log.e(TAG, String.format(
2015 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002016 }
Paul Hud44e1b72023-06-16 02:07:42 +00002017 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002018 }
2019 }
2020
Paul Hu2e0a88c2023-03-09 16:05:01 +08002021 private static class ConnectorArgs {
2022 @NonNull public final NsdServiceConnector connector;
2023 @NonNull public final INsdManagerCallback callback;
2024 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002025 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002026
2027 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002028 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002029 this.connector = connector;
2030 this.callback = callback;
2031 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002032 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002033 }
2034 }
2035
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002036 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002037 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002039 final int uid = mDeps.getCallingUid();
2040 if (cb == null) {
2041 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2042 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002043 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002044 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002045 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002046 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002047 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002048 }
2049
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002050 private static class ListenerArgs {
2051 public final NsdServiceConnector connector;
2052 public final NsdServiceInfo serviceInfo;
2053 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2054 this.connector = connector;
2055 this.serviceInfo = serviceInfo;
2056 }
2057 }
2058
2059 private class NsdServiceConnector extends INsdServiceConnector.Stub
2060 implements IBinder.DeathRecipient {
2061 @Override
2062 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2063 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2064 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2065 new ListenerArgs(this, serviceInfo)));
2066 }
2067
2068 @Override
2069 public void unregisterService(int listenerKey) {
2070 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2071 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2072 new ListenerArgs(this, null)));
2073 }
2074
2075 @Override
2076 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2077 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2078 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2079 new ListenerArgs(this, serviceInfo)));
2080 }
2081
2082 @Override
2083 public void stopDiscovery(int listenerKey) {
2084 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2085 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2086 }
2087
2088 @Override
2089 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2090 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2091 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2092 new ListenerArgs(this, serviceInfo)));
2093 }
2094
2095 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002096 public void stopResolution(int listenerKey) {
2097 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2098 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2099 }
2100
2101 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002102 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2103 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2104 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2105 new ListenerArgs(this, serviceInfo)));
2106 }
2107
2108 @Override
2109 public void unregisterServiceInfoCallback(int listenerKey) {
2110 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2111 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2112 new ListenerArgs(this, null)));
2113 }
2114
2115 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002116 public void startDaemon() {
2117 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2118 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2119 }
2120
2121 @Override
2122 public void binderDied() {
2123 mNsdStateMachine.sendMessage(
2124 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002125
2126 }
2127
2128 @Override
2129 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2130 @OffloadEngine.OffloadCapability long offloadCapabilities,
2131 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002132 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002133 Objects.requireNonNull(ifaceName);
2134 Objects.requireNonNull(cb);
2135 mNsdStateMachine.sendMessage(
2136 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2137 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2138 offloadTypes)));
2139 }
2140
2141 @Override
2142 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002143 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002144 Objects.requireNonNull(cb);
2145 mNsdStateMachine.sendMessage(
2146 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002147 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002148
2149 private static void checkOffloadEnginePermission(Context context) {
2150 if (!SdkLevel.isAtLeastT()) {
2151 throw new SecurityException("API is not available in before API level 33");
2152 }
2153 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2154 // be back ported to older builds: accept it as long as it's signature-protected
2155 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2156 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2157 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2158 return;
2159 }
2160 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2161 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2162 return;
2163 }
2164 throw new SecurityException("Requires one of the following permissions: "
2165 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2166 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2167 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002168 }
2169
Hugo Benichi912db992017-04-24 16:41:03 +09002170 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002171 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002172 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002173 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2174 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002175 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002176 }
2177
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002178 private int getUniqueId() {
2179 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2180 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002181 }
2182
Paul Hud44e1b72023-06-16 02:07:42 +00002183 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002184 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002185 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002186 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002187 String name = service.getServiceName();
2188 String type = service.getServiceType();
2189 int port = service.getPort();
2190 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002191 final int registerInterface = getNetworkInterfaceIndex(service);
2192 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002193 Log.e(TAG, "Interface to register service on not found");
2194 return false;
2195 }
Paul Hud44e1b72023-06-16 02:07:42 +00002196 return mMDnsManager.registerService(
2197 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002198 }
2199
Paul Hud44e1b72023-06-16 02:07:42 +00002200 private boolean unregisterService(int transactionId) {
2201 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002202 }
2203
Paul Hud44e1b72023-06-16 02:07:42 +00002204 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002205 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002206 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2207 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002208 Log.e(TAG, "Interface to discover service on not found");
2209 return false;
2210 }
Paul Hud44e1b72023-06-16 02:07:42 +00002211 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002212 }
2213
Paul Hud44e1b72023-06-16 02:07:42 +00002214 private boolean stopServiceDiscovery(int transactionId) {
2215 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002216 }
2217
Paul Hud44e1b72023-06-16 02:07:42 +00002218 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002219 final String name = service.getServiceName();
2220 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002221 final int resolveInterface = getNetworkInterfaceIndex(service);
2222 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002223 Log.e(TAG, "Interface to resolve service on not found");
2224 return false;
2225 }
Paul Hud44e1b72023-06-16 02:07:42 +00002226 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002227 }
2228
2229 /**
2230 * Guess the interface to use to resolve or discover a service on a specific network.
2231 *
2232 * This is an imperfect guess, as for example the network may be gone or not yet fully
2233 * registered. This is fine as failing is correct if the network is gone, and a client
2234 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2235 * this is to support the legacy mdnsresponder implementation, which historically resolved
2236 * services on an unspecified network.
2237 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002238 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2239 final Network network = serviceInfo.getNetwork();
2240 if (network == null) {
2241 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2242 // provided by NsdService from discovery results, and the service was found on an
2243 // interface that has no app-usable Network).
2244 if (serviceInfo.getInterfaceIndex() != 0) {
2245 return serviceInfo.getInterfaceIndex();
2246 }
2247 return IFACE_IDX_ANY;
2248 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002249
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002250 String interfaceName = getNetworkInterfaceName(network);
2251 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002252 return IFACE_IDX_ANY;
2253 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002254 return getNetworkInterfaceIndexByName(interfaceName);
2255 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002256
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002257 private String getNetworkInterfaceName(@Nullable Network network) {
2258 if (network == null) {
2259 return null;
2260 }
2261 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2262 if (cm == null) {
2263 Log.wtf(TAG, "No ConnectivityManager");
2264 return null;
2265 }
2266 final LinkProperties lp = cm.getLinkProperties(network);
2267 if (lp == null) {
2268 return null;
2269 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002270 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002271 return lp.getInterfaceName();
2272 }
2273
2274 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002275 final NetworkInterface iface;
2276 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002277 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002278 } catch (SocketException e) {
2279 Log.e(TAG, "Error querying interface", e);
2280 return IFACE_IDX_ANY;
2281 }
2282
2283 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002284 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002285 return IFACE_IDX_ANY;
2286 }
2287
2288 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002289 }
2290
Paul Hud44e1b72023-06-16 02:07:42 +00002291 private boolean stopResolveService(int transactionId) {
2292 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002293 }
2294
Paul Hud44e1b72023-06-16 02:07:42 +00002295 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2296 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002297 }
2298
Paul Hud44e1b72023-06-16 02:07:42 +00002299 private boolean stopGetAddrInfo(int transactionId) {
2300 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002301 }
2302
2303 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002304 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2305 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002306
Paul Hub2e67d32023-04-18 05:50:14 +00002307 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2308 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002309 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002310
2311 // Dump service and clients logs
2312 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002313 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002314 pw.increaseIndent();
2315 mServiceLogs.reverseDump(pw);
2316 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002317 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002318
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002319 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002320 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002321 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002322 private int mFoundServiceCount = 0;
2323 private int mLostServiceCount = 0;
2324 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002325 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002326 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002327
Paul Hu812e9212023-06-20 06:24:53 +00002328 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002329 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002330 mStartTimeMs = startTimeMs;
2331 }
2332
Paul Hu812e9212023-06-20 06:24:53 +00002333 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002334 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002335 }
Paul Hu812e9212023-06-20 06:24:53 +00002336
2337 public void onServiceFound(String serviceName) {
2338 mFoundServiceCount++;
2339 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2340 mServices.add(serviceName);
2341 }
2342 }
2343
2344 public void onServiceLost() {
2345 mLostServiceCount++;
2346 }
2347
2348 public int getFoundServiceCount() {
2349 return mFoundServiceCount;
2350 }
2351
2352 public int getLostServiceCount() {
2353 return mLostServiceCount;
2354 }
2355
2356 public int getServicesCount() {
2357 return mServices.size();
2358 }
Paul Hua6bc4632023-06-26 01:18:29 +00002359
2360 public void setServiceFromCache(boolean isServiceFromCache) {
2361 mIsServiceFromCache = isServiceFromCache;
2362 }
2363
2364 public boolean isServiceFromCache() {
2365 return mIsServiceFromCache;
2366 }
Paul Hubad6fe92023-07-24 21:25:22 +08002367
2368 public void onQuerySent() {
2369 mSentQueryCount++;
2370 }
2371
2372 public int getSentQueryCount() {
2373 return mSentQueryCount;
2374 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002375 }
2376
2377 private static class LegacyClientRequest extends ClientRequest {
2378 private final int mRequestCode;
2379
Paul Hu812e9212023-06-20 06:24:53 +00002380 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2381 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002382 mRequestCode = requestCode;
2383 }
2384 }
2385
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002386 private abstract static class JavaBackendClientRequest extends ClientRequest {
2387 @Nullable
2388 private final Network mRequestedNetwork;
2389
Paul Hu777ed052023-06-19 13:35:15 +00002390 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002391 long startTimeMs) {
2392 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002393 mRequestedNetwork = requestedNetwork;
2394 }
2395
2396 @Nullable
2397 public Network getRequestedNetwork() {
2398 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002399 }
2400 }
2401
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002402 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002403 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002404 long startTimeMs) {
2405 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002406 }
2407 }
2408
2409 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002410 @NonNull
2411 private final MdnsListener mListener;
2412
Paul Hud44e1b72023-06-16 02:07:42 +00002413 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002414 @Nullable Network requestedNetwork, long startTimeMs) {
2415 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002416 mListener = listener;
2417 }
2418 }
2419
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002420 /* Information tracked per client */
2421 private class ClientInfo {
2422
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002423 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002424 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002425 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002426 private NsdServiceInfo mResolvedService;
2427
Paul Hud44e1b72023-06-16 02:07:42 +00002428 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002429 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002430
Luke Huangf7277ed2021-07-12 21:15:10 +08002431 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002432 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002433 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002434 // The flag of using java backend if the client's target SDK >= U
2435 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002436 // Store client logs
2437 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002438 // Report the nsd metrics data
2439 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002440
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002441 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002442 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002443 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002444 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002445 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002446 mClientLogs = sharedLog;
2447 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002448 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002449 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002450
2451 @Override
2452 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002453 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002454 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002455 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002456 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2457 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002458 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002459 int clientRequestId = mClientRequests.keyAt(i);
2460 sb.append("clientRequestId ")
2461 .append(clientRequestId)
2462 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002463 .append(" type ").append(
2464 mClientRequests.valueAt(i).getClass().getSimpleName())
2465 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002466 }
2467 return sb.toString();
2468 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002469
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002470 private boolean isPreSClient() {
2471 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002472 }
2473
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002474 private void setPreSClient() {
2475 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002476 }
2477
Paul Hu812e9212023-06-20 06:24:53 +00002478 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002479 final MdnsListener listener =
2480 ((DiscoveryManagerRequest) request).mListener;
2481 mMdnsDiscoveryManager.unregisterListener(
2482 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002483 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002484 }
2485
Dave Plattfeff2af2014-03-07 14:48:22 -08002486 // Remove any pending requests from the global map when we get rid of a client,
2487 // and send cancellations to the daemon.
2488 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002489 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002490 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002491 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002492 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002493 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002494 final int transactionId = request.mTransactionId;
2495 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002496 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002497 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2498 + " transactionId " + transactionId
2499 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002500 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002501
2502 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002503 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2504 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002505 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002506 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2507 request.getFoundServiceCount(),
2508 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002509 request.getServicesCount(),
2510 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002511 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002512 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002513 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002514 } else if (listener instanceof ServiceInfoListener) {
2515 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2516 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2517 request.getFoundServiceCount(),
2518 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002519 request.isServiceFromCache(),
2520 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002521 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002522 continue;
2523 }
2524
2525 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002526 final AdvertiserMetrics metrics =
2527 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002528 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002529 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002530 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2531 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2532 metrics.mConflictDuringProbingCount,
2533 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002534 continue;
2535 }
2536
2537 if (!(request instanceof LegacyClientRequest)) {
2538 throw new IllegalStateException("Unknown request type: " + request.getClass());
2539 }
2540
2541 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002542 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002543 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002544 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002545 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2546 request.getFoundServiceCount(),
2547 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002548 request.getServicesCount(),
2549 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002550 break;
2551 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002552 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002553 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002554 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002555 break;
2556 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002557 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002558 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002559 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2560 NO_PACKET /* repliedRequestsCount */,
2561 NO_PACKET /* sentPacketCount */,
2562 0 /* conflictDuringProbingCount */,
2563 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002564 break;
2565 default:
2566 break;
2567 }
2568 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002569 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002570 updateMulticastLock();
2571 }
2572
2573 /**
2574 * Returns true if this client has any Java backend request that requests one of the given
2575 * networks.
2576 */
2577 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2578 for (int i = 0; i < mClientRequests.size(); i++) {
2579 final ClientRequest req = mClientRequests.valueAt(i);
2580 if (!(req instanceof JavaBackendClientRequest)) {
2581 continue;
2582 }
2583 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2584 .getRequestedNetwork();
2585 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2586 return true;
2587 }
2588 }
2589 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002590 }
2591
Paul Hud44e1b72023-06-16 02:07:42 +00002592 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2593 // transaction id, return the corresponding client request id.
2594 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002595 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002596 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002597 return mClientRequests.keyAt(i);
2598 }
Christopher Lane74411222014-04-25 18:39:07 -07002599 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002600 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002601 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002602
Paul Hub2e67d32023-04-18 05:50:14 +00002603 private void log(String message) {
2604 mClientLogs.log(message);
2605 }
2606
Paul Hu508a0122023-09-11 15:31:33 +08002607 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2608 return !(request instanceof DiscoveryManagerRequest)
2609 && !(request instanceof AdvertiserClientRequest);
2610 }
2611
2612 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2613 ClientRequest request) {
2614 mMetrics.reportServiceDiscoveryStarted(
2615 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002616 try {
2617 mCb.onDiscoverServicesStarted(listenerKey, info);
2618 } catch (RemoteException e) {
2619 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2620 }
2621 }
Paul Hu508a0122023-09-11 15:31:33 +08002622 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2623 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2624 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002625 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002626
Paul Hu508a0122023-09-11 15:31:33 +08002627 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2628 int transactionId, long durationMs) {
2629 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002630 try {
2631 mCb.onDiscoverServicesFailed(listenerKey, error);
2632 } catch (RemoteException e) {
2633 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2634 }
2635 }
2636
Paul Hu812e9212023-06-20 06:24:53 +00002637 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2638 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002639 try {
2640 mCb.onServiceFound(listenerKey, info);
2641 } catch (RemoteException e) {
2642 Log.e(TAG, "Error calling onServiceFound(", e);
2643 }
2644 }
2645
Paul Hu812e9212023-06-20 06:24:53 +00002646 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2647 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002648 try {
2649 mCb.onServiceLost(listenerKey, info);
2650 } catch (RemoteException e) {
2651 Log.e(TAG, "Error calling onServiceLost(", e);
2652 }
2653 }
2654
2655 void onStopDiscoveryFailed(int listenerKey, int error) {
2656 try {
2657 mCb.onStopDiscoveryFailed(listenerKey, error);
2658 } catch (RemoteException e) {
2659 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2660 }
2661 }
2662
Paul Hu812e9212023-06-20 06:24:53 +00002663 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2664 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002665 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002666 request.mTransactionId,
2667 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2668 request.getFoundServiceCount(),
2669 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002670 request.getServicesCount(),
2671 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002672 try {
2673 mCb.onStopDiscoverySucceeded(listenerKey);
2674 } catch (RemoteException e) {
2675 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2676 }
2677 }
2678
Paul Hu508a0122023-09-11 15:31:33 +08002679 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2680 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2681 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002682 }
2683
Paul Hu508a0122023-09-11 15:31:33 +08002684 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2685 int transactionId, long durationMs) {
2686 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002687 try {
2688 mCb.onRegisterServiceFailed(listenerKey, error);
2689 } catch (RemoteException e) {
2690 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2691 }
2692 }
2693
Paul Hu508a0122023-09-11 15:31:33 +08002694 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2695 ClientRequest request) {
2696 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2697 request.mTransactionId,
2698 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002699 try {
2700 mCb.onRegisterServiceSucceeded(listenerKey, info);
2701 } catch (RemoteException e) {
2702 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2703 }
2704 }
2705
2706 void onUnregisterServiceFailed(int listenerKey, int error) {
2707 try {
2708 mCb.onUnregisterServiceFailed(listenerKey, error);
2709 } catch (RemoteException e) {
2710 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2711 }
2712 }
2713
Paul Hu508a0122023-09-11 15:31:33 +08002714 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002715 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002716 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2717 request.mTransactionId,
2718 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002719 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2720 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002721 try {
2722 mCb.onUnregisterServiceSucceeded(listenerKey);
2723 } catch (RemoteException e) {
2724 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2725 }
2726 }
2727
Paul Hu508a0122023-09-11 15:31:33 +08002728 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2729 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2730 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002731 }
2732
Paul Hu508a0122023-09-11 15:31:33 +08002733 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2734 int transactionId, long durationMs) {
2735 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002736 try {
2737 mCb.onResolveServiceFailed(listenerKey, error);
2738 } catch (RemoteException e) {
2739 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2740 }
2741 }
2742
Paul Hua6bc4632023-06-26 01:18:29 +00002743 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2744 ClientRequest request) {
2745 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002746 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002747 request.mTransactionId,
2748 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002749 request.isServiceFromCache(),
2750 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002751 try {
2752 mCb.onResolveServiceSucceeded(listenerKey, info);
2753 } catch (RemoteException e) {
2754 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2755 }
2756 }
Paul Hub58deb72022-12-26 09:24:42 +00002757
2758 void onStopResolutionFailed(int listenerKey, int error) {
2759 try {
2760 mCb.onStopResolutionFailed(listenerKey, error);
2761 } catch (RemoteException e) {
2762 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2763 }
2764 }
2765
Paul Hu60149052023-07-31 14:26:08 +08002766 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2767 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002768 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002769 request.mTransactionId,
2770 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002771 try {
2772 mCb.onStopResolutionSucceeded(listenerKey);
2773 } catch (RemoteException e) {
2774 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2775 }
2776 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002777
2778 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002779 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002780 try {
2781 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2782 } catch (RemoteException e) {
2783 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2784 }
2785 }
2786
Paul Huddce5912023-08-01 10:26:49 +08002787 void onServiceInfoCallbackRegistered(int transactionId) {
2788 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2789 }
2790
2791 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2792 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002793 try {
2794 mCb.onServiceUpdated(listenerKey, info);
2795 } catch (RemoteException e) {
2796 Log.e(TAG, "Error calling onServiceUpdated", e);
2797 }
2798 }
2799
Paul Huddce5912023-08-01 10:26:49 +08002800 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2801 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002802 try {
2803 mCb.onServiceUpdatedLost(listenerKey);
2804 } catch (RemoteException e) {
2805 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2806 }
2807 }
2808
Paul Huddce5912023-08-01 10:26:49 +08002809 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2810 mMetrics.reportServiceInfoCallbackUnregistered(
2811 request.mTransactionId,
2812 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2813 request.getFoundServiceCount(),
2814 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002815 request.isServiceFromCache(),
2816 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002817 try {
2818 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2819 } catch (RemoteException e) {
2820 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2821 }
2822 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002823 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002824}