blob: c5104d8ef1e7bf7be96454fe2b6a802c9e17810c [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);
Paul Hub8a3a632023-04-18 02:45:34 +0000404 cInfo = new ClientInfo(cb, arg.useJavaBackend);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800405 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());
Yuyang Huang700778b2023-03-08 16:17:05 +09001333 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1334 // address events are received.
1335 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001336 mMdnsSocketClient =
1337 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1338 mMdnsDiscoveryManager =
1339 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1340 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1341 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1342 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001343 }
1344
1345 /**
1346 * Dependencies of NsdService, for injection in tests.
1347 */
1348 @VisibleForTesting
1349 public static class Dependencies {
1350 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001351 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001352 *
1353 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001354 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001355 */
1356 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001357 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1358 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1359 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001360 }
1361
1362 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001363 * Check whether the MdnsAdvertiser feature is enabled.
1364 *
1365 * @param context The global context information about an app environment.
1366 * @return true if the MdnsAdvertiser feature is enabled.
1367 */
1368 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001369 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1370 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001371 }
1372
1373 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001374 * Get the type allowlist flag value.
1375 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1376 */
1377 @Nullable
1378 public String getTypeAllowlistFlags() {
1379 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1380 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1381 }
1382
1383 /**
1384 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1385 */
1386 public boolean isFeatureEnabled(Context context, String feature) {
1387 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1388 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1389 }
1390
1391 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001392 * @see MdnsDiscoveryManager
1393 */
1394 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1395 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1396 return new MdnsDiscoveryManager(executorProvider, socketClient);
1397 }
1398
1399 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001400 * @see MdnsAdvertiser
1401 */
1402 public MdnsAdvertiser makeMdnsAdvertiser(
1403 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1404 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1405 return new MdnsAdvertiser(looper, socketProvider, cb);
1406 }
1407
1408 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001409 * @see MdnsSocketProvider
1410 */
1411 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1412 return new MdnsSocketProvider(context, looper);
1413 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001414 }
1415
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001416 /**
1417 * Return whether a type is allowlisted to use the Java backend.
1418 * @param type The service type
1419 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1420 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1421 */
1422 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1423 @NonNull String flagPrefix) {
1424 if (type == null) return false;
1425 final String typesConfig = mDeps.getTypeAllowlistFlags();
1426 if (TextUtils.isEmpty(typesConfig)) return false;
1427
1428 final String mappingPrefix = type + ":";
1429 String mappedFlag = null;
1430 for (String mapping : TextUtils.split(typesConfig, ",")) {
1431 if (mapping.startsWith(mappingPrefix)) {
1432 mappedFlag = mapping.substring(mappingPrefix.length());
1433 break;
1434 }
1435 }
1436
1437 if (mappedFlag == null) return false;
1438
1439 return mDeps.isFeatureEnabled(mContext,
1440 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1441 }
1442
1443 private boolean useDiscoveryManagerForType(@Nullable String type) {
1444 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1445 }
1446
1447 private boolean useAdvertiserForType(@Nullable String type) {
1448 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1449 }
1450
paulhu1b35e822022-04-08 14:48:41 +08001451 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001452 HandlerThread thread = new HandlerThread(TAG);
1453 thread.start();
1454 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001455 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001456 return service;
1457 }
1458
paulhu2b9ed952022-02-10 21:58:32 +08001459 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1460 private final StateMachine mStateMachine;
1461
1462 MDnsEventCallback(StateMachine sm) {
1463 mStateMachine = sm;
1464 }
1465
1466 @Override
1467 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1468 mStateMachine.sendMessage(
1469 MDNS_SERVICE_EVENT, status.result, status.id, status);
1470 }
1471
1472 @Override
1473 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1474 mStateMachine.sendMessage(
1475 MDNS_SERVICE_EVENT, status.result, status.id, status);
1476 }
1477
1478 @Override
1479 public void onServiceResolutionStatus(final ResolutionInfo status) {
1480 mStateMachine.sendMessage(
1481 MDNS_SERVICE_EVENT, status.result, status.id, status);
1482 }
1483
1484 @Override
1485 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1486 mStateMachine.sendMessage(
1487 MDNS_SERVICE_EVENT, status.result, status.id, status);
1488 }
1489
1490 @Override
1491 public int getInterfaceVersion() throws RemoteException {
1492 return this.VERSION;
1493 }
1494
1495 @Override
1496 public String getInterfaceHash() throws RemoteException {
1497 return this.HASH;
1498 }
1499 }
1500
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001501 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1502 @Override
1503 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1504 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1505 if (clientInfo == null) return;
1506
1507 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1508 if (clientId < 0) return;
1509
1510 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1511 // historical behavior.
1512 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1513 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1514 }
1515
1516 @Override
1517 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1518 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1519 if (clientInfo == null) return;
1520
1521 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1522 if (clientId < 0) return;
1523
1524 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1525 }
1526
1527 private ClientInfo getClientInfoOrLog(int serviceId) {
1528 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1529 if (clientInfo == null) {
1530 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1531 }
1532 return clientInfo;
1533 }
1534
1535 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1536 final int clientId = info.getClientId(serviceId);
1537 if (clientId < 0) {
1538 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1539 }
1540 return clientId;
1541 }
1542 }
1543
Paul Hu2e0a88c2023-03-09 16:05:01 +08001544 private static class ConnectorArgs {
1545 @NonNull public final NsdServiceConnector connector;
1546 @NonNull public final INsdManagerCallback callback;
1547 public final boolean useJavaBackend;
1548
1549 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub8a3a632023-04-18 02:45:34 +00001550 boolean useJavaBackend) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001551 this.connector = connector;
1552 this.callback = callback;
1553 this.useJavaBackend = useJavaBackend;
1554 }
1555 }
1556
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001557 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001558 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001560 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001561 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub8a3a632023-04-18 02:45:34 +00001562 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1563 NsdManager.REGISTER_CLIENT,
1564 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001565 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001566 }
1567
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001568 private static class ListenerArgs {
1569 public final NsdServiceConnector connector;
1570 public final NsdServiceInfo serviceInfo;
1571 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1572 this.connector = connector;
1573 this.serviceInfo = serviceInfo;
1574 }
1575 }
1576
1577 private class NsdServiceConnector extends INsdServiceConnector.Stub
1578 implements IBinder.DeathRecipient {
1579 @Override
1580 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1581 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1582 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1583 new ListenerArgs(this, serviceInfo)));
1584 }
1585
1586 @Override
1587 public void unregisterService(int listenerKey) {
1588 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1589 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1590 new ListenerArgs(this, null)));
1591 }
1592
1593 @Override
1594 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1595 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1596 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1597 new ListenerArgs(this, serviceInfo)));
1598 }
1599
1600 @Override
1601 public void stopDiscovery(int listenerKey) {
1602 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1603 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1604 }
1605
1606 @Override
1607 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1608 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1609 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1610 new ListenerArgs(this, serviceInfo)));
1611 }
1612
1613 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001614 public void stopResolution(int listenerKey) {
1615 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1616 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1617 }
1618
1619 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001620 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1621 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1622 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1623 new ListenerArgs(this, serviceInfo)));
1624 }
1625
1626 @Override
1627 public void unregisterServiceInfoCallback(int listenerKey) {
1628 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1629 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1630 new ListenerArgs(this, null)));
1631 }
1632
1633 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001634 public void startDaemon() {
1635 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1636 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1637 }
1638
1639 @Override
1640 public void binderDied() {
1641 mNsdStateMachine.sendMessage(
1642 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1643 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001644 }
1645
Hugo Benichi912db992017-04-24 16:41:03 +09001646 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001647 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001648 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001649 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1650 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001651 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001652 }
1653
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001654 private int getUniqueId() {
1655 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1656 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001657 }
1658
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001659 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001660 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001661 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001662 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001663 String name = service.getServiceName();
1664 String type = service.getServiceType();
1665 int port = service.getPort();
1666 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001667 final int registerInterface = getNetworkInterfaceIndex(service);
1668 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001669 Log.e(TAG, "Interface to register service on not found");
1670 return false;
1671 }
1672 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001673 }
1674
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001675 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001676 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001677 }
1678
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001679 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001680 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001681 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1682 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001683 Log.e(TAG, "Interface to discover service on not found");
1684 return false;
1685 }
paulhu2b9ed952022-02-10 21:58:32 +08001686 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001687 }
1688
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001689 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001690 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001691 }
1692
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001693 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001694 final String name = service.getServiceName();
1695 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001696 final int resolveInterface = getNetworkInterfaceIndex(service);
1697 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001698 Log.e(TAG, "Interface to resolve service on not found");
1699 return false;
1700 }
paulhu2b9ed952022-02-10 21:58:32 +08001701 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001702 }
1703
1704 /**
1705 * Guess the interface to use to resolve or discover a service on a specific network.
1706 *
1707 * This is an imperfect guess, as for example the network may be gone or not yet fully
1708 * registered. This is fine as failing is correct if the network is gone, and a client
1709 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1710 * this is to support the legacy mdnsresponder implementation, which historically resolved
1711 * services on an unspecified network.
1712 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001713 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1714 final Network network = serviceInfo.getNetwork();
1715 if (network == null) {
1716 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1717 // provided by NsdService from discovery results, and the service was found on an
1718 // interface that has no app-usable Network).
1719 if (serviceInfo.getInterfaceIndex() != 0) {
1720 return serviceInfo.getInterfaceIndex();
1721 }
1722 return IFACE_IDX_ANY;
1723 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001724
1725 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1726 if (cm == null) {
1727 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1728 return IFACE_IDX_ANY;
1729 }
1730 final LinkProperties lp = cm.getLinkProperties(network);
1731 if (lp == null) return IFACE_IDX_ANY;
1732
1733 // Only resolve on non-stacked interfaces
1734 final NetworkInterface iface;
1735 try {
1736 iface = NetworkInterface.getByName(lp.getInterfaceName());
1737 } catch (SocketException e) {
1738 Log.e(TAG, "Error querying interface", e);
1739 return IFACE_IDX_ANY;
1740 }
1741
1742 if (iface == null) {
1743 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1744 return IFACE_IDX_ANY;
1745 }
1746
1747 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001748 }
1749
1750 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001751 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001752 }
1753
paulhu2b9ed952022-02-10 21:58:32 +08001754 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1755 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001756 }
1757
1758 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001759 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001760 }
1761
1762 @Override
Paul Hub8a3a632023-04-18 02:45:34 +00001763 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1764 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001765
Paul Hub8a3a632023-04-18 02:45:34 +00001766 for (ClientInfo client : mClients.values()) {
1767 pw.println("Client Info");
1768 pw.println(client);
1769 }
1770
Irfan Sheriff75006652012-04-17 23:15:29 -07001771 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001772 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001773
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001774 private abstract static class ClientRequest {
1775 private final int mGlobalId;
1776
1777 private ClientRequest(int globalId) {
1778 mGlobalId = globalId;
1779 }
1780 }
1781
1782 private static class LegacyClientRequest extends ClientRequest {
1783 private final int mRequestCode;
1784
1785 private LegacyClientRequest(int globalId, int requestCode) {
1786 super(globalId);
1787 mRequestCode = requestCode;
1788 }
1789 }
1790
1791 private static class AdvertiserClientRequest extends ClientRequest {
1792 private AdvertiserClientRequest(int globalId) {
1793 super(globalId);
1794 }
1795 }
1796
1797 private static class DiscoveryManagerRequest extends ClientRequest {
1798 @NonNull
1799 private final MdnsListener mListener;
1800
1801 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1802 super(globalId);
1803 mListener = listener;
1804 }
1805 }
1806
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001807 /* Information tracked per client */
1808 private class ClientInfo {
1809
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001810 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001811 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001812 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001813 private NsdServiceInfo mResolvedService;
1814
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001815 /* A map from client-side ID (listenerKey) to the request */
1816 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001817
Luke Huangf7277ed2021-07-12 21:15:10 +08001818 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001819 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001820 // The flag of using java backend if the client's target SDK >= U
1821 private final boolean mUseJavaBackend;
Luke Huangf7277ed2021-07-12 21:15:10 +08001822
Paul Hub8a3a632023-04-18 02:45:34 +00001823 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001824 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001825 mUseJavaBackend = useJavaBackend;
Paul Hub8a3a632023-04-18 02:45:34 +00001826 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001827 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001828
1829 @Override
1830 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001831 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001832 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001833 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1834 for (int i = 0; i < mClientRequests.size(); i++) {
1835 int clientID = mClientRequests.keyAt(i);
1836 sb.append("clientId ")
1837 .append(clientID)
1838 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1839 .append(" type ").append(
1840 mClientRequests.valueAt(i).getClass().getSimpleName())
1841 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001842 }
1843 return sb.toString();
1844 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001845
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001846 private boolean isPreSClient() {
1847 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001848 }
1849
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001850 private void setPreSClient() {
1851 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001852 }
1853
Paul Hue4f5f252023-02-16 21:13:47 +08001854 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1855 final MdnsListener listener =
1856 ((DiscoveryManagerRequest) request).mListener;
1857 mMdnsDiscoveryManager.unregisterListener(
1858 listener.getListenedServiceType(), listener);
1859 }
1860
Dave Plattfeff2af2014-03-07 14:48:22 -08001861 // Remove any pending requests from the global map when we get rid of a client,
1862 // and send cancellations to the daemon.
1863 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001864 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001865 for (int i = 0; i < mClientRequests.size(); i++) {
1866 final int clientId = mClientRequests.keyAt(i);
1867 final ClientRequest request = mClientRequests.valueAt(i);
1868 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001869 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001870 if (DBG) {
1871 Log.d(TAG, "Terminating client-ID " + clientId
1872 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1873 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001874
1875 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001876 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001877 continue;
1878 }
1879
1880 if (request instanceof AdvertiserClientRequest) {
1881 mAdvertiser.removeService(globalId);
1882 continue;
1883 }
1884
1885 if (!(request instanceof LegacyClientRequest)) {
1886 throw new IllegalStateException("Unknown request type: " + request.getClass());
1887 }
1888
1889 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001890 case NsdManager.DISCOVER_SERVICES:
1891 stopServiceDiscovery(globalId);
1892 break;
1893 case NsdManager.RESOLVE_SERVICE:
1894 stopResolveService(globalId);
1895 break;
1896 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001897 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001898 break;
1899 default:
1900 break;
1901 }
1902 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001903 mClientRequests.clear();
1904 }
1905
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001906 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1907 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1908 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001909 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001910 for (int i = 0; i < mClientRequests.size(); i++) {
1911 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1912 return mClientRequests.keyAt(i);
1913 }
Christopher Lane74411222014-04-25 18:39:07 -07001914 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001915 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001916 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001917
1918 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1919 try {
1920 mCb.onDiscoverServicesStarted(listenerKey, info);
1921 } catch (RemoteException e) {
1922 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1923 }
1924 }
1925
1926 void onDiscoverServicesFailed(int listenerKey, int error) {
1927 try {
1928 mCb.onDiscoverServicesFailed(listenerKey, error);
1929 } catch (RemoteException e) {
1930 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1931 }
1932 }
1933
1934 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1935 try {
1936 mCb.onServiceFound(listenerKey, info);
1937 } catch (RemoteException e) {
1938 Log.e(TAG, "Error calling onServiceFound(", e);
1939 }
1940 }
1941
1942 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1943 try {
1944 mCb.onServiceLost(listenerKey, info);
1945 } catch (RemoteException e) {
1946 Log.e(TAG, "Error calling onServiceLost(", e);
1947 }
1948 }
1949
1950 void onStopDiscoveryFailed(int listenerKey, int error) {
1951 try {
1952 mCb.onStopDiscoveryFailed(listenerKey, error);
1953 } catch (RemoteException e) {
1954 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1955 }
1956 }
1957
1958 void onStopDiscoverySucceeded(int listenerKey) {
1959 try {
1960 mCb.onStopDiscoverySucceeded(listenerKey);
1961 } catch (RemoteException e) {
1962 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1963 }
1964 }
1965
1966 void onRegisterServiceFailed(int listenerKey, int error) {
1967 try {
1968 mCb.onRegisterServiceFailed(listenerKey, error);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1971 }
1972 }
1973
1974 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1975 try {
1976 mCb.onRegisterServiceSucceeded(listenerKey, info);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1979 }
1980 }
1981
1982 void onUnregisterServiceFailed(int listenerKey, int error) {
1983 try {
1984 mCb.onUnregisterServiceFailed(listenerKey, error);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1987 }
1988 }
1989
1990 void onUnregisterServiceSucceeded(int listenerKey) {
1991 try {
1992 mCb.onUnregisterServiceSucceeded(listenerKey);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1995 }
1996 }
1997
1998 void onResolveServiceFailed(int listenerKey, int error) {
1999 try {
2000 mCb.onResolveServiceFailed(listenerKey, error);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2003 }
2004 }
2005
2006 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2007 try {
2008 mCb.onResolveServiceSucceeded(listenerKey, info);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2011 }
2012 }
Paul Hub58deb72022-12-26 09:24:42 +00002013
2014 void onStopResolutionFailed(int listenerKey, int error) {
2015 try {
2016 mCb.onStopResolutionFailed(listenerKey, error);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2019 }
2020 }
2021
2022 void onStopResolutionSucceeded(int listenerKey) {
2023 try {
2024 mCb.onStopResolutionSucceeded(listenerKey);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2027 }
2028 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002029
2030 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2031 try {
2032 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2035 }
2036 }
2037
2038 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2039 try {
2040 mCb.onServiceUpdated(listenerKey, info);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onServiceUpdated", e);
2043 }
2044 }
2045
2046 void onServiceUpdatedLost(int listenerKey) {
2047 try {
2048 mCb.onServiceUpdatedLost(listenerKey);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2051 }
2052 }
2053
2054 void onServiceInfoCallbackUnregistered(int listenerKey) {
2055 try {
2056 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2057 } catch (RemoteException e) {
2058 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2059 }
2060 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002061 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002062}