blob: c136d4c69aa6e384cb6413ed0911a7697935cd22 [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;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070058import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059
paulhua262cc12019-08-12 16:25:11 +080060import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000061import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080062import com.android.internal.util.State;
63import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080064import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090065import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080066import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000067import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090069import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080070import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
71import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080072import com.android.server.connectivity.mdns.MdnsSearchOptions;
73import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
74import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080075import com.android.server.connectivity.mdns.MdnsSocketClientBase;
76import 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 VAN151d0a52023-03-03 17:50:50 +0900602 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800603 if (clientInfo.mUseJavaBackend
604 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900605 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800606 if (serviceType == null) {
607 clientInfo.onDiscoverServicesFailed(clientId,
608 NsdManager.FAILURE_INTERNAL_ERROR);
609 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700610 }
Paul Hu23fa2022023-01-13 22:57:24 +0800611
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900612 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800613 maybeStartMonitoringSockets();
614 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900615 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800616 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
617 .setNetwork(info.getNetwork())
618 .setIsPassiveMode(true)
619 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900620 mMdnsDiscoveryManager.registerListener(
621 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900622 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800623 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000624 clientInfo.log("Register a DiscoveryListener " + id
625 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700626 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800627 maybeStartDaemon();
628 if (discoverServices(id, info)) {
629 if (DBG) {
630 Log.d(TAG, "Discover " + msg.arg2 + " " + id
631 + info.getServiceType());
632 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900633 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800634 clientInfo.onDiscoverServicesStarted(clientId, info);
635 } else {
636 stopServiceDiscovery(id);
637 clientInfo.onDiscoverServicesFailed(clientId,
638 NsdManager.FAILURE_INTERNAL_ERROR);
639 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700640 }
641 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800642 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900643 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800644 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900645 args = (ListenerArgs) msg.obj;
646 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000647 // If the binder death notification for a INsdManagerCallback was received
648 // before any calls are received by NsdService, the clientInfo would be
649 // cleared and cause NPE. Add a null check here to prevent this corner case.
650 if (clientInfo == null) {
651 Log.e(TAG, "Unknown connector in stop discovery");
652 break;
653 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700654
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900655 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
656 if (request == null) {
657 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700658 break;
659 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900660 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900661 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
662 // point, so this needs to check the type of the original request to
663 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900664 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800665 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900666 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000667 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700668 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800669 removeRequestMap(clientId, id, clientInfo);
670 if (stopServiceDiscovery(id)) {
671 clientInfo.onStopDiscoverySucceeded(clientId);
672 } else {
673 clientInfo.onStopDiscoveryFailed(
674 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
675 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700676 }
677 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900678 }
679 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800680 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900681 args = (ListenerArgs) msg.obj;
682 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000683 // If the binder death notification for a INsdManagerCallback was received
684 // before any calls are received by NsdService, the clientInfo would be
685 // cleared and cause NPE. Add a null check here to prevent this corner case.
686 if (clientInfo == null) {
687 Log.e(TAG, "Unknown connector in registration");
688 break;
689 }
690
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700691 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900692 clientInfo.onRegisterServiceFailed(
693 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700694 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700695 }
696
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700697 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900698 final NsdServiceInfo serviceInfo = args.serviceInfo;
699 final String serviceType = serviceInfo.getServiceType();
700 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800701 if (clientInfo.mUseJavaBackend
702 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900703 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900704 if (registerServiceType == null) {
705 Log.e(TAG, "Invalid service type: " + serviceType);
706 clientInfo.onRegisterServiceFailed(clientId,
707 NsdManager.FAILURE_INTERNAL_ERROR);
708 break;
709 }
710 serviceInfo.setServiceType(registerServiceType);
711 serviceInfo.setServiceName(truncateServiceName(
712 serviceInfo.getServiceName()));
713
714 maybeStartMonitoringSockets();
715 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900716 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700717 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900718 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900719 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900720 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900721 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722 // Return success after mDns reports success
723 } else {
724 unregisterService(id);
725 clientInfo.onRegisterServiceFailed(
726 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
727 }
728
Irfan Sheriff75006652012-04-17 23:15:29 -0700729 }
730 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900731 }
732 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800733 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900734 args = (ListenerArgs) msg.obj;
735 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000736 // If the binder death notification for a INsdManagerCallback was received
737 // before any calls are received by NsdService, the clientInfo would be
738 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900739 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800740 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700741 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700742 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900743 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
744 if (request == null) {
745 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
746 break;
747 }
748 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900749 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900750
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900751 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
752 // so this needs to check the type of the original request to unregister
753 // instead of looking at the flag value.
754 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900755 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900756 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700757 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900758 if (unregisterService(id)) {
759 clientInfo.onUnregisterServiceSucceeded(clientId);
760 } else {
761 clientInfo.onUnregisterServiceFailed(
762 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
763 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700764 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700765 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900766 }
Paul Hu75069ed2023-01-14 00:31:09 +0800767 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800768 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900769 args = (ListenerArgs) msg.obj;
770 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000771 // If the binder death notification for a INsdManagerCallback was received
772 // before any calls are received by NsdService, the clientInfo would be
773 // cleared and cause NPE. Add a null check here to prevent this corner case.
774 if (clientInfo == null) {
775 Log.e(TAG, "Unknown connector in resolution");
776 break;
777 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700778
Paul Hu75069ed2023-01-14 00:31:09 +0800779 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700780 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900781 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800782 if (clientInfo.mUseJavaBackend
783 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900784 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800785 if (serviceType == null) {
786 clientInfo.onResolveServiceFailed(clientId,
787 NsdManager.FAILURE_INTERNAL_ERROR);
788 break;
789 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900790 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800791
792 maybeStartMonitoringSockets();
793 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900794 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800795 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
796 .setNetwork(info.getNetwork())
797 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900798 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800799 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900800 mMdnsDiscoveryManager.registerListener(
801 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900802 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000803 clientInfo.log("Register a ResolutionListener " + id
804 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700805 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800806 if (clientInfo.mResolvedService != null) {
807 clientInfo.onResolveServiceFailed(
808 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
809 break;
810 }
811
812 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900813 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800814 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900815 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800816 } else {
817 clientInfo.onResolveServiceFailed(
818 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
819 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700820 }
821 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800822 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900823 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000824 if (DBG) Log.d(TAG, "Stop service resolution");
825 args = (ListenerArgs) msg.obj;
826 clientInfo = mClients.get(args.connector);
827 // If the binder death notification for a INsdManagerCallback was received
828 // before any calls are received by NsdService, the clientInfo would be
829 // cleared and cause NPE. Add a null check here to prevent this corner case.
830 if (clientInfo == null) {
831 Log.e(TAG, "Unknown connector in stop resolution");
832 break;
833 }
834
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900835 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
836 if (request == null) {
837 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
838 break;
839 }
840 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800841 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
842 // point, so this needs to check the type of the original request to
843 // unregister instead of looking at the flag value.
844 if (request instanceof DiscoveryManagerRequest) {
845 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000846 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000847 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000848 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800849 removeRequestMap(clientId, id, clientInfo);
850 if (stopResolveService(id)) {
851 clientInfo.onStopResolutionSucceeded(clientId);
852 } else {
853 clientInfo.onStopResolutionFailed(
854 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
855 }
856 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000857 }
Paul Hub58deb72022-12-26 09:24:42 +0000858 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900859 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000860 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000861 if (DBG) Log.d(TAG, "Register a service callback");
862 args = (ListenerArgs) msg.obj;
863 clientInfo = mClients.get(args.connector);
864 // If the binder death notification for a INsdManagerCallback was received
865 // before any calls are received by NsdService, the clientInfo would be
866 // cleared and cause NPE. Add a null check here to prevent this corner case.
867 if (clientInfo == null) {
868 Log.e(TAG, "Unknown connector in callback registration");
869 break;
870 }
871
Paul Hu30bd70d2023-02-07 13:20:56 +0000872 final NsdServiceInfo info = args.serviceInfo;
873 id = getUniqueId();
874 final String serviceType = constructServiceType(info.getServiceType());
875 if (serviceType == null) {
876 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
877 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000878 break;
879 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000880 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000881
Paul Hu30bd70d2023-02-07 13:20:56 +0000882 maybeStartMonitoringSockets();
883 final MdnsListener listener =
884 new ServiceInfoListener(clientId, id, info, resolveServiceType);
885 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
886 .setNetwork(info.getNetwork())
887 .setIsPassiveMode(true)
888 .setResolveInstanceName(info.getServiceName())
889 .build();
890 mMdnsDiscoveryManager.registerListener(
891 resolveServiceType, listener, options);
892 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000893 clientInfo.log("Register a ServiceInfoListener " + id
894 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000895 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000896 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900897 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000898 if (DBG) Log.d(TAG, "Unregister a service callback");
899 args = (ListenerArgs) msg.obj;
900 clientInfo = mClients.get(args.connector);
901 // If the binder death notification for a INsdManagerCallback was received
902 // before any calls are received by NsdService, the clientInfo would be
903 // cleared and cause NPE. Add a null check here to prevent this corner case.
904 if (clientInfo == null) {
905 Log.e(TAG, "Unknown connector in callback unregistration");
906 break;
907 }
908
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900909 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
910 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000911 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900912 break;
913 }
914 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000915 if (request instanceof DiscoveryManagerRequest) {
916 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000917 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000918 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000919 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000920 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000921 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000922 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900923 }
paulhu2b9ed952022-02-10 21:58:32 +0800924 case MDNS_SERVICE_EVENT:
925 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900926 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700927 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700928 break;
Paul Hu019621e2023-01-13 23:26:49 +0800929 case MDNS_DISCOVERY_MANAGER_EVENT:
930 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
931 return NOT_HANDLED;
932 }
933 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700934 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900935 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700936 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900937 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700938 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700939
paulhu2b9ed952022-02-10 21:58:32 +0800940 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700941 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700942 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
943 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800944 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900945 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700946 }
947
948 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700949 int clientId = clientInfo.getClientId(id);
950 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700951 // This can happen because of race conditions. For example,
952 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
953 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800954 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
955 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900956 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700957 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900958 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800959 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900960 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700961 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800962 case IMDnsEventListener.SERVICE_FOUND: {
963 final DiscoveryInfo info = (DiscoveryInfo) obj;
964 final String name = info.serviceName;
965 final String type = info.registrationType;
966 servInfo = new NsdServiceInfo(name, type);
967 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900968 if (foundNetId == 0L) {
969 // Ignore services that do not have a Network: they are not usable
970 // by apps, as they would need privileged permissions to use
971 // interfaces that do not have an associated Network.
972 break;
973 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900974 if (foundNetId == INetd.DUMMY_NET_ID) {
975 // Ignore services on the dummy0 interface: they are only seen when
976 // discovering locally advertised services, and are not reachable
977 // through that interface.
978 break;
979 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900980 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900981 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700982 break;
paulhu2b9ed952022-02-10 21:58:32 +0800983 }
984 case IMDnsEventListener.SERVICE_LOST: {
985 final DiscoveryInfo info = (DiscoveryInfo) obj;
986 final String name = info.serviceName;
987 final String type = info.registrationType;
988 final int lostNetId = info.netId;
989 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900990 // The network could be set to null (netId 0) if it was torn down when the
991 // service is lost
992 // TODO: avoid returning null in that case, possibly by remembering
993 // found services on the same interface index and their network at the time
994 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900995 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700996 break;
paulhu2b9ed952022-02-10 21:58:32 +0800997 }
998 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900999 clientInfo.onDiscoverServicesFailed(
1000 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001001 break;
paulhu2b9ed952022-02-10 21:58:32 +08001002 case IMDnsEventListener.SERVICE_REGISTERED: {
1003 final RegistrationInfo info = (RegistrationInfo) obj;
1004 final String name = info.serviceName;
1005 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001006 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001007 break;
paulhu2b9ed952022-02-10 21:58:32 +08001008 }
1009 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001010 clientInfo.onRegisterServiceFailed(
1011 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001012 break;
paulhu2b9ed952022-02-10 21:58:32 +08001013 case IMDnsEventListener.SERVICE_RESOLVED: {
1014 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001015 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001016 final String fullName = info.serviceFullName;
1017 while (index < fullName.length() && fullName.charAt(index) != '.') {
1018 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001019 ++index;
1020 }
1021 ++index;
1022 }
paulhu2b9ed952022-02-10 21:58:32 +08001023 if (index >= fullName.length()) {
1024 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001025 break;
1026 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001027
paulhube186602022-04-12 07:18:23 +00001028 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001029 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 String type = rest.replace(".local.", "");
1031
Paul Hu30bd70d2023-02-07 13:20:56 +00001032 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001033 serviceInfo.setServiceName(name);
1034 serviceInfo.setServiceType(type);
1035 serviceInfo.setPort(info.port);
1036 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001037 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001038
1039 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001040 removeRequestMap(clientId, id, clientInfo);
1041
paulhu2b9ed952022-02-10 21:58:32 +08001042 final int id2 = getUniqueId();
1043 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001044 storeLegacyRequestMap(clientId, id2, clientInfo,
1045 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001046 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001047 clientInfo.onResolveServiceFailed(
1048 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1049 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001050 }
1051 break;
paulhu2b9ed952022-02-10 21:58:32 +08001052 }
1053 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001054 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001055 stopResolveService(id);
1056 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001057 clientInfo.onResolveServiceFailed(
1058 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1059 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001060 break;
paulhu2b9ed952022-02-10 21:58:32 +08001061 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001062 /* NNN resolveId errorCode */
1063 stopGetAddrInfo(id);
1064 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001065 clientInfo.onResolveServiceFailed(
1066 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1067 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001068 break;
paulhu2b9ed952022-02-10 21:58:32 +08001069 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001070 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001071 final GetAddressInfo info = (GetAddressInfo) obj;
1072 final String address = info.address;
1073 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001074 InetAddress serviceHost = null;
1075 try {
paulhu2b9ed952022-02-10 21:58:32 +08001076 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001077 } catch (UnknownHostException e) {
1078 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1079 }
1080
1081 // If the resolved service is on an interface without a network, consider it
1082 // as a failure: it would not be usable by apps as they would need
1083 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001084 if (netId != NETID_UNSET && serviceHost != null) {
1085 clientInfo.mResolvedService.setHost(serviceHost);
1086 setServiceNetworkForCallback(clientInfo.mResolvedService,
1087 netId, info.interfaceIdx);
1088 clientInfo.onResolveServiceSucceeded(
1089 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001090 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001091 clientInfo.onResolveServiceFailed(
1092 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001093 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001094 stopGetAddrInfo(id);
1095 removeRequestMap(clientId, id, clientInfo);
1096 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001097 break;
paulhu2b9ed952022-02-10 21:58:32 +08001098 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001099 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001100 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001101 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001102 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001103 }
Paul Hu019621e2023-01-13 23:26:49 +08001104
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001105 @Nullable
1106 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1107 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001108 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001109 final String[] typeArray = serviceInfo.getServiceType();
1110 final String joinedType;
1111 if (typeArray.length == 0
1112 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1113 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1114 + Arrays.toString(typeArray));
1115 return null;
1116 } else {
1117 joinedType = TextUtils.join(".",
1118 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1119 }
1120 final String serviceType;
1121 switch (code) {
1122 case NsdManager.SERVICE_FOUND:
1123 case NsdManager.SERVICE_LOST:
1124 // For consistency with historical behavior, discovered service types have
1125 // a dot at the end.
1126 serviceType = joinedType + ".";
1127 break;
1128 case RESOLVE_SERVICE_SUCCEEDED:
1129 // For consistency with historical behavior, resolved service types have
1130 // a dot at the beginning.
1131 serviceType = "." + joinedType;
1132 break;
1133 default:
1134 serviceType = joinedType;
1135 break;
1136 }
Paul Hu019621e2023-01-13 23:26:49 +08001137 final String serviceName = serviceInfo.getServiceInstanceName();
1138 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1139 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001140 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1141 // network for Tethering interface. In other words, the network == null means the
1142 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001143 setServiceNetworkForCallback(
1144 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001145 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001146 serviceInfo.getInterfaceIndex());
1147 return servInfo;
1148 }
1149
1150 private boolean handleMdnsDiscoveryManagerEvent(
1151 int transactionId, int code, Object obj) {
1152 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1153 if (clientInfo == null) {
1154 Log.e(TAG, String.format(
1155 "id %d for %d has no client mapping", transactionId, code));
1156 return false;
1157 }
1158
1159 final MdnsEvent event = (MdnsEvent) obj;
1160 final int clientId = event.mClientId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001161 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1162 // Errors are already logged if null
1163 if (info == null) return false;
Paul Hu019621e2023-01-13 23:26:49 +08001164 if (DBG) {
1165 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1166 NsdManager.nameOf(code), transactionId));
1167 }
1168 switch (code) {
1169 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001170 clientInfo.onServiceFound(clientId, info);
1171 break;
1172 case NsdManager.SERVICE_LOST:
1173 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001174 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001175 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001176 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1177 if (request == null) {
1178 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1179 break;
1180 }
Paul Hu75069ed2023-01-14 00:31:09 +08001181 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001182 info.setPort(serviceInfo.getPort());
1183
1184 Map<String, String> attrs = serviceInfo.getAttributes();
1185 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1186 final String key = kv.getKey();
1187 try {
1188 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1189 } catch (IllegalArgumentException e) {
1190 Log.e(TAG, "Invalid attribute", e);
1191 }
1192 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001193 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001194 if (addresses.size() != 0) {
1195 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001196 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001197 } else {
1198 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001199 clientInfo.onResolveServiceFailed(
1200 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1201 }
1202
1203 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001204 if (!(request instanceof DiscoveryManagerRequest)) {
1205 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1206 break;
1207 }
Paul Hue4f5f252023-02-16 21:13:47 +08001208 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001209 break;
1210 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001211 case NsdManager.SERVICE_UPDATED: {
1212 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1213 info.setPort(serviceInfo.getPort());
1214
1215 Map<String, String> attrs = serviceInfo.getAttributes();
1216 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1217 final String key = kv.getKey();
1218 try {
1219 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1220 } catch (IllegalArgumentException e) {
1221 Log.e(TAG, "Invalid attribute", e);
1222 }
1223 }
1224
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001225 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001226 info.setHostAddresses(addresses);
1227 clientInfo.onServiceUpdated(clientId, info);
1228 break;
1229 }
1230 case NsdManager.SERVICE_UPDATED_LOST:
1231 clientInfo.onServiceUpdatedLost(clientId);
1232 break;
Paul Hu019621e2023-01-13 23:26:49 +08001233 default:
1234 return false;
1235 }
1236 return true;
1237 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001238 }
1239 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001240
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001241 @NonNull
1242 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1243 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1244 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1245 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1246 for (String ipv4Address : v4Addrs) {
1247 try {
1248 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1249 } catch (IllegalArgumentException e) {
1250 Log.wtf(TAG, "Invalid ipv4 address", e);
1251 }
1252 }
1253 for (String ipv6Address : v6Addrs) {
1254 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001255 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1256 ipv6Address);
1257 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1258 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001259 Log.wtf(TAG, "Invalid ipv6 address", e);
1260 }
1261 }
1262 return addresses;
1263 }
1264
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001265 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1266 switch (netId) {
1267 case NETID_UNSET:
1268 info.setNetwork(null);
1269 break;
1270 case INetd.LOCAL_NET_ID:
1271 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1272 // visible / usable for apps, so do not return it. Store the interface
1273 // index instead, so at least if the client tries to resolve the service
1274 // with that NsdServiceInfo, it will be done on the same interface.
1275 // If they recreate the NsdServiceInfo themselves, resolution would be
1276 // done on all interfaces as before T, which should also work.
1277 info.setNetwork(null);
1278 info.setInterfaceIndex(ifaceIdx);
1279 break;
1280 default:
1281 info.setNetwork(new Network(netId));
1282 }
1283 }
1284
paulhube186602022-04-12 07:18:23 +00001285 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1286 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1287 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1288 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1289 private String unescape(String s) {
1290 StringBuilder sb = new StringBuilder(s.length());
1291 for (int i = 0; i < s.length(); ++i) {
1292 char c = s.charAt(i);
1293 if (c == '\\') {
1294 if (++i >= s.length()) {
1295 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1296 break;
1297 }
1298 c = s.charAt(i);
1299 if (c != '.' && c != '\\') {
1300 if (i + 2 >= s.length()) {
1301 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1302 break;
1303 }
1304 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1305 + (s.charAt(i + 2) - '0'));
1306 i += 2;
1307 }
1308 }
1309 sb.append(c);
1310 }
1311 return sb.toString();
1312 }
1313
Paul Hu7445e3d2023-03-03 15:14:00 +08001314 /**
1315 * Check the given service type is valid and construct it to a service type
1316 * which can use for discovery / resolution service.
1317 *
1318 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1319 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1320 * underscore; they are alphanumerical characters or dashes or underscore, except the
1321 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1322 *
1323 * @param serviceType the request service type for discovery / resolution service
1324 * @return constructed service type or null if the given service type is invalid.
1325 */
1326 @Nullable
1327 public static String constructServiceType(String serviceType) {
1328 if (TextUtils.isEmpty(serviceType)) return null;
1329
1330 final Pattern serviceTypePattern = Pattern.compile(
1331 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1332 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1333 // Drop '.' at the end of service type that is compatible with old backend.
1334 + "\\.?$");
1335 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1336 if (!matcher.matches()) return null;
1337 return matcher.group(1) == null
1338 ? matcher.group(2)
1339 : matcher.group(1) + "_sub." + matcher.group(2);
1340 }
1341
Hugo Benichi803a2f02017-04-24 11:35:06 +09001342 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001343 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001344 this(ctx, handler, cleanupDelayMs, new Dependencies());
1345 }
1346
1347 @VisibleForTesting
1348 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001349 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001350 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001351 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001352 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001353 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1354 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001355 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001356
Paul Hu14667de2023-04-17 22:42:47 +08001357 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
1358 LOGGER.forSubComponent("MdnsSocketProvider"));
Yuyang Huang700778b2023-03-08 16:17:05 +09001359 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1360 // address events are received.
1361 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001362 mMdnsSocketClient =
1363 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001364 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
1365 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001366 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1367 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001368 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001369 }
1370
1371 /**
1372 * Dependencies of NsdService, for injection in tests.
1373 */
1374 @VisibleForTesting
1375 public static class Dependencies {
1376 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001377 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001378 *
1379 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001380 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001381 */
1382 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001383 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1384 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001385 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001386 }
1387
1388 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001389 * Check whether the MdnsAdvertiser feature is enabled.
1390 *
1391 * @param context The global context information about an app environment.
1392 * @return true if the MdnsAdvertiser feature is enabled.
1393 */
1394 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001395 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1396 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1397 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001398 }
1399
1400 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001401 * Get the type allowlist flag value.
1402 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1403 */
1404 @Nullable
1405 public String getTypeAllowlistFlags() {
1406 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1407 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1408 }
1409
1410 /**
1411 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1412 */
1413 public boolean isFeatureEnabled(Context context, String feature) {
1414 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1415 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1416 }
1417
1418 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001419 * @see MdnsDiscoveryManager
1420 */
1421 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001422 @NonNull ExecutorProvider executorProvider,
1423 @NonNull MdnsSocketClientBase socketClient, @NonNull SharedLog sharedLog) {
1424 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001425 }
1426
1427 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001428 * @see MdnsAdvertiser
1429 */
1430 public MdnsAdvertiser makeMdnsAdvertiser(
1431 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001432 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1433 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001434 }
1435
1436 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001437 * @see MdnsSocketProvider
1438 */
Paul Hu14667de2023-04-17 22:42:47 +08001439 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
1440 @NonNull Looper looper, @NonNull SharedLog sharedLog) {
1441 return new MdnsSocketProvider(context, looper, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001442 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001443 }
1444
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001445 /**
1446 * Return whether a type is allowlisted to use the Java backend.
1447 * @param type The service type
1448 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1449 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1450 */
1451 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1452 @NonNull String flagPrefix) {
1453 if (type == null) return false;
1454 final String typesConfig = mDeps.getTypeAllowlistFlags();
1455 if (TextUtils.isEmpty(typesConfig)) return false;
1456
1457 final String mappingPrefix = type + ":";
1458 String mappedFlag = null;
1459 for (String mapping : TextUtils.split(typesConfig, ",")) {
1460 if (mapping.startsWith(mappingPrefix)) {
1461 mappedFlag = mapping.substring(mappingPrefix.length());
1462 break;
1463 }
1464 }
1465
1466 if (mappedFlag == null) return false;
1467
1468 return mDeps.isFeatureEnabled(mContext,
1469 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1470 }
1471
1472 private boolean useDiscoveryManagerForType(@Nullable String type) {
1473 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1474 }
1475
1476 private boolean useAdvertiserForType(@Nullable String type) {
1477 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1478 }
1479
paulhu1b35e822022-04-08 14:48:41 +08001480 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001481 HandlerThread thread = new HandlerThread(TAG);
1482 thread.start();
1483 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001484 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001485 return service;
1486 }
1487
paulhu2b9ed952022-02-10 21:58:32 +08001488 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1489 private final StateMachine mStateMachine;
1490
1491 MDnsEventCallback(StateMachine sm) {
1492 mStateMachine = sm;
1493 }
1494
1495 @Override
1496 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1497 mStateMachine.sendMessage(
1498 MDNS_SERVICE_EVENT, status.result, status.id, status);
1499 }
1500
1501 @Override
1502 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1503 mStateMachine.sendMessage(
1504 MDNS_SERVICE_EVENT, status.result, status.id, status);
1505 }
1506
1507 @Override
1508 public void onServiceResolutionStatus(final ResolutionInfo status) {
1509 mStateMachine.sendMessage(
1510 MDNS_SERVICE_EVENT, status.result, status.id, status);
1511 }
1512
1513 @Override
1514 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1515 mStateMachine.sendMessage(
1516 MDNS_SERVICE_EVENT, status.result, status.id, status);
1517 }
1518
1519 @Override
1520 public int getInterfaceVersion() throws RemoteException {
1521 return this.VERSION;
1522 }
1523
1524 @Override
1525 public String getInterfaceHash() throws RemoteException {
1526 return this.HASH;
1527 }
1528 }
1529
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001530 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1531 @Override
1532 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1533 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1534 if (clientInfo == null) return;
1535
1536 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1537 if (clientId < 0) return;
1538
1539 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1540 // historical behavior.
1541 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1542 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1543 }
1544
1545 @Override
1546 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1547 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1548 if (clientInfo == null) return;
1549
1550 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1551 if (clientId < 0) return;
1552
1553 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1554 }
1555
1556 private ClientInfo getClientInfoOrLog(int serviceId) {
1557 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1558 if (clientInfo == null) {
1559 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1560 }
1561 return clientInfo;
1562 }
1563
1564 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1565 final int clientId = info.getClientId(serviceId);
1566 if (clientId < 0) {
1567 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1568 }
1569 return clientId;
1570 }
1571 }
1572
Paul Hu2e0a88c2023-03-09 16:05:01 +08001573 private static class ConnectorArgs {
1574 @NonNull public final NsdServiceConnector connector;
1575 @NonNull public final INsdManagerCallback callback;
1576 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001577 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001578
1579 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001580 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001581 this.connector = connector;
1582 this.callback = callback;
1583 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001584 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001585 }
1586 }
1587
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001588 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001589 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001590 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001591 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001592 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001593 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1594 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1595 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001596 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001597 }
1598
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001599 private static class ListenerArgs {
1600 public final NsdServiceConnector connector;
1601 public final NsdServiceInfo serviceInfo;
1602 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1603 this.connector = connector;
1604 this.serviceInfo = serviceInfo;
1605 }
1606 }
1607
1608 private class NsdServiceConnector extends INsdServiceConnector.Stub
1609 implements IBinder.DeathRecipient {
1610 @Override
1611 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1612 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1613 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1614 new ListenerArgs(this, serviceInfo)));
1615 }
1616
1617 @Override
1618 public void unregisterService(int listenerKey) {
1619 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1620 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1621 new ListenerArgs(this, null)));
1622 }
1623
1624 @Override
1625 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1626 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1627 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1628 new ListenerArgs(this, serviceInfo)));
1629 }
1630
1631 @Override
1632 public void stopDiscovery(int listenerKey) {
1633 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1634 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1635 }
1636
1637 @Override
1638 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1639 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1640 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1641 new ListenerArgs(this, serviceInfo)));
1642 }
1643
1644 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001645 public void stopResolution(int listenerKey) {
1646 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1647 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1648 }
1649
1650 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001651 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1652 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1653 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1654 new ListenerArgs(this, serviceInfo)));
1655 }
1656
1657 @Override
1658 public void unregisterServiceInfoCallback(int listenerKey) {
1659 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1660 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1661 new ListenerArgs(this, null)));
1662 }
1663
1664 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001665 public void startDaemon() {
1666 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1667 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1668 }
1669
1670 @Override
1671 public void binderDied() {
1672 mNsdStateMachine.sendMessage(
1673 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1674 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001675 }
1676
Hugo Benichi912db992017-04-24 16:41:03 +09001677 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001678 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001679 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001680 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1681 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001682 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001683 }
1684
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001685 private int getUniqueId() {
1686 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1687 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001688 }
1689
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001690 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001691 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001692 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001693 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001694 String name = service.getServiceName();
1695 String type = service.getServiceType();
1696 int port = service.getPort();
1697 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001698 final int registerInterface = getNetworkInterfaceIndex(service);
1699 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001700 Log.e(TAG, "Interface to register service on not found");
1701 return false;
1702 }
1703 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001704 }
1705
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001706 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001707 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001708 }
1709
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001710 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001711 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001712 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1713 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001714 Log.e(TAG, "Interface to discover service on not found");
1715 return false;
1716 }
paulhu2b9ed952022-02-10 21:58:32 +08001717 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001718 }
1719
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001720 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001721 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001722 }
1723
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001724 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001725 final String name = service.getServiceName();
1726 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001727 final int resolveInterface = getNetworkInterfaceIndex(service);
1728 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001729 Log.e(TAG, "Interface to resolve service on not found");
1730 return false;
1731 }
paulhu2b9ed952022-02-10 21:58:32 +08001732 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001733 }
1734
1735 /**
1736 * Guess the interface to use to resolve or discover a service on a specific network.
1737 *
1738 * This is an imperfect guess, as for example the network may be gone or not yet fully
1739 * registered. This is fine as failing is correct if the network is gone, and a client
1740 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1741 * this is to support the legacy mdnsresponder implementation, which historically resolved
1742 * services on an unspecified network.
1743 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001744 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1745 final Network network = serviceInfo.getNetwork();
1746 if (network == null) {
1747 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1748 // provided by NsdService from discovery results, and the service was found on an
1749 // interface that has no app-usable Network).
1750 if (serviceInfo.getInterfaceIndex() != 0) {
1751 return serviceInfo.getInterfaceIndex();
1752 }
1753 return IFACE_IDX_ANY;
1754 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001755
1756 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1757 if (cm == null) {
1758 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1759 return IFACE_IDX_ANY;
1760 }
1761 final LinkProperties lp = cm.getLinkProperties(network);
1762 if (lp == null) return IFACE_IDX_ANY;
1763
1764 // Only resolve on non-stacked interfaces
1765 final NetworkInterface iface;
1766 try {
1767 iface = NetworkInterface.getByName(lp.getInterfaceName());
1768 } catch (SocketException e) {
1769 Log.e(TAG, "Error querying interface", e);
1770 return IFACE_IDX_ANY;
1771 }
1772
1773 if (iface == null) {
1774 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1775 return IFACE_IDX_ANY;
1776 }
1777
1778 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001779 }
1780
1781 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001782 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001783 }
1784
paulhu2b9ed952022-02-10 21:58:32 +08001785 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1786 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001787 }
1788
1789 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001790 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001791 }
1792
1793 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001794 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1795 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001796
Paul Hub2e67d32023-04-18 05:50:14 +00001797 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1798 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001799 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001800
1801 // Dump service and clients logs
1802 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001803 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001804 pw.increaseIndent();
1805 mServiceLogs.reverseDump(pw);
1806 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001807 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001808
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001809 private abstract static class ClientRequest {
1810 private final int mGlobalId;
1811
1812 private ClientRequest(int globalId) {
1813 mGlobalId = globalId;
1814 }
1815 }
1816
1817 private static class LegacyClientRequest extends ClientRequest {
1818 private final int mRequestCode;
1819
1820 private LegacyClientRequest(int globalId, int requestCode) {
1821 super(globalId);
1822 mRequestCode = requestCode;
1823 }
1824 }
1825
1826 private static class AdvertiserClientRequest extends ClientRequest {
1827 private AdvertiserClientRequest(int globalId) {
1828 super(globalId);
1829 }
1830 }
1831
1832 private static class DiscoveryManagerRequest extends ClientRequest {
1833 @NonNull
1834 private final MdnsListener mListener;
1835
1836 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1837 super(globalId);
1838 mListener = listener;
1839 }
1840 }
1841
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001842 /* Information tracked per client */
1843 private class ClientInfo {
1844
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001845 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001846 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001847 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001848 private NsdServiceInfo mResolvedService;
1849
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001850 /* A map from client-side ID (listenerKey) to the request */
1851 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001852
Luke Huangf7277ed2021-07-12 21:15:10 +08001853 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001854 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001855 // The flag of using java backend if the client's target SDK >= U
1856 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001857 // Store client logs
1858 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001859
Paul Hub2e67d32023-04-18 05:50:14 +00001860 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001861 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001862 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001863 mClientLogs = sharedLog;
1864 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001865 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001866
1867 @Override
1868 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001869 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001870 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001871 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1872 for (int i = 0; i < mClientRequests.size(); i++) {
1873 int clientID = mClientRequests.keyAt(i);
1874 sb.append("clientId ")
1875 .append(clientID)
1876 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1877 .append(" type ").append(
1878 mClientRequests.valueAt(i).getClass().getSimpleName())
1879 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001880 }
1881 return sb.toString();
1882 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001883
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001884 private boolean isPreSClient() {
1885 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001886 }
1887
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001888 private void setPreSClient() {
1889 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001890 }
1891
Paul Hue4f5f252023-02-16 21:13:47 +08001892 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1893 final MdnsListener listener =
1894 ((DiscoveryManagerRequest) request).mListener;
1895 mMdnsDiscoveryManager.unregisterListener(
1896 listener.getListenedServiceType(), listener);
1897 }
1898
Dave Plattfeff2af2014-03-07 14:48:22 -08001899 // Remove any pending requests from the global map when we get rid of a client,
1900 // and send cancellations to the daemon.
1901 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001902 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001903 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001904 for (int i = 0; i < mClientRequests.size(); i++) {
1905 final int clientId = mClientRequests.keyAt(i);
1906 final ClientRequest request = mClientRequests.valueAt(i);
1907 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001908 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001909 if (DBG) {
1910 Log.d(TAG, "Terminating client-ID " + clientId
1911 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1912 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001913
1914 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001915 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001916 continue;
1917 }
1918
1919 if (request instanceof AdvertiserClientRequest) {
1920 mAdvertiser.removeService(globalId);
1921 continue;
1922 }
1923
1924 if (!(request instanceof LegacyClientRequest)) {
1925 throw new IllegalStateException("Unknown request type: " + request.getClass());
1926 }
1927
1928 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001929 case NsdManager.DISCOVER_SERVICES:
1930 stopServiceDiscovery(globalId);
1931 break;
1932 case NsdManager.RESOLVE_SERVICE:
1933 stopResolveService(globalId);
1934 break;
1935 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001936 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001937 break;
1938 default:
1939 break;
1940 }
1941 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001942 mClientRequests.clear();
1943 }
1944
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001945 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1946 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1947 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001948 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001949 for (int i = 0; i < mClientRequests.size(); i++) {
1950 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1951 return mClientRequests.keyAt(i);
1952 }
Christopher Lane74411222014-04-25 18:39:07 -07001953 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001954 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001955 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001956
Paul Hub2e67d32023-04-18 05:50:14 +00001957 private void log(String message) {
1958 mClientLogs.log(message);
1959 }
1960
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001961 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1962 try {
1963 mCb.onDiscoverServicesStarted(listenerKey, info);
1964 } catch (RemoteException e) {
1965 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1966 }
1967 }
1968
1969 void onDiscoverServicesFailed(int listenerKey, int error) {
1970 try {
1971 mCb.onDiscoverServicesFailed(listenerKey, error);
1972 } catch (RemoteException e) {
1973 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1974 }
1975 }
1976
1977 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1978 try {
1979 mCb.onServiceFound(listenerKey, info);
1980 } catch (RemoteException e) {
1981 Log.e(TAG, "Error calling onServiceFound(", e);
1982 }
1983 }
1984
1985 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1986 try {
1987 mCb.onServiceLost(listenerKey, info);
1988 } catch (RemoteException e) {
1989 Log.e(TAG, "Error calling onServiceLost(", e);
1990 }
1991 }
1992
1993 void onStopDiscoveryFailed(int listenerKey, int error) {
1994 try {
1995 mCb.onStopDiscoveryFailed(listenerKey, error);
1996 } catch (RemoteException e) {
1997 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1998 }
1999 }
2000
2001 void onStopDiscoverySucceeded(int listenerKey) {
2002 try {
2003 mCb.onStopDiscoverySucceeded(listenerKey);
2004 } catch (RemoteException e) {
2005 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2006 }
2007 }
2008
2009 void onRegisterServiceFailed(int listenerKey, int error) {
2010 try {
2011 mCb.onRegisterServiceFailed(listenerKey, error);
2012 } catch (RemoteException e) {
2013 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2014 }
2015 }
2016
2017 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2018 try {
2019 mCb.onRegisterServiceSucceeded(listenerKey, info);
2020 } catch (RemoteException e) {
2021 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2022 }
2023 }
2024
2025 void onUnregisterServiceFailed(int listenerKey, int error) {
2026 try {
2027 mCb.onUnregisterServiceFailed(listenerKey, error);
2028 } catch (RemoteException e) {
2029 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2030 }
2031 }
2032
2033 void onUnregisterServiceSucceeded(int listenerKey) {
2034 try {
2035 mCb.onUnregisterServiceSucceeded(listenerKey);
2036 } catch (RemoteException e) {
2037 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2038 }
2039 }
2040
2041 void onResolveServiceFailed(int listenerKey, int error) {
2042 try {
2043 mCb.onResolveServiceFailed(listenerKey, error);
2044 } catch (RemoteException e) {
2045 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2046 }
2047 }
2048
2049 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2050 try {
2051 mCb.onResolveServiceSucceeded(listenerKey, info);
2052 } catch (RemoteException e) {
2053 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2054 }
2055 }
Paul Hub58deb72022-12-26 09:24:42 +00002056
2057 void onStopResolutionFailed(int listenerKey, int error) {
2058 try {
2059 mCb.onStopResolutionFailed(listenerKey, error);
2060 } catch (RemoteException e) {
2061 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2062 }
2063 }
2064
2065 void onStopResolutionSucceeded(int listenerKey) {
2066 try {
2067 mCb.onStopResolutionSucceeded(listenerKey);
2068 } catch (RemoteException e) {
2069 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2070 }
2071 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002072
2073 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2074 try {
2075 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2076 } catch (RemoteException e) {
2077 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2078 }
2079 }
2080
2081 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2082 try {
2083 mCb.onServiceUpdated(listenerKey, info);
2084 } catch (RemoteException e) {
2085 Log.e(TAG, "Error calling onServiceUpdated", e);
2086 }
2087 }
2088
2089 void onServiceUpdatedLost(int listenerKey) {
2090 try {
2091 mCb.onServiceUpdatedLost(listenerKey);
2092 } catch (RemoteException e) {
2093 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2094 }
2095 }
2096
2097 void onServiceInfoCallbackUnregistered(int listenerKey) {
2098 try {
2099 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2100 } catch (RemoteException e) {
2101 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2102 }
2103 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002104 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002105}