blob: a6587912230305659d82d98c44ffa44db32aef8c [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;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
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;
26
Paul Hu23fa2022023-01-13 22:57:24 +080027import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080028import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080029import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070030import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090032import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080033import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090034import android.net.LinkProperties;
35import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080036import android.net.mdns.aidl.DiscoveryInfo;
37import android.net.mdns.aidl.GetAddressInfo;
38import android.net.mdns.aidl.IMDnsEventListener;
39import android.net.mdns.aidl.RegistrationInfo;
40import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070041import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090042import android.net.nsd.INsdManagerCallback;
43import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080044import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080046import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090047import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080048import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090049import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080050import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070051import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070053import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080054import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.util.Log;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070056import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080059import com.android.internal.util.State;
60import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080062import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090064import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
66import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080067import com.android.server.connectivity.mdns.MdnsSearchOptions;
68import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
69import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080070import com.android.server.connectivity.mdns.MdnsSocketClientBase;
71import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080072
Irfan Sheriff77ec5582012-03-22 17:01:39 -070073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090075import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070076import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090077import java.net.NetworkInterface;
78import java.net.SocketException;
79import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090080import java.nio.ByteBuffer;
81import java.nio.CharBuffer;
82import java.nio.charset.Charset;
83import java.nio.charset.CharsetEncoder;
84import java.nio.charset.StandardCharsets;
Paul Hu2b865912023-03-06 14:27:53 +080085import java.util.ArrayList;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070086import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080087import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080088import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080089import java.util.regex.Matcher;
90import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070091
Irfan Sheriff77ec5582012-03-22 17:01:39 -070092/**
93 * Network Service Discovery Service handles remote service discovery operation requests by
94 * implementing the INsdManager interface.
95 *
96 * @hide
97 */
98public class NsdService extends INsdManager.Stub {
99 private static final String TAG = "NsdService";
100 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900101 /**
102 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
103 * implementation.
104 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800105 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800106 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900107 // Max label length as per RFC 1034/1035
108 private static final int MAX_LABEL_LENGTH = 63;
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;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700147
Hugo Benichi32be63d2017-04-05 14:06:11 +0900148 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900149 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800150 private final MDnsManager mMDnsManager;
151 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900152 @NonNull
153 private final Dependencies mDeps;
154 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800155 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900156 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800157 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900158 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800159 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900160 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900161 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800162 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800163 // state machine thread. If change this outside state machine, it will need to introduce
164 // synchronization.
165 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800166 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700167
168 /**
169 * Clients receiving asynchronous messages
170 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900171 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700172
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700173 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900174 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700175
Luke Huang05298582021-06-13 16:52:05 +0000176 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700177
Hugo Benichi32be63d2017-04-05 14:06:11 +0900178 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700179 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800180 // The count of the connected legacy clients.
181 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700182
Paul Hu23fa2022023-01-13 22:57:24 +0800183 private static class MdnsListener implements MdnsServiceBrowserListener {
184 protected final int mClientId;
185 protected final int mTransactionId;
186 @NonNull
187 protected final NsdServiceInfo mReqServiceInfo;
188 @NonNull
189 protected final String mListenedServiceType;
190
191 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
192 @NonNull String listenedServiceType) {
193 mClientId = clientId;
194 mTransactionId = transactionId;
195 mReqServiceInfo = reqServiceInfo;
196 mListenedServiceType = listenedServiceType;
197 }
198
199 @NonNull
200 public String getListenedServiceType() {
201 return mListenedServiceType;
202 }
203
204 @Override
205 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
206
207 @Override
208 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
209
210 @Override
211 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
212
213 @Override
214 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
215
216 @Override
217 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
218
219 @Override
220 public void onSearchStoppedWithError(int error) { }
221
222 @Override
223 public void onSearchFailedToStart() { }
224
225 @Override
226 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
227
228 @Override
229 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
230 }
231
232 private class DiscoveryListener extends MdnsListener {
233
234 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
235 @NonNull String listenServiceType) {
236 super(clientId, transactionId, reqServiceInfo, listenServiceType);
237 }
238
239 @Override
240 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800241 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
242 NsdManager.SERVICE_FOUND,
243 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800244 }
245
246 @Override
247 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800248 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
249 NsdManager.SERVICE_LOST,
250 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800251 }
252 }
253
Paul Hu75069ed2023-01-14 00:31:09 +0800254 private class ResolutionListener extends MdnsListener {
255
256 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
257 @NonNull String listenServiceType) {
258 super(clientId, transactionId, reqServiceInfo, listenServiceType);
259 }
260
261 @Override
262 public void onServiceFound(MdnsServiceInfo serviceInfo) {
263 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
264 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
265 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
266 }
267 }
268
Paul Hu30bd70d2023-02-07 13:20:56 +0000269 private class ServiceInfoListener extends MdnsListener {
270
271 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
272 @NonNull String listenServiceType) {
273 super(clientId, transactionId, reqServiceInfo, listenServiceType);
274 }
275
276 @Override
277 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
278 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
279 NsdManager.SERVICE_UPDATED,
280 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
281 }
282
283 @Override
284 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
285 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
286 NsdManager.SERVICE_UPDATED,
287 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
288 }
289
290 @Override
291 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
292 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
293 NsdManager.SERVICE_UPDATED_LOST,
294 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
295 }
296 }
297
Paul Hu019621e2023-01-13 23:26:49 +0800298 /**
299 * Data class of mdns service callback information.
300 */
301 private static class MdnsEvent {
302 final int mClientId;
303 @NonNull
304 final String mRequestedServiceType;
305 @NonNull
306 final MdnsServiceInfo mMdnsServiceInfo;
307
308 MdnsEvent(int clientId, @NonNull String requestedServiceType,
309 @NonNull MdnsServiceInfo mdnsServiceInfo) {
310 mClientId = clientId;
311 mRequestedServiceType = requestedServiceType;
312 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();
335 }
336
paulhu2b9ed952022-02-10 21:58:32 +0800337 private void maybeStopDaemon() {
338 if (!mIsDaemonStarted) {
339 if (DBG) Log.d(TAG, "Daemon has not been started.");
340 return;
341 }
342 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
343 mMDnsManager.stopDaemon();
344 mIsDaemonStarted = false;
345 }
346
Luke Huang92860f92021-06-23 06:29:30 +0000347 private boolean isAnyRequestActive() {
348 return mIdToClientInfoMap.size() != 0;
349 }
350
351 private void scheduleStop() {
352 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
353 }
354 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800355 // The native daemon should stay alive and can't be cleanup
356 // if any legacy client connected.
357 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000358 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000359 }
360 }
361
Luke Huang92860f92021-06-23 06:29:30 +0000362 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000363 this.removeMessages(NsdManager.DAEMON_CLEANUP);
364 }
365
Paul Hu23fa2022023-01-13 22:57:24 +0800366 private void maybeStartMonitoringSockets() {
367 if (mIsMonitoringSocketsStarted) {
368 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
369 return;
370 }
371
372 mMdnsSocketProvider.startMonitoringSockets();
373 mIsMonitoringSocketsStarted = true;
374 }
375
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900376 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
377 if (!mIsMonitoringSocketsStarted) return;
378 if (isAnyRequestActive()) return;
379
Paul Hu58f20602023-02-18 11:41:07 +0800380 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800381 mIsMonitoringSocketsStarted = false;
382 }
383
Hugo Benichi803a2f02017-04-24 11:35:06 +0900384 NsdStateMachine(String name, Handler handler) {
385 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700386 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700387 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800388 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900389 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700390 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700391 }
392
393 class DefaultState extends State {
394 @Override
395 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900396 final ClientInfo cInfo;
397 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700398 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900399 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800400 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
401 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900402 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800403 cb.asBinder().linkToDeath(arg.connector, 0);
404 cInfo = new ClientInfo(cb, arg.useJavaBackend);
405 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900406 } catch (RemoteException e) {
407 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700408 }
409 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900410 case NsdManager.UNREGISTER_CLIENT:
411 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
412 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800413 if (cInfo != null) {
414 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900415 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800416 mLegacyClientCount -= 1;
417 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800418 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900419 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800420 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700421 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700422 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900423 cInfo = getClientInfoForReply(msg);
424 if (cInfo != null) {
425 cInfo.onDiscoverServicesFailed(
426 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
427 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700428 break;
429 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900430 cInfo = getClientInfoForReply(msg);
431 if (cInfo != null) {
432 cInfo.onStopDiscoveryFailed(
433 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
434 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700435 break;
436 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900437 cInfo = getClientInfoForReply(msg);
438 if (cInfo != null) {
439 cInfo.onRegisterServiceFailed(
440 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
441 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700442 break;
443 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900444 cInfo = getClientInfoForReply(msg);
445 if (cInfo != null) {
446 cInfo.onUnregisterServiceFailed(
447 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
448 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700449 break;
450 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900451 cInfo = getClientInfoForReply(msg);
452 if (cInfo != null) {
453 cInfo.onResolveServiceFailed(
454 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
455 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700456 break;
Paul Hub58deb72022-12-26 09:24:42 +0000457 case NsdManager.STOP_RESOLUTION:
458 cInfo = getClientInfoForReply(msg);
459 if (cInfo != null) {
460 cInfo.onStopResolutionFailed(
461 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
462 }
463 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000464 case NsdManager.REGISTER_SERVICE_CALLBACK:
465 cInfo = getClientInfoForReply(msg);
466 if (cInfo != null) {
467 cInfo.onServiceInfoCallbackRegistrationFailed(
468 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
469 }
470 break;
Luke Huang05298582021-06-13 16:52:05 +0000471 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800472 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000473 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800474 // This event should be only sent by the legacy (target SDK < S) clients.
475 // Mark the sending client as legacy.
476 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900477 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800478 if (cInfo != null) {
479 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900480 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800481 mLegacyClientCount += 1;
482 maybeStartDaemon();
483 }
484 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700485 default:
paulhub2225702021-11-17 09:35:33 +0800486 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700487 return NOT_HANDLED;
488 }
489 return HANDLED;
490 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900491
492 private ClientInfo getClientInfoForReply(Message msg) {
493 final ListenerArgs args = (ListenerArgs) msg.obj;
494 return mClients.get(args.connector);
495 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700496 }
497
Irfan Sheriff75006652012-04-17 23:15:29 -0700498 class EnabledState extends State {
499 @Override
500 public void enter() {
501 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700502 }
503
504 @Override
505 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000506 // TODO: it is incorrect to stop the daemon without expunging all requests
507 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000508 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700509 }
510
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700511 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900512 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800513 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700514 return true;
515 }
516 return false;
517 }
518
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900519 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
520 int what) {
521 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700522 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000523 // Remove the cleanup event because here comes a new request.
524 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700525 }
526
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900527 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800528 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900529 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
530 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800531 }
532
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900533 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
534 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
535 if (existing == null) return;
536 clientInfo.mClientRequests.remove(clientId);
537 mIdToClientInfoMap.remove(globalId);
538
539 if (existing instanceof LegacyClientRequest) {
540 maybeScheduleStop();
541 } else {
542 maybeStopMonitoringSocketsIfNoActiveRequest();
543 }
544 }
545
546 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
547 MdnsListener listener, ClientInfo clientInfo) {
548 clientInfo.mClientRequests.put(clientId,
549 new DiscoveryManagerRequest(globalId, listener));
550 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800551 }
552
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900553 /**
554 * Truncate a service name to up to 63 UTF-8 bytes.
555 *
556 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
557 * names used in registerService follows historical behavior (see mdnsresponder
558 * handle_regservice_request).
559 */
560 @NonNull
561 private String truncateServiceName(@NonNull String originalName) {
562 // UTF-8 is at most 4 bytes per character; return early in the common case where
563 // the name can't possibly be over the limit given its string length.
564 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
565
566 final Charset utf8 = StandardCharsets.UTF_8;
567 final CharsetEncoder encoder = utf8.newEncoder();
568 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
569 // encode will write as many characters as possible to the out buffer, and just
570 // return an overflow code if there were too many characters (no need to check the
571 // return code here, this method truncates the name on purpose).
572 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
573 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800574 }
575
Paul Hue4f5f252023-02-16 21:13:47 +0800576 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
577 ClientInfo clientInfo) {
578 clientInfo.unregisterMdnsListenerFromRequest(request);
579 removeRequestMap(clientId, id, clientInfo);
580 }
581
Irfan Sheriff75006652012-04-17 23:15:29 -0700582 @Override
583 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900584 final ClientInfo clientInfo;
585 final int id;
586 final int clientId = msg.arg2;
587 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700588 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800589 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800590 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900591 args = (ListenerArgs) msg.obj;
592 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000593 // If the binder death notification for a INsdManagerCallback was received
594 // before any calls are received by NsdService, the clientInfo would be
595 // cleared and cause NPE. Add a null check here to prevent this corner case.
596 if (clientInfo == null) {
597 Log.e(TAG, "Unknown connector in discovery");
598 break;
599 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700600
601 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 clientInfo.onDiscoverServicesFailed(
603 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700604 break;
605 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700606
Paul Hu23fa2022023-01-13 22:57:24 +0800607 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700608 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900609 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800610 if (clientInfo.mUseJavaBackend
611 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900612 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800613 if (serviceType == null) {
614 clientInfo.onDiscoverServicesFailed(clientId,
615 NsdManager.FAILURE_INTERNAL_ERROR);
616 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617 }
Paul Hu23fa2022023-01-13 22:57:24 +0800618
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900619 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800620 maybeStartMonitoringSockets();
621 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900622 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800623 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
624 .setNetwork(info.getNetwork())
625 .setIsPassiveMode(true)
626 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900627 mMdnsDiscoveryManager.registerListener(
628 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900629 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800630 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700631 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800632 maybeStartDaemon();
633 if (discoverServices(id, info)) {
634 if (DBG) {
635 Log.d(TAG, "Discover " + msg.arg2 + " " + id
636 + info.getServiceType());
637 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900638 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800639 clientInfo.onDiscoverServicesStarted(clientId, info);
640 } else {
641 stopServiceDiscovery(id);
642 clientInfo.onDiscoverServicesFailed(clientId,
643 NsdManager.FAILURE_INTERNAL_ERROR);
644 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700645 }
646 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800647 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900648 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800649 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900650 args = (ListenerArgs) msg.obj;
651 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000652 // If the binder death notification for a INsdManagerCallback was received
653 // before any calls are received by NsdService, the clientInfo would be
654 // cleared and cause NPE. Add a null check here to prevent this corner case.
655 if (clientInfo == null) {
656 Log.e(TAG, "Unknown connector in stop discovery");
657 break;
658 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700659
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900660 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
661 if (request == null) {
662 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700663 break;
664 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900665 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900666 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
667 // point, so this needs to check the type of the original request to
668 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900669 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800670 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900671 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700672 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800673 removeRequestMap(clientId, id, clientInfo);
674 if (stopServiceDiscovery(id)) {
675 clientInfo.onStopDiscoverySucceeded(clientId);
676 } else {
677 clientInfo.onStopDiscoveryFailed(
678 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
679 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700680 }
681 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900682 }
683 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800684 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900685 args = (ListenerArgs) msg.obj;
686 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000687 // If the binder death notification for a INsdManagerCallback was received
688 // before any calls are received by NsdService, the clientInfo would be
689 // cleared and cause NPE. Add a null check here to prevent this corner case.
690 if (clientInfo == null) {
691 Log.e(TAG, "Unknown connector in registration");
692 break;
693 }
694
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700695 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900696 clientInfo.onRegisterServiceFailed(
697 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700698 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700699 }
700
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700701 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900702 final NsdServiceInfo serviceInfo = args.serviceInfo;
703 final String serviceType = serviceInfo.getServiceType();
704 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800705 if (clientInfo.mUseJavaBackend
706 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900707 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900708 if (registerServiceType == null) {
709 Log.e(TAG, "Invalid service type: " + serviceType);
710 clientInfo.onRegisterServiceFailed(clientId,
711 NsdManager.FAILURE_INTERNAL_ERROR);
712 break;
713 }
714 serviceInfo.setServiceType(registerServiceType);
715 serviceInfo.setServiceName(truncateServiceName(
716 serviceInfo.getServiceName()));
717
718 maybeStartMonitoringSockets();
719 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900720 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700721 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900723 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900724 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900725 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900726 // Return success after mDns reports success
727 } else {
728 unregisterService(id);
729 clientInfo.onRegisterServiceFailed(
730 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
731 }
732
Irfan Sheriff75006652012-04-17 23:15:29 -0700733 }
734 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900735 }
736 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800737 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900738 args = (ListenerArgs) msg.obj;
739 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000740 // If the binder death notification for a INsdManagerCallback was received
741 // before any calls are received by NsdService, the clientInfo would be
742 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900743 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800744 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700745 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700746 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900747 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
748 if (request == null) {
749 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
750 break;
751 }
752 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900753 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900754
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900755 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
756 // so this needs to check the type of the original request to unregister
757 // instead of looking at the flag value.
758 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900759 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900760 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700761 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900762 if (unregisterService(id)) {
763 clientInfo.onUnregisterServiceSucceeded(clientId);
764 } else {
765 clientInfo.onUnregisterServiceFailed(
766 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
767 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700768 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700769 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900770 }
Paul Hu75069ed2023-01-14 00:31:09 +0800771 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800772 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900773 args = (ListenerArgs) msg.obj;
774 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000775 // If the binder death notification for a INsdManagerCallback was received
776 // before any calls are received by NsdService, the clientInfo would be
777 // cleared and cause NPE. Add a null check here to prevent this corner case.
778 if (clientInfo == null) {
779 Log.e(TAG, "Unknown connector in resolution");
780 break;
781 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700782
Paul Hu75069ed2023-01-14 00:31:09 +0800783 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700784 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900785 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800786 if (clientInfo.mUseJavaBackend
787 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900788 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800789 if (serviceType == null) {
790 clientInfo.onResolveServiceFailed(clientId,
791 NsdManager.FAILURE_INTERNAL_ERROR);
792 break;
793 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900794 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800795
796 maybeStartMonitoringSockets();
797 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900798 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800799 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
800 .setNetwork(info.getNetwork())
801 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900802 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800803 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900804 mMdnsDiscoveryManager.registerListener(
805 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900806 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700807 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800808 if (clientInfo.mResolvedService != null) {
809 clientInfo.onResolveServiceFailed(
810 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
811 break;
812 }
813
814 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900815 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800816 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800818 } else {
819 clientInfo.onResolveServiceFailed(
820 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
821 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 }
823 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800824 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900825 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000826 if (DBG) Log.d(TAG, "Stop service resolution");
827 args = (ListenerArgs) msg.obj;
828 clientInfo = mClients.get(args.connector);
829 // If the binder death notification for a INsdManagerCallback was received
830 // before any calls are received by NsdService, the clientInfo would be
831 // cleared and cause NPE. Add a null check here to prevent this corner case.
832 if (clientInfo == null) {
833 Log.e(TAG, "Unknown connector in stop resolution");
834 break;
835 }
836
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900837 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
838 if (request == null) {
839 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
840 break;
841 }
842 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800843 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
844 // point, so this needs to check the type of the original request to
845 // unregister instead of looking at the flag value.
846 if (request instanceof DiscoveryManagerRequest) {
847 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000848 clientInfo.onStopResolutionSucceeded(clientId);
849 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800850 removeRequestMap(clientId, id, clientInfo);
851 if (stopResolveService(id)) {
852 clientInfo.onStopResolutionSucceeded(clientId);
853 } else {
854 clientInfo.onStopResolutionFailed(
855 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
856 }
857 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000858 }
Paul Hub58deb72022-12-26 09:24:42 +0000859 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900860 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000861 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000862 if (DBG) Log.d(TAG, "Register a service callback");
863 args = (ListenerArgs) msg.obj;
864 clientInfo = mClients.get(args.connector);
865 // If the binder death notification for a INsdManagerCallback was received
866 // before any calls are received by NsdService, the clientInfo would be
867 // cleared and cause NPE. Add a null check here to prevent this corner case.
868 if (clientInfo == null) {
869 Log.e(TAG, "Unknown connector in callback registration");
870 break;
871 }
872
Paul Hu30bd70d2023-02-07 13:20:56 +0000873 final NsdServiceInfo info = args.serviceInfo;
874 id = getUniqueId();
875 final String serviceType = constructServiceType(info.getServiceType());
876 if (serviceType == null) {
877 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
878 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000879 break;
880 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000881 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000882
Paul Hu30bd70d2023-02-07 13:20:56 +0000883 maybeStartMonitoringSockets();
884 final MdnsListener listener =
885 new ServiceInfoListener(clientId, id, info, resolveServiceType);
886 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
887 .setNetwork(info.getNetwork())
888 .setIsPassiveMode(true)
889 .setResolveInstanceName(info.getServiceName())
890 .build();
891 mMdnsDiscoveryManager.registerListener(
892 resolveServiceType, listener, options);
893 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000894 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000895 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900896 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000897 if (DBG) Log.d(TAG, "Unregister a service callback");
898 args = (ListenerArgs) msg.obj;
899 clientInfo = mClients.get(args.connector);
900 // If the binder death notification for a INsdManagerCallback was received
901 // before any calls are received by NsdService, the clientInfo would be
902 // cleared and cause NPE. Add a null check here to prevent this corner case.
903 if (clientInfo == null) {
904 Log.e(TAG, "Unknown connector in callback unregistration");
905 break;
906 }
907
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900908 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
909 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000910 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900911 break;
912 }
913 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000914 if (request instanceof DiscoveryManagerRequest) {
915 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000916 clientInfo.onServiceInfoCallbackUnregistered(clientId);
917 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000918 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000919 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000920 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900921 }
paulhu2b9ed952022-02-10 21:58:32 +0800922 case MDNS_SERVICE_EVENT:
923 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900924 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700925 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700926 break;
Paul Hu019621e2023-01-13 23:26:49 +0800927 case MDNS_DISCOVERY_MANAGER_EVENT:
928 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
929 return NOT_HANDLED;
930 }
931 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700932 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900933 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700934 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900935 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700936 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700937
paulhu2b9ed952022-02-10 21:58:32 +0800938 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700939 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700940 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
941 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800942 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900943 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700944 }
945
946 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700947 int clientId = clientInfo.getClientId(id);
948 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700949 // This can happen because of race conditions. For example,
950 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
951 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800952 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
953 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900954 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700955 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900956 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800957 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900958 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700959 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800960 case IMDnsEventListener.SERVICE_FOUND: {
961 final DiscoveryInfo info = (DiscoveryInfo) obj;
962 final String name = info.serviceName;
963 final String type = info.registrationType;
964 servInfo = new NsdServiceInfo(name, type);
965 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900966 if (foundNetId == 0L) {
967 // Ignore services that do not have a Network: they are not usable
968 // by apps, as they would need privileged permissions to use
969 // interfaces that do not have an associated Network.
970 break;
971 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900972 if (foundNetId == INetd.DUMMY_NET_ID) {
973 // Ignore services on the dummy0 interface: they are only seen when
974 // discovering locally advertised services, and are not reachable
975 // through that interface.
976 break;
977 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900978 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900979 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700980 break;
paulhu2b9ed952022-02-10 21:58:32 +0800981 }
982 case IMDnsEventListener.SERVICE_LOST: {
983 final DiscoveryInfo info = (DiscoveryInfo) obj;
984 final String name = info.serviceName;
985 final String type = info.registrationType;
986 final int lostNetId = info.netId;
987 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900988 // The network could be set to null (netId 0) if it was torn down when the
989 // service is lost
990 // TODO: avoid returning null in that case, possibly by remembering
991 // found services on the same interface index and their network at the time
992 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900993 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700994 break;
paulhu2b9ed952022-02-10 21:58:32 +0800995 }
996 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900997 clientInfo.onDiscoverServicesFailed(
998 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700999 break;
paulhu2b9ed952022-02-10 21:58:32 +08001000 case IMDnsEventListener.SERVICE_REGISTERED: {
1001 final RegistrationInfo info = (RegistrationInfo) obj;
1002 final String name = info.serviceName;
1003 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001004 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001005 break;
paulhu2b9ed952022-02-10 21:58:32 +08001006 }
1007 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001008 clientInfo.onRegisterServiceFailed(
1009 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001010 break;
paulhu2b9ed952022-02-10 21:58:32 +08001011 case IMDnsEventListener.SERVICE_RESOLVED: {
1012 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001013 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001014 final String fullName = info.serviceFullName;
1015 while (index < fullName.length() && fullName.charAt(index) != '.') {
1016 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001017 ++index;
1018 }
1019 ++index;
1020 }
paulhu2b9ed952022-02-10 21:58:32 +08001021 if (index >= fullName.length()) {
1022 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001023 break;
1024 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001025
paulhube186602022-04-12 07:18:23 +00001026 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001027 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001028 String type = rest.replace(".local.", "");
1029
Paul Hu30bd70d2023-02-07 13:20:56 +00001030 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001031 serviceInfo.setServiceName(name);
1032 serviceInfo.setServiceType(type);
1033 serviceInfo.setPort(info.port);
1034 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001035 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001036
1037 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001038 removeRequestMap(clientId, id, clientInfo);
1039
paulhu2b9ed952022-02-10 21:58:32 +08001040 final int id2 = getUniqueId();
1041 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001042 storeLegacyRequestMap(clientId, id2, clientInfo,
1043 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001044 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001045 clientInfo.onResolveServiceFailed(
1046 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1047 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001048 }
1049 break;
paulhu2b9ed952022-02-10 21:58:32 +08001050 }
1051 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001052 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001053 stopResolveService(id);
1054 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001055 clientInfo.onResolveServiceFailed(
1056 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1057 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001058 break;
paulhu2b9ed952022-02-10 21:58:32 +08001059 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001060 /* NNN resolveId errorCode */
1061 stopGetAddrInfo(id);
1062 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001063 clientInfo.onResolveServiceFailed(
1064 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1065 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001066 break;
paulhu2b9ed952022-02-10 21:58:32 +08001067 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001068 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001069 final GetAddressInfo info = (GetAddressInfo) obj;
1070 final String address = info.address;
1071 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001072 InetAddress serviceHost = null;
1073 try {
paulhu2b9ed952022-02-10 21:58:32 +08001074 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001075 } catch (UnknownHostException e) {
1076 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1077 }
1078
1079 // If the resolved service is on an interface without a network, consider it
1080 // as a failure: it would not be usable by apps as they would need
1081 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001082 if (netId != NETID_UNSET && serviceHost != null) {
1083 clientInfo.mResolvedService.setHost(serviceHost);
1084 setServiceNetworkForCallback(clientInfo.mResolvedService,
1085 netId, info.interfaceIdx);
1086 clientInfo.onResolveServiceSucceeded(
1087 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001088 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001089 clientInfo.onResolveServiceFailed(
1090 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001091 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001092 stopGetAddrInfo(id);
1093 removeRequestMap(clientId, id, clientInfo);
1094 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001095 break;
paulhu2b9ed952022-02-10 21:58:32 +08001096 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001097 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001098 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001099 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001100 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001101 }
Paul Hu019621e2023-01-13 23:26:49 +08001102
1103 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1104 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1105 final String serviceType = event.mRequestedServiceType;
1106 final String serviceName = serviceInfo.getServiceInstanceName();
1107 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1108 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001109 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1110 // network for Tethering interface. In other words, the network == null means the
1111 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001112 setServiceNetworkForCallback(
1113 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001114 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001115 serviceInfo.getInterfaceIndex());
1116 return servInfo;
1117 }
1118
1119 private boolean handleMdnsDiscoveryManagerEvent(
1120 int transactionId, int code, Object obj) {
1121 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1122 if (clientInfo == null) {
1123 Log.e(TAG, String.format(
1124 "id %d for %d has no client mapping", transactionId, code));
1125 return false;
1126 }
1127
1128 final MdnsEvent event = (MdnsEvent) obj;
1129 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001130 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001131 if (DBG) {
1132 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1133 NsdManager.nameOf(code), transactionId));
1134 }
1135 switch (code) {
1136 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001137 clientInfo.onServiceFound(clientId, info);
1138 break;
1139 case NsdManager.SERVICE_LOST:
1140 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001141 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001142 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001143 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1144 if (request == null) {
1145 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1146 break;
1147 }
Paul Hu75069ed2023-01-14 00:31:09 +08001148 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1149 // Add '.' in front of the service type that aligns with historical behavior
1150 info.setServiceType("." + event.mRequestedServiceType);
1151 info.setPort(serviceInfo.getPort());
1152
1153 Map<String, String> attrs = serviceInfo.getAttributes();
1154 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1155 final String key = kv.getKey();
1156 try {
1157 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1158 } catch (IllegalArgumentException e) {
1159 Log.e(TAG, "Invalid attribute", e);
1160 }
1161 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001162 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001163 if (addresses.size() != 0) {
1164 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001165 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001166 } else {
1167 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001168 clientInfo.onResolveServiceFailed(
1169 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1170 }
1171
1172 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001173 if (!(request instanceof DiscoveryManagerRequest)) {
1174 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1175 break;
1176 }
Paul Hue4f5f252023-02-16 21:13:47 +08001177 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001178 break;
1179 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001180 case NsdManager.SERVICE_UPDATED: {
1181 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1182 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 }
1193
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001194 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001195 info.setHostAddresses(addresses);
1196 clientInfo.onServiceUpdated(clientId, info);
1197 break;
1198 }
1199 case NsdManager.SERVICE_UPDATED_LOST:
1200 clientInfo.onServiceUpdatedLost(clientId);
1201 break;
Paul Hu019621e2023-01-13 23:26:49 +08001202 default:
1203 return false;
1204 }
1205 return true;
1206 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001207 }
1208 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001209
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001210 @NonNull
1211 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1212 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1213 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1214 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1215 for (String ipv4Address : v4Addrs) {
1216 try {
1217 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1218 } catch (IllegalArgumentException e) {
1219 Log.wtf(TAG, "Invalid ipv4 address", e);
1220 }
1221 }
1222 for (String ipv6Address : v6Addrs) {
1223 try {
1224 final InetAddress addr = InetAddresses.parseNumericAddress(ipv6Address);
1225 if (addr.isLinkLocalAddress()) {
1226 final Inet6Address v6Addr = Inet6Address.getByAddress(
1227 null /* host */, addr.getAddress(),
1228 serviceInfo.getInterfaceIndex());
1229 addresses.add(v6Addr);
1230 } else {
1231 addresses.add(addr);
1232 }
1233 } catch (IllegalArgumentException | UnknownHostException e) {
1234 Log.wtf(TAG, "Invalid ipv6 address", e);
1235 }
1236 }
1237 return addresses;
1238 }
1239
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001240 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1241 switch (netId) {
1242 case NETID_UNSET:
1243 info.setNetwork(null);
1244 break;
1245 case INetd.LOCAL_NET_ID:
1246 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1247 // visible / usable for apps, so do not return it. Store the interface
1248 // index instead, so at least if the client tries to resolve the service
1249 // with that NsdServiceInfo, it will be done on the same interface.
1250 // If they recreate the NsdServiceInfo themselves, resolution would be
1251 // done on all interfaces as before T, which should also work.
1252 info.setNetwork(null);
1253 info.setInterfaceIndex(ifaceIdx);
1254 break;
1255 default:
1256 info.setNetwork(new Network(netId));
1257 }
1258 }
1259
paulhube186602022-04-12 07:18:23 +00001260 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1261 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1262 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1263 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1264 private String unescape(String s) {
1265 StringBuilder sb = new StringBuilder(s.length());
1266 for (int i = 0; i < s.length(); ++i) {
1267 char c = s.charAt(i);
1268 if (c == '\\') {
1269 if (++i >= s.length()) {
1270 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1271 break;
1272 }
1273 c = s.charAt(i);
1274 if (c != '.' && c != '\\') {
1275 if (i + 2 >= s.length()) {
1276 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1277 break;
1278 }
1279 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1280 + (s.charAt(i + 2) - '0'));
1281 i += 2;
1282 }
1283 }
1284 sb.append(c);
1285 }
1286 return sb.toString();
1287 }
1288
Paul Hu7445e3d2023-03-03 15:14:00 +08001289 /**
1290 * Check the given service type is valid and construct it to a service type
1291 * which can use for discovery / resolution service.
1292 *
1293 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1294 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1295 * underscore; they are alphanumerical characters or dashes or underscore, except the
1296 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1297 *
1298 * @param serviceType the request service type for discovery / resolution service
1299 * @return constructed service type or null if the given service type is invalid.
1300 */
1301 @Nullable
1302 public static String constructServiceType(String serviceType) {
1303 if (TextUtils.isEmpty(serviceType)) return null;
1304
1305 final Pattern serviceTypePattern = Pattern.compile(
1306 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1307 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1308 // Drop '.' at the end of service type that is compatible with old backend.
1309 + "\\.?$");
1310 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1311 if (!matcher.matches()) return null;
1312 return matcher.group(1) == null
1313 ? matcher.group(2)
1314 : matcher.group(1) + "_sub." + matcher.group(2);
1315 }
1316
Hugo Benichi803a2f02017-04-24 11:35:06 +09001317 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001318 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001319 this(ctx, handler, cleanupDelayMs, new Dependencies());
1320 }
1321
1322 @VisibleForTesting
1323 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001324 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001325 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001326 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001327 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001328 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1329 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001330 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001331
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001332 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1333 mMdnsSocketClient =
1334 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1335 mMdnsDiscoveryManager =
1336 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1337 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1338 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1339 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001340 }
1341
1342 /**
1343 * Dependencies of NsdService, for injection in tests.
1344 */
1345 @VisibleForTesting
1346 public static class Dependencies {
1347 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001348 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001349 *
1350 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001351 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001352 */
1353 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001354 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1355 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1356 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001357 }
1358
1359 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001360 * Check whether the MdnsAdvertiser feature is enabled.
1361 *
1362 * @param context The global context information about an app environment.
1363 * @return true if the MdnsAdvertiser feature is enabled.
1364 */
1365 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001366 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1367 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001368 }
1369
1370 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001371 * Get the type allowlist flag value.
1372 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1373 */
1374 @Nullable
1375 public String getTypeAllowlistFlags() {
1376 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1377 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1378 }
1379
1380 /**
1381 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1382 */
1383 public boolean isFeatureEnabled(Context context, String feature) {
1384 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1385 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1386 }
1387
1388 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001389 * @see MdnsDiscoveryManager
1390 */
1391 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1392 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1393 return new MdnsDiscoveryManager(executorProvider, socketClient);
1394 }
1395
1396 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001397 * @see MdnsAdvertiser
1398 */
1399 public MdnsAdvertiser makeMdnsAdvertiser(
1400 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1401 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1402 return new MdnsAdvertiser(looper, socketProvider, cb);
1403 }
1404
1405 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001406 * @see MdnsSocketProvider
1407 */
1408 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1409 return new MdnsSocketProvider(context, looper);
1410 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001411 }
1412
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001413 /**
1414 * Return whether a type is allowlisted to use the Java backend.
1415 * @param type The service type
1416 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1417 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1418 */
1419 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1420 @NonNull String flagPrefix) {
1421 if (type == null) return false;
1422 final String typesConfig = mDeps.getTypeAllowlistFlags();
1423 if (TextUtils.isEmpty(typesConfig)) return false;
1424
1425 final String mappingPrefix = type + ":";
1426 String mappedFlag = null;
1427 for (String mapping : TextUtils.split(typesConfig, ",")) {
1428 if (mapping.startsWith(mappingPrefix)) {
1429 mappedFlag = mapping.substring(mappingPrefix.length());
1430 break;
1431 }
1432 }
1433
1434 if (mappedFlag == null) return false;
1435
1436 return mDeps.isFeatureEnabled(mContext,
1437 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1438 }
1439
1440 private boolean useDiscoveryManagerForType(@Nullable String type) {
1441 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1442 }
1443
1444 private boolean useAdvertiserForType(@Nullable String type) {
1445 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1446 }
1447
paulhu1b35e822022-04-08 14:48:41 +08001448 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001449 HandlerThread thread = new HandlerThread(TAG);
1450 thread.start();
1451 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001452 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001453 return service;
1454 }
1455
paulhu2b9ed952022-02-10 21:58:32 +08001456 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1457 private final StateMachine mStateMachine;
1458
1459 MDnsEventCallback(StateMachine sm) {
1460 mStateMachine = sm;
1461 }
1462
1463 @Override
1464 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1465 mStateMachine.sendMessage(
1466 MDNS_SERVICE_EVENT, status.result, status.id, status);
1467 }
1468
1469 @Override
1470 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1471 mStateMachine.sendMessage(
1472 MDNS_SERVICE_EVENT, status.result, status.id, status);
1473 }
1474
1475 @Override
1476 public void onServiceResolutionStatus(final ResolutionInfo status) {
1477 mStateMachine.sendMessage(
1478 MDNS_SERVICE_EVENT, status.result, status.id, status);
1479 }
1480
1481 @Override
1482 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1483 mStateMachine.sendMessage(
1484 MDNS_SERVICE_EVENT, status.result, status.id, status);
1485 }
1486
1487 @Override
1488 public int getInterfaceVersion() throws RemoteException {
1489 return this.VERSION;
1490 }
1491
1492 @Override
1493 public String getInterfaceHash() throws RemoteException {
1494 return this.HASH;
1495 }
1496 }
1497
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001498 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1499 @Override
1500 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1501 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1502 if (clientInfo == null) return;
1503
1504 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1505 if (clientId < 0) return;
1506
1507 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1508 // historical behavior.
1509 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1510 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1511 }
1512
1513 @Override
1514 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1515 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1516 if (clientInfo == null) return;
1517
1518 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1519 if (clientId < 0) return;
1520
1521 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1522 }
1523
1524 private ClientInfo getClientInfoOrLog(int serviceId) {
1525 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1526 if (clientInfo == null) {
1527 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1528 }
1529 return clientInfo;
1530 }
1531
1532 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1533 final int clientId = info.getClientId(serviceId);
1534 if (clientId < 0) {
1535 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1536 }
1537 return clientId;
1538 }
1539 }
1540
Paul Hu2e0a88c2023-03-09 16:05:01 +08001541 private static class ConnectorArgs {
1542 @NonNull public final NsdServiceConnector connector;
1543 @NonNull public final INsdManagerCallback callback;
1544 public final boolean useJavaBackend;
1545
1546 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
1547 boolean useJavaBackend) {
1548 this.connector = connector;
1549 this.callback = callback;
1550 this.useJavaBackend = useJavaBackend;
1551 }
1552 }
1553
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001554 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001555 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001557 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001558 final INsdServiceConnector connector = new NsdServiceConnector();
1559 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
Paul Hu2e0a88c2023-03-09 16:05:01 +08001560 NsdManager.REGISTER_CLIENT,
1561 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001562 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001563 }
1564
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001565 private static class ListenerArgs {
1566 public final NsdServiceConnector connector;
1567 public final NsdServiceInfo serviceInfo;
1568 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1569 this.connector = connector;
1570 this.serviceInfo = serviceInfo;
1571 }
1572 }
1573
1574 private class NsdServiceConnector extends INsdServiceConnector.Stub
1575 implements IBinder.DeathRecipient {
1576 @Override
1577 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1578 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1579 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1580 new ListenerArgs(this, serviceInfo)));
1581 }
1582
1583 @Override
1584 public void unregisterService(int listenerKey) {
1585 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1586 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1587 new ListenerArgs(this, null)));
1588 }
1589
1590 @Override
1591 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1592 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1593 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1594 new ListenerArgs(this, serviceInfo)));
1595 }
1596
1597 @Override
1598 public void stopDiscovery(int listenerKey) {
1599 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1600 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1601 }
1602
1603 @Override
1604 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1605 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1606 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1607 new ListenerArgs(this, serviceInfo)));
1608 }
1609
1610 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001611 public void stopResolution(int listenerKey) {
1612 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1613 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1614 }
1615
1616 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001617 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1618 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1619 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1620 new ListenerArgs(this, serviceInfo)));
1621 }
1622
1623 @Override
1624 public void unregisterServiceInfoCallback(int listenerKey) {
1625 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1626 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1627 new ListenerArgs(this, null)));
1628 }
1629
1630 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001631 public void startDaemon() {
1632 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1633 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1634 }
1635
1636 @Override
1637 public void binderDied() {
1638 mNsdStateMachine.sendMessage(
1639 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1640 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001641 }
1642
Hugo Benichi912db992017-04-24 16:41:03 +09001643 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001644 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001645 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001646 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1647 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001648 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001649 }
1650
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001651 private int getUniqueId() {
1652 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1653 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001654 }
1655
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001656 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001657 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001658 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001659 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001660 String name = service.getServiceName();
1661 String type = service.getServiceType();
1662 int port = service.getPort();
1663 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001664 final int registerInterface = getNetworkInterfaceIndex(service);
1665 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001666 Log.e(TAG, "Interface to register service on not found");
1667 return false;
1668 }
1669 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001670 }
1671
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001672 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001673 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001674 }
1675
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001676 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001677 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001678 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1679 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001680 Log.e(TAG, "Interface to discover service on not found");
1681 return false;
1682 }
paulhu2b9ed952022-02-10 21:58:32 +08001683 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001684 }
1685
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001686 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001687 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001688 }
1689
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001690 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001691 final String name = service.getServiceName();
1692 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001693 final int resolveInterface = getNetworkInterfaceIndex(service);
1694 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001695 Log.e(TAG, "Interface to resolve service on not found");
1696 return false;
1697 }
paulhu2b9ed952022-02-10 21:58:32 +08001698 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001699 }
1700
1701 /**
1702 * Guess the interface to use to resolve or discover a service on a specific network.
1703 *
1704 * This is an imperfect guess, as for example the network may be gone or not yet fully
1705 * registered. This is fine as failing is correct if the network is gone, and a client
1706 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1707 * this is to support the legacy mdnsresponder implementation, which historically resolved
1708 * services on an unspecified network.
1709 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001710 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1711 final Network network = serviceInfo.getNetwork();
1712 if (network == null) {
1713 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1714 // provided by NsdService from discovery results, and the service was found on an
1715 // interface that has no app-usable Network).
1716 if (serviceInfo.getInterfaceIndex() != 0) {
1717 return serviceInfo.getInterfaceIndex();
1718 }
1719 return IFACE_IDX_ANY;
1720 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001721
1722 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1723 if (cm == null) {
1724 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1725 return IFACE_IDX_ANY;
1726 }
1727 final LinkProperties lp = cm.getLinkProperties(network);
1728 if (lp == null) return IFACE_IDX_ANY;
1729
1730 // Only resolve on non-stacked interfaces
1731 final NetworkInterface iface;
1732 try {
1733 iface = NetworkInterface.getByName(lp.getInterfaceName());
1734 } catch (SocketException e) {
1735 Log.e(TAG, "Error querying interface", e);
1736 return IFACE_IDX_ANY;
1737 }
1738
1739 if (iface == null) {
1740 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1741 return IFACE_IDX_ANY;
1742 }
1743
1744 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001745 }
1746
1747 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001748 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001749 }
1750
paulhu2b9ed952022-02-10 21:58:32 +08001751 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1752 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001753 }
1754
1755 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001756 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001757 }
1758
1759 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001760 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001761 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001762
Irfan Sheriff75006652012-04-17 23:15:29 -07001763 for (ClientInfo client : mClients.values()) {
1764 pw.println("Client Info");
1765 pw.println(client);
1766 }
1767
1768 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001769 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001770
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001771 private abstract static class ClientRequest {
1772 private final int mGlobalId;
1773
1774 private ClientRequest(int globalId) {
1775 mGlobalId = globalId;
1776 }
1777 }
1778
1779 private static class LegacyClientRequest extends ClientRequest {
1780 private final int mRequestCode;
1781
1782 private LegacyClientRequest(int globalId, int requestCode) {
1783 super(globalId);
1784 mRequestCode = requestCode;
1785 }
1786 }
1787
1788 private static class AdvertiserClientRequest extends ClientRequest {
1789 private AdvertiserClientRequest(int globalId) {
1790 super(globalId);
1791 }
1792 }
1793
1794 private static class DiscoveryManagerRequest extends ClientRequest {
1795 @NonNull
1796 private final MdnsListener mListener;
1797
1798 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1799 super(globalId);
1800 mListener = listener;
1801 }
1802 }
1803
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001804 /* Information tracked per client */
1805 private class ClientInfo {
1806
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001807 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001808 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001809 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001810 private NsdServiceInfo mResolvedService;
1811
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001812 /* A map from client-side ID (listenerKey) to the request */
1813 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001814
Luke Huangf7277ed2021-07-12 21:15:10 +08001815 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001816 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001817 // The flag of using java backend if the client's target SDK >= U
1818 private final boolean mUseJavaBackend;
Luke Huangf7277ed2021-07-12 21:15:10 +08001819
Paul Hu2e0a88c2023-03-09 16:05:01 +08001820 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001821 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001822 mUseJavaBackend = useJavaBackend;
paulhub2225702021-11-17 09:35:33 +08001823 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001824 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001825
1826 @Override
1827 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001828 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001829 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001830 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1831 for (int i = 0; i < mClientRequests.size(); i++) {
1832 int clientID = mClientRequests.keyAt(i);
1833 sb.append("clientId ")
1834 .append(clientID)
1835 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1836 .append(" type ").append(
1837 mClientRequests.valueAt(i).getClass().getSimpleName())
1838 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001839 }
1840 return sb.toString();
1841 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001842
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001843 private boolean isPreSClient() {
1844 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001845 }
1846
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001847 private void setPreSClient() {
1848 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001849 }
1850
Paul Hue4f5f252023-02-16 21:13:47 +08001851 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1852 final MdnsListener listener =
1853 ((DiscoveryManagerRequest) request).mListener;
1854 mMdnsDiscoveryManager.unregisterListener(
1855 listener.getListenedServiceType(), listener);
1856 }
1857
Dave Plattfeff2af2014-03-07 14:48:22 -08001858 // Remove any pending requests from the global map when we get rid of a client,
1859 // and send cancellations to the daemon.
1860 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001861 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001862 for (int i = 0; i < mClientRequests.size(); i++) {
1863 final int clientId = mClientRequests.keyAt(i);
1864 final ClientRequest request = mClientRequests.valueAt(i);
1865 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001866 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001867 if (DBG) {
1868 Log.d(TAG, "Terminating client-ID " + clientId
1869 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1870 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001871
1872 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001873 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001874 continue;
1875 }
1876
1877 if (request instanceof AdvertiserClientRequest) {
1878 mAdvertiser.removeService(globalId);
1879 continue;
1880 }
1881
1882 if (!(request instanceof LegacyClientRequest)) {
1883 throw new IllegalStateException("Unknown request type: " + request.getClass());
1884 }
1885
1886 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001887 case NsdManager.DISCOVER_SERVICES:
1888 stopServiceDiscovery(globalId);
1889 break;
1890 case NsdManager.RESOLVE_SERVICE:
1891 stopResolveService(globalId);
1892 break;
1893 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001894 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001895 break;
1896 default:
1897 break;
1898 }
1899 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001900 mClientRequests.clear();
1901 }
1902
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001903 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1904 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1905 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001906 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001907 for (int i = 0; i < mClientRequests.size(); i++) {
1908 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1909 return mClientRequests.keyAt(i);
1910 }
Christopher Lane74411222014-04-25 18:39:07 -07001911 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001912 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001913 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001914
1915 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1916 try {
1917 mCb.onDiscoverServicesStarted(listenerKey, info);
1918 } catch (RemoteException e) {
1919 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1920 }
1921 }
1922
1923 void onDiscoverServicesFailed(int listenerKey, int error) {
1924 try {
1925 mCb.onDiscoverServicesFailed(listenerKey, error);
1926 } catch (RemoteException e) {
1927 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1928 }
1929 }
1930
1931 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1932 try {
1933 mCb.onServiceFound(listenerKey, info);
1934 } catch (RemoteException e) {
1935 Log.e(TAG, "Error calling onServiceFound(", e);
1936 }
1937 }
1938
1939 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1940 try {
1941 mCb.onServiceLost(listenerKey, info);
1942 } catch (RemoteException e) {
1943 Log.e(TAG, "Error calling onServiceLost(", e);
1944 }
1945 }
1946
1947 void onStopDiscoveryFailed(int listenerKey, int error) {
1948 try {
1949 mCb.onStopDiscoveryFailed(listenerKey, error);
1950 } catch (RemoteException e) {
1951 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1952 }
1953 }
1954
1955 void onStopDiscoverySucceeded(int listenerKey) {
1956 try {
1957 mCb.onStopDiscoverySucceeded(listenerKey);
1958 } catch (RemoteException e) {
1959 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1960 }
1961 }
1962
1963 void onRegisterServiceFailed(int listenerKey, int error) {
1964 try {
1965 mCb.onRegisterServiceFailed(listenerKey, error);
1966 } catch (RemoteException e) {
1967 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1968 }
1969 }
1970
1971 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1972 try {
1973 mCb.onRegisterServiceSucceeded(listenerKey, info);
1974 } catch (RemoteException e) {
1975 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1976 }
1977 }
1978
1979 void onUnregisterServiceFailed(int listenerKey, int error) {
1980 try {
1981 mCb.onUnregisterServiceFailed(listenerKey, error);
1982 } catch (RemoteException e) {
1983 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1984 }
1985 }
1986
1987 void onUnregisterServiceSucceeded(int listenerKey) {
1988 try {
1989 mCb.onUnregisterServiceSucceeded(listenerKey);
1990 } catch (RemoteException e) {
1991 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1992 }
1993 }
1994
1995 void onResolveServiceFailed(int listenerKey, int error) {
1996 try {
1997 mCb.onResolveServiceFailed(listenerKey, error);
1998 } catch (RemoteException e) {
1999 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2000 }
2001 }
2002
2003 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2004 try {
2005 mCb.onResolveServiceSucceeded(listenerKey, info);
2006 } catch (RemoteException e) {
2007 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2008 }
2009 }
Paul Hub58deb72022-12-26 09:24:42 +00002010
2011 void onStopResolutionFailed(int listenerKey, int error) {
2012 try {
2013 mCb.onStopResolutionFailed(listenerKey, error);
2014 } catch (RemoteException e) {
2015 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2016 }
2017 }
2018
2019 void onStopResolutionSucceeded(int listenerKey) {
2020 try {
2021 mCb.onStopResolutionSucceeded(listenerKey);
2022 } catch (RemoteException e) {
2023 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2024 }
2025 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002026
2027 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2028 try {
2029 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2030 } catch (RemoteException e) {
2031 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2032 }
2033 }
2034
2035 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2036 try {
2037 mCb.onServiceUpdated(listenerKey, info);
2038 } catch (RemoteException e) {
2039 Log.e(TAG, "Error calling onServiceUpdated", e);
2040 }
2041 }
2042
2043 void onServiceUpdatedLost(int listenerKey) {
2044 try {
2045 mCb.onServiceUpdatedLost(listenerKey);
2046 } catch (RemoteException e) {
2047 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2048 }
2049 }
2050
2051 void onServiceInfoCallbackUnregistered(int listenerKey) {
2052 try {
2053 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2054 } catch (RemoteException e) {
2055 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2056 }
2057 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002058 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002059}