blob: 47a1022551debbfe2a5356ff62b93e3ae11a7f11 [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
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090022import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090025import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090026import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090027
Paul Hu23fa2022023-01-13 22:57:24 +080028import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080029import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080030import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070031import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090032import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090033import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080034import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090035import android.net.LinkProperties;
36import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080037import android.net.mdns.aidl.DiscoveryInfo;
38import android.net.mdns.aidl.GetAddressInfo;
39import android.net.mdns.aidl.IMDnsEventListener;
40import android.net.mdns.aidl.RegistrationInfo;
41import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090043import android.net.nsd.INsdManagerCallback;
44import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080045import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070046import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080047import android.net.nsd.NsdServiceInfo;
Paul Hub2e67d32023-04-18 05:50:14 +000048import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090049import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080050import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090051import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080052import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070053import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090054import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070055import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080056import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090057import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090058import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070059import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070060
paulhua262cc12019-08-12 16:25:11 +080061import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000062import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080063import com.android.internal.util.State;
64import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090066import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080067import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000068import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090070import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080071import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
72import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080073import com.android.server.connectivity.mdns.MdnsSearchOptions;
74import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
75import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080076import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090077import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080078
Irfan Sheriff77ec5582012-03-22 17:01:39 -070079import java.io.FileDescriptor;
80import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090081import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070082import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090083import java.net.NetworkInterface;
84import java.net.SocketException;
85import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080086import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090087import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070088import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080089import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080090import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080091import java.util.regex.Matcher;
92import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070093
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094/**
95 * Network Service Discovery Service handles remote service discovery operation requests by
96 * implementing the INsdManager interface.
97 *
98 * @hide
99 */
100public class NsdService extends INsdManager.Stub {
101 private static final String TAG = "NsdService";
102 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900103 /**
104 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
105 * implementation.
106 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800107 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800108 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700109
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900110 /**
111 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
112 * implementation.
113 */
114 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
115
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900116 /**
117 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
118 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
119 *
120 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
121 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
122 *
123 * In which case the flags:
124 * "mdns_discovery_manager_allowlist_mytype_version",
125 * "mdns_advertiser_allowlist_mytype_version",
126 * "mdns_discovery_manager_allowlist_othertype_version",
127 * "mdns_advertiser_allowlist_othertype_version"
128 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
129 * be read with
130 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
131 *
132 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
133 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
134 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
135 */
136 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
137
138 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
139 "mdns_discovery_manager_allowlist_";
140 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
141 "mdns_advertiser_allowlist_";
142 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
143
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900144 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000145 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900146 private static final int IFACE_IDX_ANY = 0;
Paul Hu14667de2023-04-17 22:42:47 +0800147 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700148
Hugo Benichi32be63d2017-04-05 14:06:11 +0900149 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900150 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800151 private final MDnsManager mMDnsManager;
152 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900153 @NonNull
154 private final Dependencies mDeps;
155 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800156 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800160 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900161 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900162 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800163 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800164 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800165 // state machine thread. If change this outside state machine, it will need to introduce
166 // synchronization.
167 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800168 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700169
170 /**
171 * Clients receiving asynchronous messages
172 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900173 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700174
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700175 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900176 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700177
Luke Huang05298582021-06-13 16:52:05 +0000178 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700179
Hugo Benichi32be63d2017-04-05 14:06:11 +0900180 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700181 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800182 // The count of the connected legacy clients.
183 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000184 // The number of client that ever connected.
185 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700186
Paul Hu23fa2022023-01-13 22:57:24 +0800187 private static class MdnsListener implements MdnsServiceBrowserListener {
188 protected final int mClientId;
189 protected final int mTransactionId;
190 @NonNull
191 protected final NsdServiceInfo mReqServiceInfo;
192 @NonNull
193 protected final String mListenedServiceType;
194
195 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
196 @NonNull String listenedServiceType) {
197 mClientId = clientId;
198 mTransactionId = transactionId;
199 mReqServiceInfo = reqServiceInfo;
200 mListenedServiceType = listenedServiceType;
201 }
202
203 @NonNull
204 public String getListenedServiceType() {
205 return mListenedServiceType;
206 }
207
208 @Override
209 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
210
211 @Override
212 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
213
214 @Override
215 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
216
217 @Override
218 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
219
220 @Override
221 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
222
223 @Override
224 public void onSearchStoppedWithError(int error) { }
225
226 @Override
227 public void onSearchFailedToStart() { }
228
229 @Override
230 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
231
232 @Override
233 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
234 }
235
236 private class DiscoveryListener extends MdnsListener {
237
238 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
239 @NonNull String listenServiceType) {
240 super(clientId, transactionId, reqServiceInfo, listenServiceType);
241 }
242
243 @Override
244 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800245 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
246 NsdManager.SERVICE_FOUND,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900247 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800248 }
249
250 @Override
251 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800252 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
253 NsdManager.SERVICE_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900254 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800255 }
256 }
257
Paul Hu75069ed2023-01-14 00:31:09 +0800258 private class ResolutionListener extends MdnsListener {
259
260 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
261 @NonNull String listenServiceType) {
262 super(clientId, transactionId, reqServiceInfo, listenServiceType);
263 }
264
265 @Override
266 public void onServiceFound(MdnsServiceInfo serviceInfo) {
267 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
268 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900269 new MdnsEvent(mClientId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800270 }
271 }
272
Paul Hu30bd70d2023-02-07 13:20:56 +0000273 private class ServiceInfoListener extends MdnsListener {
274
275 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
276 @NonNull String listenServiceType) {
277 super(clientId, transactionId, reqServiceInfo, listenServiceType);
278 }
279
280 @Override
281 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
282 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
283 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900284 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000285 }
286
287 @Override
288 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
289 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
290 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900291 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000292 }
293
294 @Override
295 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
296 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
297 NsdManager.SERVICE_UPDATED_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900298 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000299 }
300 }
301
Paul Hu019621e2023-01-13 23:26:49 +0800302 /**
303 * Data class of mdns service callback information.
304 */
305 private static class MdnsEvent {
306 final int mClientId;
307 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800308 final MdnsServiceInfo mMdnsServiceInfo;
309
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900310 MdnsEvent(int clientId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800311 mClientId = clientId;
Paul Hu019621e2023-01-13 23:26:49 +0800312 mMdnsServiceInfo = mdnsServiceInfo;
313 }
314 }
315
Irfan Sheriff75006652012-04-17 23:15:29 -0700316 private class NsdStateMachine extends StateMachine {
317
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700318 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700319 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700320
321 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700322 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900323 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700324 }
325
Luke Huang92860f92021-06-23 06:29:30 +0000326 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800327 if (mIsDaemonStarted) {
328 if (DBG) Log.d(TAG, "Daemon is already started.");
329 return;
330 }
331 mMDnsManager.registerEventListener(mMDnsEventCallback);
332 mMDnsManager.startDaemon();
333 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000334 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000335 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000336 }
337
paulhu2b9ed952022-02-10 21:58:32 +0800338 private void maybeStopDaemon() {
339 if (!mIsDaemonStarted) {
340 if (DBG) Log.d(TAG, "Daemon has not been started.");
341 return;
342 }
343 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
344 mMDnsManager.stopDaemon();
345 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000346 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800347 }
348
Luke Huang92860f92021-06-23 06:29:30 +0000349 private boolean isAnyRequestActive() {
350 return mIdToClientInfoMap.size() != 0;
351 }
352
353 private void scheduleStop() {
354 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
355 }
356 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800357 // The native daemon should stay alive and can't be cleanup
358 // if any legacy client connected.
359 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000360 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000361 }
362 }
363
Luke Huang92860f92021-06-23 06:29:30 +0000364 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000365 this.removeMessages(NsdManager.DAEMON_CLEANUP);
366 }
367
Paul Hu23fa2022023-01-13 22:57:24 +0800368 private void maybeStartMonitoringSockets() {
369 if (mIsMonitoringSocketsStarted) {
370 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
371 return;
372 }
373
374 mMdnsSocketProvider.startMonitoringSockets();
375 mIsMonitoringSocketsStarted = true;
376 }
377
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900378 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
379 if (!mIsMonitoringSocketsStarted) return;
380 if (isAnyRequestActive()) return;
381
Paul Hu58f20602023-02-18 11:41:07 +0800382 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800383 mIsMonitoringSocketsStarted = false;
384 }
385
Hugo Benichi803a2f02017-04-24 11:35:06 +0900386 NsdStateMachine(String name, Handler handler) {
387 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700388 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700389 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800390 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900391 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700392 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700393 }
394
395 class DefaultState extends State {
396 @Override
397 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900398 final ClientInfo cInfo;
399 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700400 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900401 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800402 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
403 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900404 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800405 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000406 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
407 cInfo = new ClientInfo(cb, arg.useJavaBackend,
408 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800409 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900410 } catch (RemoteException e) {
411 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700412 }
413 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900414 case NsdManager.UNREGISTER_CLIENT:
415 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
416 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800417 if (cInfo != null) {
418 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900419 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800420 mLegacyClientCount -= 1;
421 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800422 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900423 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800424 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700425 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900427 cInfo = getClientInfoForReply(msg);
428 if (cInfo != null) {
429 cInfo.onDiscoverServicesFailed(
430 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
431 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700432 break;
433 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900434 cInfo = getClientInfoForReply(msg);
435 if (cInfo != null) {
436 cInfo.onStopDiscoveryFailed(
437 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
438 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 break;
440 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900441 cInfo = getClientInfoForReply(msg);
442 if (cInfo != null) {
443 cInfo.onRegisterServiceFailed(
444 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
445 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 break;
447 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900448 cInfo = getClientInfoForReply(msg);
449 if (cInfo != null) {
450 cInfo.onUnregisterServiceFailed(
451 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
452 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 break;
454 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900455 cInfo = getClientInfoForReply(msg);
456 if (cInfo != null) {
457 cInfo.onResolveServiceFailed(
458 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
459 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700460 break;
Paul Hub58deb72022-12-26 09:24:42 +0000461 case NsdManager.STOP_RESOLUTION:
462 cInfo = getClientInfoForReply(msg);
463 if (cInfo != null) {
464 cInfo.onStopResolutionFailed(
465 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
466 }
467 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000468 case NsdManager.REGISTER_SERVICE_CALLBACK:
469 cInfo = getClientInfoForReply(msg);
470 if (cInfo != null) {
471 cInfo.onServiceInfoCallbackRegistrationFailed(
472 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
473 }
474 break;
Luke Huang05298582021-06-13 16:52:05 +0000475 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800476 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000477 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800478 // This event should be only sent by the legacy (target SDK < S) clients.
479 // Mark the sending client as legacy.
480 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900481 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800482 if (cInfo != null) {
483 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900484 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800485 mLegacyClientCount += 1;
486 maybeStartDaemon();
487 }
488 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700489 default:
paulhub2225702021-11-17 09:35:33 +0800490 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700491 return NOT_HANDLED;
492 }
493 return HANDLED;
494 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900495
496 private ClientInfo getClientInfoForReply(Message msg) {
497 final ListenerArgs args = (ListenerArgs) msg.obj;
498 return mClients.get(args.connector);
499 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700500 }
501
Irfan Sheriff75006652012-04-17 23:15:29 -0700502 class EnabledState extends State {
503 @Override
504 public void enter() {
505 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700506 }
507
508 @Override
509 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000510 // TODO: it is incorrect to stop the daemon without expunging all requests
511 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000512 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700513 }
514
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700515 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900516 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800517 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700518 return true;
519 }
520 return false;
521 }
522
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900523 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
524 int what) {
525 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700526 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000527 // Remove the cleanup event because here comes a new request.
528 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700529 }
530
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900531 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800532 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900533 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
534 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800535 }
536
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900537 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
538 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
539 if (existing == null) return;
540 clientInfo.mClientRequests.remove(clientId);
541 mIdToClientInfoMap.remove(globalId);
542
543 if (existing instanceof LegacyClientRequest) {
544 maybeScheduleStop();
545 } else {
546 maybeStopMonitoringSocketsIfNoActiveRequest();
547 }
548 }
549
550 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
551 MdnsListener listener, ClientInfo clientInfo) {
552 clientInfo.mClientRequests.put(clientId,
553 new DiscoveryManagerRequest(globalId, listener));
554 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800555 }
556
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900557 /**
558 * Truncate a service name to up to 63 UTF-8 bytes.
559 *
560 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
561 * names used in registerService follows historical behavior (see mdnsresponder
562 * handle_regservice_request).
563 */
564 @NonNull
565 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900566 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800567 }
568
Paul Hue4f5f252023-02-16 21:13:47 +0800569 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
570 ClientInfo clientInfo) {
571 clientInfo.unregisterMdnsListenerFromRequest(request);
572 removeRequestMap(clientId, id, clientInfo);
573 }
574
Irfan Sheriff75006652012-04-17 23:15:29 -0700575 @Override
576 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900577 final ClientInfo clientInfo;
578 final int id;
579 final int clientId = msg.arg2;
580 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700581 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800582 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800583 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900584 args = (ListenerArgs) msg.obj;
585 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000586 // If the binder death notification for a INsdManagerCallback was received
587 // before any calls are received by NsdService, the clientInfo would be
588 // cleared and cause NPE. Add a null check here to prevent this corner case.
589 if (clientInfo == null) {
590 Log.e(TAG, "Unknown connector in discovery");
591 break;
592 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700593
594 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 clientInfo.onDiscoverServicesFailed(
596 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700597 break;
598 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700599
Paul Hu23fa2022023-01-13 22:57:24 +0800600 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700601 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900602 final Pair<String, String> typeAndSubtype =
603 parseTypeAndSubtype(info.getServiceType());
604 final String serviceType = typeAndSubtype == null
605 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800606 if (clientInfo.mUseJavaBackend
607 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900608 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800609 if (serviceType == null) {
610 clientInfo.onDiscoverServicesFailed(clientId,
611 NsdManager.FAILURE_INTERNAL_ERROR);
612 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700613 }
Paul Hu23fa2022023-01-13 22:57:24 +0800614
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900615 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800616 maybeStartMonitoringSockets();
617 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900618 new DiscoveryListener(clientId, id, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900619 final MdnsSearchOptions.Builder optionsBuilder =
620 MdnsSearchOptions.newBuilder()
621 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900622 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900623 .setIsPassiveMode(true);
624 if (typeAndSubtype.second != null) {
625 // The parsing ensures subtype starts with an underscore.
626 // MdnsSearchOptions expects the underscore to not be present.
627 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
628 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900629 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900630 listenServiceType, listener, optionsBuilder.build());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900631 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800632 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000633 clientInfo.log("Register a DiscoveryListener " + id
634 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700635 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800636 maybeStartDaemon();
637 if (discoverServices(id, info)) {
638 if (DBG) {
639 Log.d(TAG, "Discover " + msg.arg2 + " " + id
640 + info.getServiceType());
641 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900642 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800643 clientInfo.onDiscoverServicesStarted(clientId, info);
644 } else {
645 stopServiceDiscovery(id);
646 clientInfo.onDiscoverServicesFailed(clientId,
647 NsdManager.FAILURE_INTERNAL_ERROR);
648 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700649 }
650 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800651 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900652 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800653 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 args = (ListenerArgs) msg.obj;
655 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000656 // If the binder death notification for a INsdManagerCallback was received
657 // before any calls are received by NsdService, the clientInfo would be
658 // cleared and cause NPE. Add a null check here to prevent this corner case.
659 if (clientInfo == null) {
660 Log.e(TAG, "Unknown connector in stop discovery");
661 break;
662 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700663
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900664 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
665 if (request == null) {
666 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 break;
668 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900669 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900670 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
671 // point, so this needs to check the type of the original request to
672 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900673 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800674 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900675 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000676 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700677 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800678 removeRequestMap(clientId, id, clientInfo);
679 if (stopServiceDiscovery(id)) {
680 clientInfo.onStopDiscoverySucceeded(clientId);
681 } else {
682 clientInfo.onStopDiscoveryFailed(
683 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
684 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700685 }
686 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900687 }
688 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800689 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900690 args = (ListenerArgs) msg.obj;
691 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000692 // If the binder death notification for a INsdManagerCallback was received
693 // before any calls are received by NsdService, the clientInfo would be
694 // cleared and cause NPE. Add a null check here to prevent this corner case.
695 if (clientInfo == null) {
696 Log.e(TAG, "Unknown connector in registration");
697 break;
698 }
699
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700700 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900701 clientInfo.onRegisterServiceFailed(
702 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700703 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700704 }
705
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700706 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900707 final NsdServiceInfo serviceInfo = args.serviceInfo;
708 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900709 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
710 final String registerServiceType = typeSubtype == null
711 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800712 if (clientInfo.mUseJavaBackend
713 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900714 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900715 if (registerServiceType == null) {
716 Log.e(TAG, "Invalid service type: " + serviceType);
717 clientInfo.onRegisterServiceFailed(clientId,
718 NsdManager.FAILURE_INTERNAL_ERROR);
719 break;
720 }
721 serviceInfo.setServiceType(registerServiceType);
722 serviceInfo.setServiceName(truncateServiceName(
723 serviceInfo.getServiceName()));
724
725 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900726 // TODO: pass in the subtype as well. Including the subtype in the
727 // service type would generate service instance names like
728 // Name._subtype._sub._type._tcp, which is incorrect
729 // (it should be Name._type._tcp).
Remi NGUYEN VANce44beb2023-05-11 20:42:26 +0900730 mAdvertiser.addService(id, serviceInfo, typeSubtype.second);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900731 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700732 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900733 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900734 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900735 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900736 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900737 // Return success after mDns reports success
738 } else {
739 unregisterService(id);
740 clientInfo.onRegisterServiceFailed(
741 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
742 }
743
Irfan Sheriff75006652012-04-17 23:15:29 -0700744 }
745 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900746 }
747 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800748 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900749 args = (ListenerArgs) msg.obj;
750 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000751 // If the binder death notification for a INsdManagerCallback was received
752 // before any calls are received by NsdService, the clientInfo would be
753 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900754 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800755 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700756 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700757 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900758 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
759 if (request == null) {
760 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
761 break;
762 }
763 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900764 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900765
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900766 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
767 // so this needs to check the type of the original request to unregister
768 // instead of looking at the flag value.
769 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900770 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900771 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700772 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900773 if (unregisterService(id)) {
774 clientInfo.onUnregisterServiceSucceeded(clientId);
775 } else {
776 clientInfo.onUnregisterServiceFailed(
777 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
778 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700779 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700780 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900781 }
Paul Hu75069ed2023-01-14 00:31:09 +0800782 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800783 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900784 args = (ListenerArgs) msg.obj;
785 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000786 // If the binder death notification for a INsdManagerCallback was received
787 // before any calls are received by NsdService, the clientInfo would be
788 // cleared and cause NPE. Add a null check here to prevent this corner case.
789 if (clientInfo == null) {
790 Log.e(TAG, "Unknown connector in resolution");
791 break;
792 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700793
Paul Hu75069ed2023-01-14 00:31:09 +0800794 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700795 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900796 final Pair<String, String> typeSubtype =
797 parseTypeAndSubtype(info.getServiceType());
798 final String serviceType = typeSubtype == null
799 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800800 if (clientInfo.mUseJavaBackend
801 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900802 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800803 if (serviceType == null) {
804 clientInfo.onResolveServiceFailed(clientId,
805 NsdManager.FAILURE_INTERNAL_ERROR);
806 break;
807 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900808 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800809
810 maybeStartMonitoringSockets();
811 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900812 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800813 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
814 .setNetwork(info.getNetwork())
815 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900816 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900817 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800818 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900819 mMdnsDiscoveryManager.registerListener(
820 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900821 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000822 clientInfo.log("Register a ResolutionListener " + id
823 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700824 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800825 if (clientInfo.mResolvedService != null) {
826 clientInfo.onResolveServiceFailed(
827 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
828 break;
829 }
830
831 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900832 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800833 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900834 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800835 } else {
836 clientInfo.onResolveServiceFailed(
837 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
838 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700839 }
840 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800841 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900842 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000843 if (DBG) Log.d(TAG, "Stop service resolution");
844 args = (ListenerArgs) msg.obj;
845 clientInfo = mClients.get(args.connector);
846 // If the binder death notification for a INsdManagerCallback was received
847 // before any calls are received by NsdService, the clientInfo would be
848 // cleared and cause NPE. Add a null check here to prevent this corner case.
849 if (clientInfo == null) {
850 Log.e(TAG, "Unknown connector in stop resolution");
851 break;
852 }
853
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900854 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
855 if (request == null) {
856 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
857 break;
858 }
859 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800860 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
861 // point, so this needs to check the type of the original request to
862 // unregister instead of looking at the flag value.
863 if (request instanceof DiscoveryManagerRequest) {
864 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000865 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000866 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000867 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800868 removeRequestMap(clientId, id, clientInfo);
869 if (stopResolveService(id)) {
870 clientInfo.onStopResolutionSucceeded(clientId);
871 } else {
872 clientInfo.onStopResolutionFailed(
873 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
874 }
875 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000876 }
Paul Hub58deb72022-12-26 09:24:42 +0000877 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900878 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000879 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000880 if (DBG) Log.d(TAG, "Register a service callback");
881 args = (ListenerArgs) msg.obj;
882 clientInfo = mClients.get(args.connector);
883 // If the binder death notification for a INsdManagerCallback was received
884 // before any calls are received by NsdService, the clientInfo would be
885 // cleared and cause NPE. Add a null check here to prevent this corner case.
886 if (clientInfo == null) {
887 Log.e(TAG, "Unknown connector in callback registration");
888 break;
889 }
890
Paul Hu30bd70d2023-02-07 13:20:56 +0000891 final NsdServiceInfo info = args.serviceInfo;
892 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900893 final Pair<String, String> typeAndSubtype =
894 parseTypeAndSubtype(info.getServiceType());
895 final String serviceType = typeAndSubtype == null
896 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +0000897 if (serviceType == null) {
898 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
899 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000900 break;
901 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000902 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000903
Paul Hu30bd70d2023-02-07 13:20:56 +0000904 maybeStartMonitoringSockets();
905 final MdnsListener listener =
906 new ServiceInfoListener(clientId, id, info, resolveServiceType);
907 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
908 .setNetwork(info.getNetwork())
909 .setIsPassiveMode(true)
910 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900911 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +0000912 .build();
913 mMdnsDiscoveryManager.registerListener(
914 resolveServiceType, listener, options);
915 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000916 clientInfo.log("Register a ServiceInfoListener " + id
917 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000918 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000919 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900920 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000921 if (DBG) Log.d(TAG, "Unregister a service callback");
922 args = (ListenerArgs) msg.obj;
923 clientInfo = mClients.get(args.connector);
924 // If the binder death notification for a INsdManagerCallback was received
925 // before any calls are received by NsdService, the clientInfo would be
926 // cleared and cause NPE. Add a null check here to prevent this corner case.
927 if (clientInfo == null) {
928 Log.e(TAG, "Unknown connector in callback unregistration");
929 break;
930 }
931
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900932 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
933 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000934 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900935 break;
936 }
937 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000938 if (request instanceof DiscoveryManagerRequest) {
939 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000940 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000941 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000942 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000943 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000944 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000945 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900946 }
paulhu2b9ed952022-02-10 21:58:32 +0800947 case MDNS_SERVICE_EVENT:
948 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900949 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700950 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700951 break;
Paul Hu019621e2023-01-13 23:26:49 +0800952 case MDNS_DISCOVERY_MANAGER_EVENT:
953 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
954 return NOT_HANDLED;
955 }
956 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700957 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900958 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700959 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900960 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700961 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700962
paulhu2b9ed952022-02-10 21:58:32 +0800963 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700964 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700965 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
966 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800967 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900968 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700969 }
970
971 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700972 int clientId = clientInfo.getClientId(id);
973 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700974 // This can happen because of race conditions. For example,
975 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
976 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800977 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
978 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900979 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700980 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900981 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800982 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900983 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700984 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800985 case IMDnsEventListener.SERVICE_FOUND: {
986 final DiscoveryInfo info = (DiscoveryInfo) obj;
987 final String name = info.serviceName;
988 final String type = info.registrationType;
989 servInfo = new NsdServiceInfo(name, type);
990 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900991 if (foundNetId == 0L) {
992 // Ignore services that do not have a Network: they are not usable
993 // by apps, as they would need privileged permissions to use
994 // interfaces that do not have an associated Network.
995 break;
996 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900997 if (foundNetId == INetd.DUMMY_NET_ID) {
998 // Ignore services on the dummy0 interface: they are only seen when
999 // discovering locally advertised services, and are not reachable
1000 // through that interface.
1001 break;
1002 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001003 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001004 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001005 break;
paulhu2b9ed952022-02-10 21:58:32 +08001006 }
1007 case IMDnsEventListener.SERVICE_LOST: {
1008 final DiscoveryInfo info = (DiscoveryInfo) obj;
1009 final String name = info.serviceName;
1010 final String type = info.registrationType;
1011 final int lostNetId = info.netId;
1012 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001013 // The network could be set to null (netId 0) if it was torn down when the
1014 // service is lost
1015 // TODO: avoid returning null in that case, possibly by remembering
1016 // found services on the same interface index and their network at the time
1017 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001018 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001019 break;
paulhu2b9ed952022-02-10 21:58:32 +08001020 }
1021 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001022 clientInfo.onDiscoverServicesFailed(
1023 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001024 break;
paulhu2b9ed952022-02-10 21:58:32 +08001025 case IMDnsEventListener.SERVICE_REGISTERED: {
1026 final RegistrationInfo info = (RegistrationInfo) obj;
1027 final String name = info.serviceName;
1028 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001029 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 break;
paulhu2b9ed952022-02-10 21:58:32 +08001031 }
1032 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001033 clientInfo.onRegisterServiceFailed(
1034 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001035 break;
paulhu2b9ed952022-02-10 21:58:32 +08001036 case IMDnsEventListener.SERVICE_RESOLVED: {
1037 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001038 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001039 final String fullName = info.serviceFullName;
1040 while (index < fullName.length() && fullName.charAt(index) != '.') {
1041 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001042 ++index;
1043 }
1044 ++index;
1045 }
paulhu2b9ed952022-02-10 21:58:32 +08001046 if (index >= fullName.length()) {
1047 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001048 break;
1049 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001050
paulhube186602022-04-12 07:18:23 +00001051 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001052 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001053 String type = rest.replace(".local.", "");
1054
Paul Hu30bd70d2023-02-07 13:20:56 +00001055 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001056 serviceInfo.setServiceName(name);
1057 serviceInfo.setServiceType(type);
1058 serviceInfo.setPort(info.port);
1059 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001060 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001061
1062 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001063 removeRequestMap(clientId, id, clientInfo);
1064
paulhu2b9ed952022-02-10 21:58:32 +08001065 final int id2 = getUniqueId();
1066 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001067 storeLegacyRequestMap(clientId, id2, clientInfo,
1068 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001069 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001070 clientInfo.onResolveServiceFailed(
1071 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1072 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001073 }
1074 break;
paulhu2b9ed952022-02-10 21:58:32 +08001075 }
1076 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001077 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001078 stopResolveService(id);
1079 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001080 clientInfo.onResolveServiceFailed(
1081 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1082 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 break;
paulhu2b9ed952022-02-10 21:58:32 +08001084 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001085 /* NNN resolveId errorCode */
1086 stopGetAddrInfo(id);
1087 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001088 clientInfo.onResolveServiceFailed(
1089 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1090 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001091 break;
paulhu2b9ed952022-02-10 21:58:32 +08001092 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001093 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001094 final GetAddressInfo info = (GetAddressInfo) obj;
1095 final String address = info.address;
1096 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001097 InetAddress serviceHost = null;
1098 try {
paulhu2b9ed952022-02-10 21:58:32 +08001099 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001100 } catch (UnknownHostException e) {
1101 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1102 }
1103
1104 // If the resolved service is on an interface without a network, consider it
1105 // as a failure: it would not be usable by apps as they would need
1106 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001107 if (netId != NETID_UNSET && serviceHost != null) {
1108 clientInfo.mResolvedService.setHost(serviceHost);
1109 setServiceNetworkForCallback(clientInfo.mResolvedService,
1110 netId, info.interfaceIdx);
1111 clientInfo.onResolveServiceSucceeded(
1112 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001113 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001114 clientInfo.onResolveServiceFailed(
1115 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001116 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001117 stopGetAddrInfo(id);
1118 removeRequestMap(clientId, id, clientInfo);
1119 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001120 break;
paulhu2b9ed952022-02-10 21:58:32 +08001121 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001122 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001123 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001124 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001125 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001126 }
Paul Hu019621e2023-01-13 23:26:49 +08001127
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001128 @Nullable
1129 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1130 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001131 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001132 final String[] typeArray = serviceInfo.getServiceType();
1133 final String joinedType;
1134 if (typeArray.length == 0
1135 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1136 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1137 + Arrays.toString(typeArray));
1138 return null;
1139 } else {
1140 joinedType = TextUtils.join(".",
1141 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1142 }
1143 final String serviceType;
1144 switch (code) {
1145 case NsdManager.SERVICE_FOUND:
1146 case NsdManager.SERVICE_LOST:
1147 // For consistency with historical behavior, discovered service types have
1148 // a dot at the end.
1149 serviceType = joinedType + ".";
1150 break;
1151 case RESOLVE_SERVICE_SUCCEEDED:
1152 // For consistency with historical behavior, resolved service types have
1153 // a dot at the beginning.
1154 serviceType = "." + joinedType;
1155 break;
1156 default:
1157 serviceType = joinedType;
1158 break;
1159 }
Paul Hu019621e2023-01-13 23:26:49 +08001160 final String serviceName = serviceInfo.getServiceInstanceName();
1161 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1162 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001163 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1164 // network for Tethering interface. In other words, the network == null means the
1165 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001166 setServiceNetworkForCallback(
1167 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001168 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001169 serviceInfo.getInterfaceIndex());
1170 return servInfo;
1171 }
1172
1173 private boolean handleMdnsDiscoveryManagerEvent(
1174 int transactionId, int code, Object obj) {
1175 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1176 if (clientInfo == null) {
1177 Log.e(TAG, String.format(
1178 "id %d for %d has no client mapping", transactionId, code));
1179 return false;
1180 }
1181
1182 final MdnsEvent event = (MdnsEvent) obj;
1183 final int clientId = event.mClientId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001184 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1185 // Errors are already logged if null
1186 if (info == null) return false;
Paul Hu019621e2023-01-13 23:26:49 +08001187 if (DBG) {
1188 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1189 NsdManager.nameOf(code), transactionId));
1190 }
1191 switch (code) {
1192 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001193 clientInfo.onServiceFound(clientId, info);
1194 break;
1195 case NsdManager.SERVICE_LOST:
1196 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001197 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001198 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001199 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1200 if (request == null) {
1201 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1202 break;
1203 }
Paul Hu75069ed2023-01-14 00:31:09 +08001204 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001205 info.setPort(serviceInfo.getPort());
1206
1207 Map<String, String> attrs = serviceInfo.getAttributes();
1208 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1209 final String key = kv.getKey();
1210 try {
1211 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1212 } catch (IllegalArgumentException e) {
1213 Log.e(TAG, "Invalid attribute", e);
1214 }
1215 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001216 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001217 if (addresses.size() != 0) {
1218 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001219 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001220 } else {
1221 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001222 clientInfo.onResolveServiceFailed(
1223 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1224 }
1225
1226 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001227 if (!(request instanceof DiscoveryManagerRequest)) {
1228 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1229 break;
1230 }
Paul Hue4f5f252023-02-16 21:13:47 +08001231 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001232 break;
1233 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001234 case NsdManager.SERVICE_UPDATED: {
1235 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1236 info.setPort(serviceInfo.getPort());
1237
1238 Map<String, String> attrs = serviceInfo.getAttributes();
1239 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1240 final String key = kv.getKey();
1241 try {
1242 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1243 } catch (IllegalArgumentException e) {
1244 Log.e(TAG, "Invalid attribute", e);
1245 }
1246 }
1247
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001248 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001249 info.setHostAddresses(addresses);
1250 clientInfo.onServiceUpdated(clientId, info);
1251 break;
1252 }
1253 case NsdManager.SERVICE_UPDATED_LOST:
1254 clientInfo.onServiceUpdatedLost(clientId);
1255 break;
Paul Hu019621e2023-01-13 23:26:49 +08001256 default:
1257 return false;
1258 }
1259 return true;
1260 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001261 }
1262 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001263
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001264 @NonNull
1265 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1266 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1267 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1268 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1269 for (String ipv4Address : v4Addrs) {
1270 try {
1271 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1272 } catch (IllegalArgumentException e) {
1273 Log.wtf(TAG, "Invalid ipv4 address", e);
1274 }
1275 }
1276 for (String ipv6Address : v6Addrs) {
1277 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001278 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1279 ipv6Address);
1280 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1281 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001282 Log.wtf(TAG, "Invalid ipv6 address", e);
1283 }
1284 }
1285 return addresses;
1286 }
1287
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001288 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1289 switch (netId) {
1290 case NETID_UNSET:
1291 info.setNetwork(null);
1292 break;
1293 case INetd.LOCAL_NET_ID:
1294 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1295 // visible / usable for apps, so do not return it. Store the interface
1296 // index instead, so at least if the client tries to resolve the service
1297 // with that NsdServiceInfo, it will be done on the same interface.
1298 // If they recreate the NsdServiceInfo themselves, resolution would be
1299 // done on all interfaces as before T, which should also work.
1300 info.setNetwork(null);
1301 info.setInterfaceIndex(ifaceIdx);
1302 break;
1303 default:
1304 info.setNetwork(new Network(netId));
1305 }
1306 }
1307
paulhube186602022-04-12 07:18:23 +00001308 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1309 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1310 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1311 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1312 private String unescape(String s) {
1313 StringBuilder sb = new StringBuilder(s.length());
1314 for (int i = 0; i < s.length(); ++i) {
1315 char c = s.charAt(i);
1316 if (c == '\\') {
1317 if (++i >= s.length()) {
1318 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1319 break;
1320 }
1321 c = s.charAt(i);
1322 if (c != '.' && c != '\\') {
1323 if (i + 2 >= s.length()) {
1324 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1325 break;
1326 }
1327 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1328 + (s.charAt(i + 2) - '0'));
1329 i += 2;
1330 }
1331 }
1332 sb.append(c);
1333 }
1334 return sb.toString();
1335 }
1336
Paul Hu7445e3d2023-03-03 15:14:00 +08001337 /**
1338 * Check the given service type is valid and construct it to a service type
1339 * which can use for discovery / resolution service.
1340 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001341 * <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 +08001342 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1343 * underscore; they are alphanumerical characters or dashes or underscore, except the
1344 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1345 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001346 * <p>The subtype may also be specified with a comma after the service type, for example
1347 * _type._tcp,_subtype.
1348 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001349 * @param serviceType the request service type for discovery / resolution service
1350 * @return constructed service type or null if the given service type is invalid.
1351 */
1352 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001353 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001354 if (TextUtils.isEmpty(serviceType)) return null;
1355
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001356 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001357 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001358 // Optional leading subtype (_subtype._type._tcp)
1359 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1360 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1361 // Actual type (_type._tcp.local)
1362 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001363 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001364 // e.g. allow "_type._tcp.local."
1365 + "\\.?"
1366 // Optional subtype after comma, for "_type._tcp,_subtype" format
1367 + "(?:,(" + typeOrSubtypePattern + "))?"
1368 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001369 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1370 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001371 // Use the subtype either at the beginning or after the comma
1372 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1373 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001374 }
1375
Hugo Benichi803a2f02017-04-24 11:35:06 +09001376 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001377 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001378 this(ctx, handler, cleanupDelayMs, new Dependencies());
1379 }
1380
1381 @VisibleForTesting
1382 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001383 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001384 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001385 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001386 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001387 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1388 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001389 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001390
Paul Hu14667de2023-04-17 22:42:47 +08001391 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
1392 LOGGER.forSubComponent("MdnsSocketProvider"));
Yuyang Huang700778b2023-03-08 16:17:05 +09001393 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1394 // address events are received.
1395 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001396 mMdnsSocketClient =
1397 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001398 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001399 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001400 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1401 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001402 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001403 }
1404
1405 /**
1406 * Dependencies of NsdService, for injection in tests.
1407 */
1408 @VisibleForTesting
1409 public static class Dependencies {
1410 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001411 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001412 *
1413 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001414 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001415 */
1416 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001417 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1418 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001419 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001420 }
1421
1422 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001423 * Check whether the MdnsAdvertiser feature is enabled.
1424 *
1425 * @param context The global context information about an app environment.
1426 * @return true if the MdnsAdvertiser feature is enabled.
1427 */
1428 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001429 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1430 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1431 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001432 }
1433
1434 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001435 * Get the type allowlist flag value.
1436 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1437 */
1438 @Nullable
1439 public String getTypeAllowlistFlags() {
1440 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1441 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1442 }
1443
1444 /**
1445 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1446 */
1447 public boolean isFeatureEnabled(Context context, String feature) {
1448 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1449 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1450 }
1451
1452 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001453 * @see MdnsDiscoveryManager
1454 */
1455 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001456 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001457 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1458 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001459 }
1460
1461 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001462 * @see MdnsAdvertiser
1463 */
1464 public MdnsAdvertiser makeMdnsAdvertiser(
1465 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001466 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1467 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001468 }
1469
1470 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001471 * @see MdnsSocketProvider
1472 */
Paul Hu14667de2023-04-17 22:42:47 +08001473 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
1474 @NonNull Looper looper, @NonNull SharedLog sharedLog) {
1475 return new MdnsSocketProvider(context, looper, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001476 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001477 }
1478
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001479 /**
1480 * Return whether a type is allowlisted to use the Java backend.
1481 * @param type The service type
1482 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1483 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1484 */
1485 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1486 @NonNull String flagPrefix) {
1487 if (type == null) return false;
1488 final String typesConfig = mDeps.getTypeAllowlistFlags();
1489 if (TextUtils.isEmpty(typesConfig)) return false;
1490
1491 final String mappingPrefix = type + ":";
1492 String mappedFlag = null;
1493 for (String mapping : TextUtils.split(typesConfig, ",")) {
1494 if (mapping.startsWith(mappingPrefix)) {
1495 mappedFlag = mapping.substring(mappingPrefix.length());
1496 break;
1497 }
1498 }
1499
1500 if (mappedFlag == null) return false;
1501
1502 return mDeps.isFeatureEnabled(mContext,
1503 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1504 }
1505
1506 private boolean useDiscoveryManagerForType(@Nullable String type) {
1507 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1508 }
1509
1510 private boolean useAdvertiserForType(@Nullable String type) {
1511 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1512 }
1513
paulhu1b35e822022-04-08 14:48:41 +08001514 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001515 HandlerThread thread = new HandlerThread(TAG);
1516 thread.start();
1517 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001518 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001519 return service;
1520 }
1521
paulhu2b9ed952022-02-10 21:58:32 +08001522 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1523 private final StateMachine mStateMachine;
1524
1525 MDnsEventCallback(StateMachine sm) {
1526 mStateMachine = sm;
1527 }
1528
1529 @Override
1530 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1531 mStateMachine.sendMessage(
1532 MDNS_SERVICE_EVENT, status.result, status.id, status);
1533 }
1534
1535 @Override
1536 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1537 mStateMachine.sendMessage(
1538 MDNS_SERVICE_EVENT, status.result, status.id, status);
1539 }
1540
1541 @Override
1542 public void onServiceResolutionStatus(final ResolutionInfo status) {
1543 mStateMachine.sendMessage(
1544 MDNS_SERVICE_EVENT, status.result, status.id, status);
1545 }
1546
1547 @Override
1548 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1549 mStateMachine.sendMessage(
1550 MDNS_SERVICE_EVENT, status.result, status.id, status);
1551 }
1552
1553 @Override
1554 public int getInterfaceVersion() throws RemoteException {
1555 return this.VERSION;
1556 }
1557
1558 @Override
1559 public String getInterfaceHash() throws RemoteException {
1560 return this.HASH;
1561 }
1562 }
1563
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001564 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1565 @Override
1566 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1567 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1568 if (clientInfo == null) return;
1569
1570 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1571 if (clientId < 0) return;
1572
1573 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1574 // historical behavior.
1575 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1576 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1577 }
1578
1579 @Override
1580 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1581 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1582 if (clientInfo == null) return;
1583
1584 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1585 if (clientId < 0) return;
1586
1587 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1588 }
1589
1590 private ClientInfo getClientInfoOrLog(int serviceId) {
1591 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1592 if (clientInfo == null) {
1593 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1594 }
1595 return clientInfo;
1596 }
1597
1598 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1599 final int clientId = info.getClientId(serviceId);
1600 if (clientId < 0) {
1601 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1602 }
1603 return clientId;
1604 }
1605 }
1606
Paul Hu2e0a88c2023-03-09 16:05:01 +08001607 private static class ConnectorArgs {
1608 @NonNull public final NsdServiceConnector connector;
1609 @NonNull public final INsdManagerCallback callback;
1610 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001611 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001612
1613 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001614 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001615 this.connector = connector;
1616 this.callback = callback;
1617 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001618 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001619 }
1620 }
1621
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001622 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001623 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001625 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001626 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001627 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1628 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1629 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001630 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001631 }
1632
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001633 private static class ListenerArgs {
1634 public final NsdServiceConnector connector;
1635 public final NsdServiceInfo serviceInfo;
1636 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1637 this.connector = connector;
1638 this.serviceInfo = serviceInfo;
1639 }
1640 }
1641
1642 private class NsdServiceConnector extends INsdServiceConnector.Stub
1643 implements IBinder.DeathRecipient {
1644 @Override
1645 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1646 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1647 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1648 new ListenerArgs(this, serviceInfo)));
1649 }
1650
1651 @Override
1652 public void unregisterService(int listenerKey) {
1653 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1654 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1655 new ListenerArgs(this, null)));
1656 }
1657
1658 @Override
1659 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1660 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1661 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1662 new ListenerArgs(this, serviceInfo)));
1663 }
1664
1665 @Override
1666 public void stopDiscovery(int listenerKey) {
1667 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1668 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1669 }
1670
1671 @Override
1672 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1673 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1674 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1675 new ListenerArgs(this, serviceInfo)));
1676 }
1677
1678 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001679 public void stopResolution(int listenerKey) {
1680 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1681 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1682 }
1683
1684 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001685 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1686 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1687 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1688 new ListenerArgs(this, serviceInfo)));
1689 }
1690
1691 @Override
1692 public void unregisterServiceInfoCallback(int listenerKey) {
1693 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1694 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1695 new ListenerArgs(this, null)));
1696 }
1697
1698 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001699 public void startDaemon() {
1700 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1701 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1702 }
1703
1704 @Override
1705 public void binderDied() {
1706 mNsdStateMachine.sendMessage(
1707 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1708 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001709 }
1710
Hugo Benichi912db992017-04-24 16:41:03 +09001711 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001712 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001713 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001714 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1715 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001716 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001717 }
1718
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001719 private int getUniqueId() {
1720 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1721 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001722 }
1723
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001724 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001725 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001726 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001727 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001728 String name = service.getServiceName();
1729 String type = service.getServiceType();
1730 int port = service.getPort();
1731 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001732 final int registerInterface = getNetworkInterfaceIndex(service);
1733 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001734 Log.e(TAG, "Interface to register service on not found");
1735 return false;
1736 }
1737 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001738 }
1739
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001740 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001741 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001742 }
1743
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001744 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001745 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001746 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1747 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001748 Log.e(TAG, "Interface to discover service on not found");
1749 return false;
1750 }
paulhu2b9ed952022-02-10 21:58:32 +08001751 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001752 }
1753
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001754 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001755 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001756 }
1757
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001758 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001759 final String name = service.getServiceName();
1760 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001761 final int resolveInterface = getNetworkInterfaceIndex(service);
1762 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001763 Log.e(TAG, "Interface to resolve service on not found");
1764 return false;
1765 }
paulhu2b9ed952022-02-10 21:58:32 +08001766 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001767 }
1768
1769 /**
1770 * Guess the interface to use to resolve or discover a service on a specific network.
1771 *
1772 * This is an imperfect guess, as for example the network may be gone or not yet fully
1773 * registered. This is fine as failing is correct if the network is gone, and a client
1774 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1775 * this is to support the legacy mdnsresponder implementation, which historically resolved
1776 * services on an unspecified network.
1777 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001778 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1779 final Network network = serviceInfo.getNetwork();
1780 if (network == null) {
1781 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1782 // provided by NsdService from discovery results, and the service was found on an
1783 // interface that has no app-usable Network).
1784 if (serviceInfo.getInterfaceIndex() != 0) {
1785 return serviceInfo.getInterfaceIndex();
1786 }
1787 return IFACE_IDX_ANY;
1788 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001789
1790 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1791 if (cm == null) {
1792 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1793 return IFACE_IDX_ANY;
1794 }
1795 final LinkProperties lp = cm.getLinkProperties(network);
1796 if (lp == null) return IFACE_IDX_ANY;
1797
1798 // Only resolve on non-stacked interfaces
1799 final NetworkInterface iface;
1800 try {
1801 iface = NetworkInterface.getByName(lp.getInterfaceName());
1802 } catch (SocketException e) {
1803 Log.e(TAG, "Error querying interface", e);
1804 return IFACE_IDX_ANY;
1805 }
1806
1807 if (iface == null) {
1808 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1809 return IFACE_IDX_ANY;
1810 }
1811
1812 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001813 }
1814
1815 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001816 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001817 }
1818
paulhu2b9ed952022-02-10 21:58:32 +08001819 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1820 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001821 }
1822
1823 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001824 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001825 }
1826
1827 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001828 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1829 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001830
Paul Hub2e67d32023-04-18 05:50:14 +00001831 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1832 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001833 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001834
1835 // Dump service and clients logs
1836 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001837 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001838 pw.increaseIndent();
1839 mServiceLogs.reverseDump(pw);
1840 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001841 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001842
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001843 private abstract static class ClientRequest {
1844 private final int mGlobalId;
1845
1846 private ClientRequest(int globalId) {
1847 mGlobalId = globalId;
1848 }
1849 }
1850
1851 private static class LegacyClientRequest extends ClientRequest {
1852 private final int mRequestCode;
1853
1854 private LegacyClientRequest(int globalId, int requestCode) {
1855 super(globalId);
1856 mRequestCode = requestCode;
1857 }
1858 }
1859
1860 private static class AdvertiserClientRequest extends ClientRequest {
1861 private AdvertiserClientRequest(int globalId) {
1862 super(globalId);
1863 }
1864 }
1865
1866 private static class DiscoveryManagerRequest extends ClientRequest {
1867 @NonNull
1868 private final MdnsListener mListener;
1869
1870 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1871 super(globalId);
1872 mListener = listener;
1873 }
1874 }
1875
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001876 /* Information tracked per client */
1877 private class ClientInfo {
1878
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001879 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001880 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001881 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001882 private NsdServiceInfo mResolvedService;
1883
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001884 /* A map from client-side ID (listenerKey) to the request */
1885 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001886
Luke Huangf7277ed2021-07-12 21:15:10 +08001887 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001888 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001889 // The flag of using java backend if the client's target SDK >= U
1890 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001891 // Store client logs
1892 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001893
Paul Hub2e67d32023-04-18 05:50:14 +00001894 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001895 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001896 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001897 mClientLogs = sharedLog;
1898 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001899 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001900
1901 @Override
1902 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001903 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001904 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001905 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1906 for (int i = 0; i < mClientRequests.size(); i++) {
1907 int clientID = mClientRequests.keyAt(i);
1908 sb.append("clientId ")
1909 .append(clientID)
1910 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1911 .append(" type ").append(
1912 mClientRequests.valueAt(i).getClass().getSimpleName())
1913 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001914 }
1915 return sb.toString();
1916 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001917
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001918 private boolean isPreSClient() {
1919 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001920 }
1921
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001922 private void setPreSClient() {
1923 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001924 }
1925
Paul Hue4f5f252023-02-16 21:13:47 +08001926 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1927 final MdnsListener listener =
1928 ((DiscoveryManagerRequest) request).mListener;
1929 mMdnsDiscoveryManager.unregisterListener(
1930 listener.getListenedServiceType(), listener);
1931 }
1932
Dave Plattfeff2af2014-03-07 14:48:22 -08001933 // Remove any pending requests from the global map when we get rid of a client,
1934 // and send cancellations to the daemon.
1935 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001936 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001937 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001938 for (int i = 0; i < mClientRequests.size(); i++) {
1939 final int clientId = mClientRequests.keyAt(i);
1940 final ClientRequest request = mClientRequests.valueAt(i);
1941 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001942 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001943 if (DBG) {
1944 Log.d(TAG, "Terminating client-ID " + clientId
1945 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1946 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001947
1948 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001949 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001950 continue;
1951 }
1952
1953 if (request instanceof AdvertiserClientRequest) {
1954 mAdvertiser.removeService(globalId);
1955 continue;
1956 }
1957
1958 if (!(request instanceof LegacyClientRequest)) {
1959 throw new IllegalStateException("Unknown request type: " + request.getClass());
1960 }
1961
1962 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001963 case NsdManager.DISCOVER_SERVICES:
1964 stopServiceDiscovery(globalId);
1965 break;
1966 case NsdManager.RESOLVE_SERVICE:
1967 stopResolveService(globalId);
1968 break;
1969 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001970 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001971 break;
1972 default:
1973 break;
1974 }
1975 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001976 mClientRequests.clear();
1977 }
1978
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001979 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1980 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1981 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001982 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001983 for (int i = 0; i < mClientRequests.size(); i++) {
1984 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1985 return mClientRequests.keyAt(i);
1986 }
Christopher Lane74411222014-04-25 18:39:07 -07001987 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001988 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001989 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001990
Paul Hub2e67d32023-04-18 05:50:14 +00001991 private void log(String message) {
1992 mClientLogs.log(message);
1993 }
1994
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001995 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1996 try {
1997 mCb.onDiscoverServicesStarted(listenerKey, info);
1998 } catch (RemoteException e) {
1999 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2000 }
2001 }
2002
2003 void onDiscoverServicesFailed(int listenerKey, int error) {
2004 try {
2005 mCb.onDiscoverServicesFailed(listenerKey, error);
2006 } catch (RemoteException e) {
2007 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2008 }
2009 }
2010
2011 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2012 try {
2013 mCb.onServiceFound(listenerKey, info);
2014 } catch (RemoteException e) {
2015 Log.e(TAG, "Error calling onServiceFound(", e);
2016 }
2017 }
2018
2019 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2020 try {
2021 mCb.onServiceLost(listenerKey, info);
2022 } catch (RemoteException e) {
2023 Log.e(TAG, "Error calling onServiceLost(", e);
2024 }
2025 }
2026
2027 void onStopDiscoveryFailed(int listenerKey, int error) {
2028 try {
2029 mCb.onStopDiscoveryFailed(listenerKey, error);
2030 } catch (RemoteException e) {
2031 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2032 }
2033 }
2034
2035 void onStopDiscoverySucceeded(int listenerKey) {
2036 try {
2037 mCb.onStopDiscoverySucceeded(listenerKey);
2038 } catch (RemoteException e) {
2039 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2040 }
2041 }
2042
2043 void onRegisterServiceFailed(int listenerKey, int error) {
2044 try {
2045 mCb.onRegisterServiceFailed(listenerKey, error);
2046 } catch (RemoteException e) {
2047 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2048 }
2049 }
2050
2051 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2052 try {
2053 mCb.onRegisterServiceSucceeded(listenerKey, info);
2054 } catch (RemoteException e) {
2055 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2056 }
2057 }
2058
2059 void onUnregisterServiceFailed(int listenerKey, int error) {
2060 try {
2061 mCb.onUnregisterServiceFailed(listenerKey, error);
2062 } catch (RemoteException e) {
2063 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2064 }
2065 }
2066
2067 void onUnregisterServiceSucceeded(int listenerKey) {
2068 try {
2069 mCb.onUnregisterServiceSucceeded(listenerKey);
2070 } catch (RemoteException e) {
2071 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2072 }
2073 }
2074
2075 void onResolveServiceFailed(int listenerKey, int error) {
2076 try {
2077 mCb.onResolveServiceFailed(listenerKey, error);
2078 } catch (RemoteException e) {
2079 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2080 }
2081 }
2082
2083 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2084 try {
2085 mCb.onResolveServiceSucceeded(listenerKey, info);
2086 } catch (RemoteException e) {
2087 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2088 }
2089 }
Paul Hub58deb72022-12-26 09:24:42 +00002090
2091 void onStopResolutionFailed(int listenerKey, int error) {
2092 try {
2093 mCb.onStopResolutionFailed(listenerKey, error);
2094 } catch (RemoteException e) {
2095 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2096 }
2097 }
2098
2099 void onStopResolutionSucceeded(int listenerKey) {
2100 try {
2101 mCb.onStopResolutionSucceeded(listenerKey);
2102 } catch (RemoteException e) {
2103 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2104 }
2105 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002106
2107 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2108 try {
2109 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2110 } catch (RemoteException e) {
2111 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2112 }
2113 }
2114
2115 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2116 try {
2117 mCb.onServiceUpdated(listenerKey, info);
2118 } catch (RemoteException e) {
2119 Log.e(TAG, "Error calling onServiceUpdated", e);
2120 }
2121 }
2122
2123 void onServiceUpdatedLost(int listenerKey) {
2124 try {
2125 mCb.onServiceUpdatedLost(listenerKey);
2126 } catch (RemoteException e) {
2127 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2128 }
2129 }
2130
2131 void onServiceInfoCallbackUnregistered(int listenerKey) {
2132 try {
2133 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2134 } catch (RemoteException e) {
2135 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2136 }
2137 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002138 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002139}