blob: cbe6691d8c47dc920089e4d16482ef88b0b385a6 [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;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070075import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090076import java.net.NetworkInterface;
77import java.net.SocketException;
78import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090079import java.nio.ByteBuffer;
80import java.nio.CharBuffer;
81import java.nio.charset.Charset;
82import java.nio.charset.CharsetEncoder;
83import java.nio.charset.StandardCharsets;
Paul Hu2b865912023-03-06 14:27:53 +080084import java.util.ArrayList;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070085import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080086import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080087import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080088import java.util.regex.Matcher;
89import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070090
Irfan Sheriff77ec5582012-03-22 17:01:39 -070091/**
92 * Network Service Discovery Service handles remote service discovery operation requests by
93 * implementing the INsdManager interface.
94 *
95 * @hide
96 */
97public class NsdService extends INsdManager.Stub {
98 private static final String TAG = "NsdService";
99 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900100 /**
101 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
102 * implementation.
103 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800104 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800105 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900106 // Max label length as per RFC 1034/1035
107 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700108
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900109 /**
110 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
111 * implementation.
112 */
113 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
114
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900115 /**
116 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
117 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
118 *
119 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
120 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
121 *
122 * In which case the flags:
123 * "mdns_discovery_manager_allowlist_mytype_version",
124 * "mdns_advertiser_allowlist_mytype_version",
125 * "mdns_discovery_manager_allowlist_othertype_version",
126 * "mdns_advertiser_allowlist_othertype_version"
127 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
128 * be read with
129 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
130 *
131 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
132 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
133 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
134 */
135 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
136
137 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
138 "mdns_discovery_manager_allowlist_";
139 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
140 "mdns_advertiser_allowlist_";
141 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
142
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900143 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000144 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900145 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900148 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800149 private final MDnsManager mMDnsManager;
150 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900151 @NonNull
152 private final Dependencies mDeps;
153 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800154 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900155 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800156 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900160 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800161 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800162 // state machine thread. If change this outside state machine, it will need to introduce
163 // synchronization.
164 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800165 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700166
167 /**
168 * Clients receiving asynchronous messages
169 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900170 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700171
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700172 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900173 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700174
Luke Huang05298582021-06-13 16:52:05 +0000175 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700176
Hugo Benichi32be63d2017-04-05 14:06:11 +0900177 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700178 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800179 // The count of the connected legacy clients.
180 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700181
Paul Hu23fa2022023-01-13 22:57:24 +0800182 private static class MdnsListener implements MdnsServiceBrowserListener {
183 protected final int mClientId;
184 protected final int mTransactionId;
185 @NonNull
186 protected final NsdServiceInfo mReqServiceInfo;
187 @NonNull
188 protected final String mListenedServiceType;
189
190 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
191 @NonNull String listenedServiceType) {
192 mClientId = clientId;
193 mTransactionId = transactionId;
194 mReqServiceInfo = reqServiceInfo;
195 mListenedServiceType = listenedServiceType;
196 }
197
198 @NonNull
199 public String getListenedServiceType() {
200 return mListenedServiceType;
201 }
202
203 @Override
204 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
205
206 @Override
207 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
208
209 @Override
210 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
211
212 @Override
213 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
214
215 @Override
216 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
217
218 @Override
219 public void onSearchStoppedWithError(int error) { }
220
221 @Override
222 public void onSearchFailedToStart() { }
223
224 @Override
225 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
226
227 @Override
228 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
229 }
230
231 private class DiscoveryListener extends MdnsListener {
232
233 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
234 @NonNull String listenServiceType) {
235 super(clientId, transactionId, reqServiceInfo, listenServiceType);
236 }
237
238 @Override
239 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800240 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
241 NsdManager.SERVICE_FOUND,
242 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800243 }
244
245 @Override
246 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800247 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
248 NsdManager.SERVICE_LOST,
249 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800250 }
251 }
252
Paul Hu75069ed2023-01-14 00:31:09 +0800253 private class ResolutionListener extends MdnsListener {
254
255 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
256 @NonNull String listenServiceType) {
257 super(clientId, transactionId, reqServiceInfo, listenServiceType);
258 }
259
260 @Override
261 public void onServiceFound(MdnsServiceInfo serviceInfo) {
262 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
263 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
264 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
265 }
266 }
267
Paul Hu30bd70d2023-02-07 13:20:56 +0000268 private class ServiceInfoListener extends MdnsListener {
269
270 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
271 @NonNull String listenServiceType) {
272 super(clientId, transactionId, reqServiceInfo, listenServiceType);
273 }
274
275 @Override
276 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
277 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
278 NsdManager.SERVICE_UPDATED,
279 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
280 }
281
282 @Override
283 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
284 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
285 NsdManager.SERVICE_UPDATED,
286 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
287 }
288
289 @Override
290 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
291 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
292 NsdManager.SERVICE_UPDATED_LOST,
293 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
294 }
295 }
296
Paul Hu019621e2023-01-13 23:26:49 +0800297 /**
298 * Data class of mdns service callback information.
299 */
300 private static class MdnsEvent {
301 final int mClientId;
302 @NonNull
303 final String mRequestedServiceType;
304 @NonNull
305 final MdnsServiceInfo mMdnsServiceInfo;
306
307 MdnsEvent(int clientId, @NonNull String requestedServiceType,
308 @NonNull MdnsServiceInfo mdnsServiceInfo) {
309 mClientId = clientId;
310 mRequestedServiceType = requestedServiceType;
311 mMdnsServiceInfo = mdnsServiceInfo;
312 }
313 }
314
Irfan Sheriff75006652012-04-17 23:15:29 -0700315 private class NsdStateMachine extends StateMachine {
316
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700317 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700318 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700319
320 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700321 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900322 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700323 }
324
Luke Huang92860f92021-06-23 06:29:30 +0000325 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800326 if (mIsDaemonStarted) {
327 if (DBG) Log.d(TAG, "Daemon is already started.");
328 return;
329 }
330 mMDnsManager.registerEventListener(mMDnsEventCallback);
331 mMDnsManager.startDaemon();
332 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000333 maybeScheduleStop();
334 }
335
paulhu2b9ed952022-02-10 21:58:32 +0800336 private void maybeStopDaemon() {
337 if (!mIsDaemonStarted) {
338 if (DBG) Log.d(TAG, "Daemon has not been started.");
339 return;
340 }
341 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
342 mMDnsManager.stopDaemon();
343 mIsDaemonStarted = false;
344 }
345
Luke Huang92860f92021-06-23 06:29:30 +0000346 private boolean isAnyRequestActive() {
347 return mIdToClientInfoMap.size() != 0;
348 }
349
350 private void scheduleStop() {
351 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
352 }
353 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800354 // The native daemon should stay alive and can't be cleanup
355 // if any legacy client connected.
356 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000357 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000358 }
359 }
360
Luke Huang92860f92021-06-23 06:29:30 +0000361 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000362 this.removeMessages(NsdManager.DAEMON_CLEANUP);
363 }
364
Paul Hu23fa2022023-01-13 22:57:24 +0800365 private void maybeStartMonitoringSockets() {
366 if (mIsMonitoringSocketsStarted) {
367 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
368 return;
369 }
370
371 mMdnsSocketProvider.startMonitoringSockets();
372 mIsMonitoringSocketsStarted = true;
373 }
374
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900375 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
376 if (!mIsMonitoringSocketsStarted) return;
377 if (isAnyRequestActive()) return;
378
Paul Hu58f20602023-02-18 11:41:07 +0800379 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800380 mIsMonitoringSocketsStarted = false;
381 }
382
Hugo Benichi803a2f02017-04-24 11:35:06 +0900383 NsdStateMachine(String name, Handler handler) {
384 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700385 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700386 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800387 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900388 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700389 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 }
391
392 class DefaultState extends State {
393 @Override
394 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900395 final ClientInfo cInfo;
396 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700397 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900398 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800399 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
400 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900401 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800402 cb.asBinder().linkToDeath(arg.connector, 0);
403 cInfo = new ClientInfo(cb, arg.useJavaBackend);
404 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900405 } catch (RemoteException e) {
406 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700407 }
408 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900409 case NsdManager.UNREGISTER_CLIENT:
410 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
411 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800412 if (cInfo != null) {
413 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900414 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800415 mLegacyClientCount -= 1;
416 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800417 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900418 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800419 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700420 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700421 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900422 cInfo = getClientInfoForReply(msg);
423 if (cInfo != null) {
424 cInfo.onDiscoverServicesFailed(
425 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
426 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700427 break;
428 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900429 cInfo = getClientInfoForReply(msg);
430 if (cInfo != null) {
431 cInfo.onStopDiscoveryFailed(
432 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
433 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700434 break;
435 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900436 cInfo = getClientInfoForReply(msg);
437 if (cInfo != null) {
438 cInfo.onRegisterServiceFailed(
439 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
440 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700441 break;
442 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900443 cInfo = getClientInfoForReply(msg);
444 if (cInfo != null) {
445 cInfo.onUnregisterServiceFailed(
446 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
447 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700448 break;
449 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900450 cInfo = getClientInfoForReply(msg);
451 if (cInfo != null) {
452 cInfo.onResolveServiceFailed(
453 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
454 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700455 break;
Paul Hub58deb72022-12-26 09:24:42 +0000456 case NsdManager.STOP_RESOLUTION:
457 cInfo = getClientInfoForReply(msg);
458 if (cInfo != null) {
459 cInfo.onStopResolutionFailed(
460 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
461 }
462 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000463 case NsdManager.REGISTER_SERVICE_CALLBACK:
464 cInfo = getClientInfoForReply(msg);
465 if (cInfo != null) {
466 cInfo.onServiceInfoCallbackRegistrationFailed(
467 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
468 }
469 break;
Luke Huang05298582021-06-13 16:52:05 +0000470 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800471 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000472 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800473 // This event should be only sent by the legacy (target SDK < S) clients.
474 // Mark the sending client as legacy.
475 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900476 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800477 if (cInfo != null) {
478 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900479 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800480 mLegacyClientCount += 1;
481 maybeStartDaemon();
482 }
483 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700484 default:
paulhub2225702021-11-17 09:35:33 +0800485 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700486 return NOT_HANDLED;
487 }
488 return HANDLED;
489 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900490
491 private ClientInfo getClientInfoForReply(Message msg) {
492 final ListenerArgs args = (ListenerArgs) msg.obj;
493 return mClients.get(args.connector);
494 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700495 }
496
Irfan Sheriff75006652012-04-17 23:15:29 -0700497 class EnabledState extends State {
498 @Override
499 public void enter() {
500 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700501 }
502
503 @Override
504 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000505 // TODO: it is incorrect to stop the daemon without expunging all requests
506 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000507 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700508 }
509
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700510 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900511 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800512 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700513 return true;
514 }
515 return false;
516 }
517
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900518 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
519 int what) {
520 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700521 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000522 // Remove the cleanup event because here comes a new request.
523 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700524 }
525
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900526 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800527 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900528 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
529 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800530 }
531
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900532 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
533 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
534 if (existing == null) return;
535 clientInfo.mClientRequests.remove(clientId);
536 mIdToClientInfoMap.remove(globalId);
537
538 if (existing instanceof LegacyClientRequest) {
539 maybeScheduleStop();
540 } else {
541 maybeStopMonitoringSocketsIfNoActiveRequest();
542 }
543 }
544
545 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
546 MdnsListener listener, ClientInfo clientInfo) {
547 clientInfo.mClientRequests.put(clientId,
548 new DiscoveryManagerRequest(globalId, listener));
549 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800550 }
551
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900552 /**
553 * Truncate a service name to up to 63 UTF-8 bytes.
554 *
555 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
556 * names used in registerService follows historical behavior (see mdnsresponder
557 * handle_regservice_request).
558 */
559 @NonNull
560 private String truncateServiceName(@NonNull String originalName) {
561 // UTF-8 is at most 4 bytes per character; return early in the common case where
562 // the name can't possibly be over the limit given its string length.
563 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
564
565 final Charset utf8 = StandardCharsets.UTF_8;
566 final CharsetEncoder encoder = utf8.newEncoder();
567 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
568 // encode will write as many characters as possible to the out buffer, and just
569 // return an overflow code if there were too many characters (no need to check the
570 // return code here, this method truncates the name on purpose).
571 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
572 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800573 }
574
Paul Hue4f5f252023-02-16 21:13:47 +0800575 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
576 ClientInfo clientInfo) {
577 clientInfo.unregisterMdnsListenerFromRequest(request);
578 removeRequestMap(clientId, id, clientInfo);
579 }
580
Irfan Sheriff75006652012-04-17 23:15:29 -0700581 @Override
582 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900583 final ClientInfo clientInfo;
584 final int id;
585 final int clientId = msg.arg2;
586 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700587 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800588 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800589 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900590 args = (ListenerArgs) msg.obj;
591 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000592 // If the binder death notification for a INsdManagerCallback was received
593 // before any calls are received by NsdService, the clientInfo would be
594 // cleared and cause NPE. Add a null check here to prevent this corner case.
595 if (clientInfo == null) {
596 Log.e(TAG, "Unknown connector in discovery");
597 break;
598 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700599
600 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900601 clientInfo.onDiscoverServicesFailed(
602 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700603 break;
604 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700605
Paul Hu23fa2022023-01-13 22:57:24 +0800606 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700607 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900608 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800609 if (clientInfo.mUseJavaBackend
610 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900611 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800612 if (serviceType == null) {
613 clientInfo.onDiscoverServicesFailed(clientId,
614 NsdManager.FAILURE_INTERNAL_ERROR);
615 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700616 }
Paul Hu23fa2022023-01-13 22:57:24 +0800617
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900618 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800619 maybeStartMonitoringSockets();
620 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900621 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800622 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
623 .setNetwork(info.getNetwork())
624 .setIsPassiveMode(true)
625 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900626 mMdnsDiscoveryManager.registerListener(
627 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900628 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800629 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700630 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800631 maybeStartDaemon();
632 if (discoverServices(id, info)) {
633 if (DBG) {
634 Log.d(TAG, "Discover " + msg.arg2 + " " + id
635 + info.getServiceType());
636 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900637 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800638 clientInfo.onDiscoverServicesStarted(clientId, info);
639 } else {
640 stopServiceDiscovery(id);
641 clientInfo.onDiscoverServicesFailed(clientId,
642 NsdManager.FAILURE_INTERNAL_ERROR);
643 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 }
645 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800646 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900647 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800648 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900649 args = (ListenerArgs) msg.obj;
650 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000651 // If the binder death notification for a INsdManagerCallback was received
652 // before any calls are received by NsdService, the clientInfo would be
653 // cleared and cause NPE. Add a null check here to prevent this corner case.
654 if (clientInfo == null) {
655 Log.e(TAG, "Unknown connector in stop discovery");
656 break;
657 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700658
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900659 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
660 if (request == null) {
661 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700662 break;
663 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900664 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900665 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
666 // point, so this needs to check the type of the original request to
667 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900668 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800669 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900670 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700671 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800672 removeRequestMap(clientId, id, clientInfo);
673 if (stopServiceDiscovery(id)) {
674 clientInfo.onStopDiscoverySucceeded(clientId);
675 } else {
676 clientInfo.onStopDiscoveryFailed(
677 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
678 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700679 }
680 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900681 }
682 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800683 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900684 args = (ListenerArgs) msg.obj;
685 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000686 // If the binder death notification for a INsdManagerCallback was received
687 // before any calls are received by NsdService, the clientInfo would be
688 // cleared and cause NPE. Add a null check here to prevent this corner case.
689 if (clientInfo == null) {
690 Log.e(TAG, "Unknown connector in registration");
691 break;
692 }
693
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700694 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900695 clientInfo.onRegisterServiceFailed(
696 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700697 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700698 }
699
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700700 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900701 final NsdServiceInfo serviceInfo = args.serviceInfo;
702 final String serviceType = serviceInfo.getServiceType();
703 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800704 if (clientInfo.mUseJavaBackend
705 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900706 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900707 if (registerServiceType == null) {
708 Log.e(TAG, "Invalid service type: " + serviceType);
709 clientInfo.onRegisterServiceFailed(clientId,
710 NsdManager.FAILURE_INTERNAL_ERROR);
711 break;
712 }
713 serviceInfo.setServiceType(registerServiceType);
714 serviceInfo.setServiceName(truncateServiceName(
715 serviceInfo.getServiceName()));
716
717 maybeStartMonitoringSockets();
718 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900719 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700720 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900721 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900722 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900723 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900724 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900725 // Return success after mDns reports success
726 } else {
727 unregisterService(id);
728 clientInfo.onRegisterServiceFailed(
729 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
730 }
731
Irfan Sheriff75006652012-04-17 23:15:29 -0700732 }
733 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900734 }
735 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800736 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900737 args = (ListenerArgs) msg.obj;
738 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000739 // If the binder death notification for a INsdManagerCallback was received
740 // before any calls are received by NsdService, the clientInfo would be
741 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900742 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800743 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700744 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700745 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900746 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
747 if (request == null) {
748 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
749 break;
750 }
751 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900752 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900753
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900754 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
755 // so this needs to check the type of the original request to unregister
756 // instead of looking at the flag value.
757 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900758 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900759 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700760 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900761 if (unregisterService(id)) {
762 clientInfo.onUnregisterServiceSucceeded(clientId);
763 } else {
764 clientInfo.onUnregisterServiceFailed(
765 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
766 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700767 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700768 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900769 }
Paul Hu75069ed2023-01-14 00:31:09 +0800770 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800771 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900772 args = (ListenerArgs) msg.obj;
773 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000774 // If the binder death notification for a INsdManagerCallback was received
775 // before any calls are received by NsdService, the clientInfo would be
776 // cleared and cause NPE. Add a null check here to prevent this corner case.
777 if (clientInfo == null) {
778 Log.e(TAG, "Unknown connector in resolution");
779 break;
780 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700781
Paul Hu75069ed2023-01-14 00:31:09 +0800782 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700783 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900784 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800785 if (clientInfo.mUseJavaBackend
786 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900787 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800788 if (serviceType == null) {
789 clientInfo.onResolveServiceFailed(clientId,
790 NsdManager.FAILURE_INTERNAL_ERROR);
791 break;
792 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900793 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800794
795 maybeStartMonitoringSockets();
796 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900797 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800798 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
799 .setNetwork(info.getNetwork())
800 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900801 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800802 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900803 mMdnsDiscoveryManager.registerListener(
804 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900805 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700806 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800807 if (clientInfo.mResolvedService != null) {
808 clientInfo.onResolveServiceFailed(
809 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
810 break;
811 }
812
813 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900814 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800815 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900816 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800817 } else {
818 clientInfo.onResolveServiceFailed(
819 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
820 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700821 }
822 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800823 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900824 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000825 if (DBG) Log.d(TAG, "Stop service resolution");
826 args = (ListenerArgs) msg.obj;
827 clientInfo = mClients.get(args.connector);
828 // If the binder death notification for a INsdManagerCallback was received
829 // before any calls are received by NsdService, the clientInfo would be
830 // cleared and cause NPE. Add a null check here to prevent this corner case.
831 if (clientInfo == null) {
832 Log.e(TAG, "Unknown connector in stop resolution");
833 break;
834 }
835
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900836 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
837 if (request == null) {
838 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
839 break;
840 }
841 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800842 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
843 // point, so this needs to check the type of the original request to
844 // unregister instead of looking at the flag value.
845 if (request instanceof DiscoveryManagerRequest) {
846 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000847 clientInfo.onStopResolutionSucceeded(clientId);
848 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800849 removeRequestMap(clientId, id, clientInfo);
850 if (stopResolveService(id)) {
851 clientInfo.onStopResolutionSucceeded(clientId);
852 } else {
853 clientInfo.onStopResolutionFailed(
854 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
855 }
856 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000857 }
Paul Hub58deb72022-12-26 09:24:42 +0000858 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900859 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000860 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000861 if (DBG) Log.d(TAG, "Register a service callback");
862 args = (ListenerArgs) msg.obj;
863 clientInfo = mClients.get(args.connector);
864 // If the binder death notification for a INsdManagerCallback was received
865 // before any calls are received by NsdService, the clientInfo would be
866 // cleared and cause NPE. Add a null check here to prevent this corner case.
867 if (clientInfo == null) {
868 Log.e(TAG, "Unknown connector in callback registration");
869 break;
870 }
871
Paul Hu30bd70d2023-02-07 13:20:56 +0000872 final NsdServiceInfo info = args.serviceInfo;
873 id = getUniqueId();
874 final String serviceType = constructServiceType(info.getServiceType());
875 if (serviceType == null) {
876 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
877 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000878 break;
879 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000880 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000881
Paul Hu30bd70d2023-02-07 13:20:56 +0000882 maybeStartMonitoringSockets();
883 final MdnsListener listener =
884 new ServiceInfoListener(clientId, id, info, resolveServiceType);
885 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
886 .setNetwork(info.getNetwork())
887 .setIsPassiveMode(true)
888 .setResolveInstanceName(info.getServiceName())
889 .build();
890 mMdnsDiscoveryManager.registerListener(
891 resolveServiceType, listener, options);
892 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000893 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000894 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900895 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000896 if (DBG) Log.d(TAG, "Unregister a service callback");
897 args = (ListenerArgs) msg.obj;
898 clientInfo = mClients.get(args.connector);
899 // If the binder death notification for a INsdManagerCallback was received
900 // before any calls are received by NsdService, the clientInfo would be
901 // cleared and cause NPE. Add a null check here to prevent this corner case.
902 if (clientInfo == null) {
903 Log.e(TAG, "Unknown connector in callback unregistration");
904 break;
905 }
906
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900907 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
908 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000909 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900910 break;
911 }
912 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000913 if (request instanceof DiscoveryManagerRequest) {
914 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000915 clientInfo.onServiceInfoCallbackUnregistered(clientId);
916 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000917 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000918 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000919 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900920 }
paulhu2b9ed952022-02-10 21:58:32 +0800921 case MDNS_SERVICE_EVENT:
922 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900923 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700924 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700925 break;
Paul Hu019621e2023-01-13 23:26:49 +0800926 case MDNS_DISCOVERY_MANAGER_EVENT:
927 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
928 return NOT_HANDLED;
929 }
930 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700931 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900932 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700933 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900934 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700935 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700936
paulhu2b9ed952022-02-10 21:58:32 +0800937 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700938 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700939 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
940 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800941 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900942 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700943 }
944
945 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700946 int clientId = clientInfo.getClientId(id);
947 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700948 // This can happen because of race conditions. For example,
949 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
950 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800951 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
952 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900953 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700954 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900955 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800956 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900957 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700958 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800959 case IMDnsEventListener.SERVICE_FOUND: {
960 final DiscoveryInfo info = (DiscoveryInfo) obj;
961 final String name = info.serviceName;
962 final String type = info.registrationType;
963 servInfo = new NsdServiceInfo(name, type);
964 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900965 if (foundNetId == 0L) {
966 // Ignore services that do not have a Network: they are not usable
967 // by apps, as they would need privileged permissions to use
968 // interfaces that do not have an associated Network.
969 break;
970 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900971 if (foundNetId == INetd.DUMMY_NET_ID) {
972 // Ignore services on the dummy0 interface: they are only seen when
973 // discovering locally advertised services, and are not reachable
974 // through that interface.
975 break;
976 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900977 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900978 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700979 break;
paulhu2b9ed952022-02-10 21:58:32 +0800980 }
981 case IMDnsEventListener.SERVICE_LOST: {
982 final DiscoveryInfo info = (DiscoveryInfo) obj;
983 final String name = info.serviceName;
984 final String type = info.registrationType;
985 final int lostNetId = info.netId;
986 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900987 // The network could be set to null (netId 0) if it was torn down when the
988 // service is lost
989 // TODO: avoid returning null in that case, possibly by remembering
990 // found services on the same interface index and their network at the time
991 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900992 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700993 break;
paulhu2b9ed952022-02-10 21:58:32 +0800994 }
995 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900996 clientInfo.onDiscoverServicesFailed(
997 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700998 break;
paulhu2b9ed952022-02-10 21:58:32 +0800999 case IMDnsEventListener.SERVICE_REGISTERED: {
1000 final RegistrationInfo info = (RegistrationInfo) obj;
1001 final String name = info.serviceName;
1002 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001003 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001004 break;
paulhu2b9ed952022-02-10 21:58:32 +08001005 }
1006 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001007 clientInfo.onRegisterServiceFailed(
1008 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001009 break;
paulhu2b9ed952022-02-10 21:58:32 +08001010 case IMDnsEventListener.SERVICE_RESOLVED: {
1011 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001012 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001013 final String fullName = info.serviceFullName;
1014 while (index < fullName.length() && fullName.charAt(index) != '.') {
1015 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001016 ++index;
1017 }
1018 ++index;
1019 }
paulhu2b9ed952022-02-10 21:58:32 +08001020 if (index >= fullName.length()) {
1021 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001022 break;
1023 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001024
paulhube186602022-04-12 07:18:23 +00001025 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001026 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001027 String type = rest.replace(".local.", "");
1028
Paul Hu30bd70d2023-02-07 13:20:56 +00001029 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001030 serviceInfo.setServiceName(name);
1031 serviceInfo.setServiceType(type);
1032 serviceInfo.setPort(info.port);
1033 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001034 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001035
1036 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001037 removeRequestMap(clientId, id, clientInfo);
1038
paulhu2b9ed952022-02-10 21:58:32 +08001039 final int id2 = getUniqueId();
1040 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001041 storeLegacyRequestMap(clientId, id2, clientInfo,
1042 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001043 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001044 clientInfo.onResolveServiceFailed(
1045 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1046 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001047 }
1048 break;
paulhu2b9ed952022-02-10 21:58:32 +08001049 }
1050 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001051 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001052 stopResolveService(id);
1053 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001054 clientInfo.onResolveServiceFailed(
1055 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1056 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001057 break;
paulhu2b9ed952022-02-10 21:58:32 +08001058 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001059 /* NNN resolveId errorCode */
1060 stopGetAddrInfo(id);
1061 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001062 clientInfo.onResolveServiceFailed(
1063 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1064 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001065 break;
paulhu2b9ed952022-02-10 21:58:32 +08001066 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001067 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001068 final GetAddressInfo info = (GetAddressInfo) obj;
1069 final String address = info.address;
1070 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001071 InetAddress serviceHost = null;
1072 try {
paulhu2b9ed952022-02-10 21:58:32 +08001073 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001074 } catch (UnknownHostException e) {
1075 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1076 }
1077
1078 // If the resolved service is on an interface without a network, consider it
1079 // as a failure: it would not be usable by apps as they would need
1080 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001081 if (netId != NETID_UNSET && serviceHost != null) {
1082 clientInfo.mResolvedService.setHost(serviceHost);
1083 setServiceNetworkForCallback(clientInfo.mResolvedService,
1084 netId, info.interfaceIdx);
1085 clientInfo.onResolveServiceSucceeded(
1086 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001087 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001088 clientInfo.onResolveServiceFailed(
1089 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001090 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001091 stopGetAddrInfo(id);
1092 removeRequestMap(clientId, id, clientInfo);
1093 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001094 break;
paulhu2b9ed952022-02-10 21:58:32 +08001095 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001096 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001097 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001098 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001099 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001100 }
Paul Hu019621e2023-01-13 23:26:49 +08001101
1102 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1103 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1104 final String serviceType = event.mRequestedServiceType;
1105 final String serviceName = serviceInfo.getServiceInstanceName();
1106 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1107 final Network network = serviceInfo.getNetwork();
1108 setServiceNetworkForCallback(
1109 servInfo,
1110 network == null ? NETID_UNSET : network.netId,
1111 serviceInfo.getInterfaceIndex());
1112 return servInfo;
1113 }
1114
1115 private boolean handleMdnsDiscoveryManagerEvent(
1116 int transactionId, int code, Object obj) {
1117 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1118 if (clientInfo == null) {
1119 Log.e(TAG, String.format(
1120 "id %d for %d has no client mapping", transactionId, code));
1121 return false;
1122 }
1123
1124 final MdnsEvent event = (MdnsEvent) obj;
1125 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001126 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001127 if (DBG) {
1128 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1129 NsdManager.nameOf(code), transactionId));
1130 }
1131 switch (code) {
1132 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001133 clientInfo.onServiceFound(clientId, info);
1134 break;
1135 case NsdManager.SERVICE_LOST:
1136 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001137 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001138 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001139 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1140 if (request == null) {
1141 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1142 break;
1143 }
Paul Hu75069ed2023-01-14 00:31:09 +08001144 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1145 // Add '.' in front of the service type that aligns with historical behavior
1146 info.setServiceType("." + event.mRequestedServiceType);
1147 info.setPort(serviceInfo.getPort());
1148
1149 Map<String, String> attrs = serviceInfo.getAttributes();
1150 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1151 final String key = kv.getKey();
1152 try {
1153 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1154 } catch (IllegalArgumentException e) {
1155 Log.e(TAG, "Invalid attribute", e);
1156 }
1157 }
Paul Hu2b865912023-03-06 14:27:53 +08001158 final List<InetAddress> addresses = new ArrayList<>();
1159 for (String ipv4Address : serviceInfo.getIpv4Addresses()) {
1160 try {
1161 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1162 } catch (IllegalArgumentException e) {
1163 Log.wtf(TAG, "Invalid ipv4 address", e);
Paul Hu75069ed2023-01-14 00:31:09 +08001164 }
Paul Hu2b865912023-03-06 14:27:53 +08001165 }
1166 for (String ipv6Address : serviceInfo.getIpv6Addresses()) {
1167 try {
1168 addresses.add(InetAddresses.parseNumericAddress(ipv6Address));
1169 } catch (IllegalArgumentException e) {
1170 Log.wtf(TAG, "Invalid ipv6 address", e);
1171 }
1172 }
1173
1174 if (addresses.size() != 0) {
1175 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001176 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001177 } else {
1178 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001179 clientInfo.onResolveServiceFailed(
1180 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1181 }
1182
1183 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001184 if (!(request instanceof DiscoveryManagerRequest)) {
1185 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1186 break;
1187 }
Paul Hue4f5f252023-02-16 21:13:47 +08001188 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001189 break;
1190 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001191 case NsdManager.SERVICE_UPDATED: {
1192 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1193 info.setPort(serviceInfo.getPort());
1194
1195 Map<String, String> attrs = serviceInfo.getAttributes();
1196 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1197 final String key = kv.getKey();
1198 try {
1199 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1200 } catch (IllegalArgumentException e) {
1201 Log.e(TAG, "Invalid attribute", e);
1202 }
1203 }
1204
1205 final List<InetAddress> addresses = new ArrayList<>();
1206 for (String ipv4Address : serviceInfo.getIpv4Addresses()) {
1207 try {
1208 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1209 } catch (IllegalArgumentException e) {
1210 Log.wtf(TAG, "Invalid ipv4 address", e);
1211 }
1212 }
1213 for (String ipv6Address : serviceInfo.getIpv6Addresses()) {
1214 try {
1215 addresses.add(InetAddresses.parseNumericAddress(ipv6Address));
1216 } catch (IllegalArgumentException e) {
1217 Log.wtf(TAG, "Invalid ipv6 address", e);
1218 }
1219 }
1220 info.setHostAddresses(addresses);
1221 clientInfo.onServiceUpdated(clientId, info);
1222 break;
1223 }
1224 case NsdManager.SERVICE_UPDATED_LOST:
1225 clientInfo.onServiceUpdatedLost(clientId);
1226 break;
Paul Hu019621e2023-01-13 23:26:49 +08001227 default:
1228 return false;
1229 }
1230 return true;
1231 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001232 }
1233 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001234
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001235 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1236 switch (netId) {
1237 case NETID_UNSET:
1238 info.setNetwork(null);
1239 break;
1240 case INetd.LOCAL_NET_ID:
1241 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1242 // visible / usable for apps, so do not return it. Store the interface
1243 // index instead, so at least if the client tries to resolve the service
1244 // with that NsdServiceInfo, it will be done on the same interface.
1245 // If they recreate the NsdServiceInfo themselves, resolution would be
1246 // done on all interfaces as before T, which should also work.
1247 info.setNetwork(null);
1248 info.setInterfaceIndex(ifaceIdx);
1249 break;
1250 default:
1251 info.setNetwork(new Network(netId));
1252 }
1253 }
1254
paulhube186602022-04-12 07:18:23 +00001255 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1256 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1257 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1258 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1259 private String unescape(String s) {
1260 StringBuilder sb = new StringBuilder(s.length());
1261 for (int i = 0; i < s.length(); ++i) {
1262 char c = s.charAt(i);
1263 if (c == '\\') {
1264 if (++i >= s.length()) {
1265 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1266 break;
1267 }
1268 c = s.charAt(i);
1269 if (c != '.' && c != '\\') {
1270 if (i + 2 >= s.length()) {
1271 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1272 break;
1273 }
1274 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1275 + (s.charAt(i + 2) - '0'));
1276 i += 2;
1277 }
1278 }
1279 sb.append(c);
1280 }
1281 return sb.toString();
1282 }
1283
Paul Hu7445e3d2023-03-03 15:14:00 +08001284 /**
1285 * Check the given service type is valid and construct it to a service type
1286 * which can use for discovery / resolution service.
1287 *
1288 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1289 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1290 * underscore; they are alphanumerical characters or dashes or underscore, except the
1291 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1292 *
1293 * @param serviceType the request service type for discovery / resolution service
1294 * @return constructed service type or null if the given service type is invalid.
1295 */
1296 @Nullable
1297 public static String constructServiceType(String serviceType) {
1298 if (TextUtils.isEmpty(serviceType)) return null;
1299
1300 final Pattern serviceTypePattern = Pattern.compile(
1301 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1302 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1303 // Drop '.' at the end of service type that is compatible with old backend.
1304 + "\\.?$");
1305 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1306 if (!matcher.matches()) return null;
1307 return matcher.group(1) == null
1308 ? matcher.group(2)
1309 : matcher.group(1) + "_sub." + matcher.group(2);
1310 }
1311
Hugo Benichi803a2f02017-04-24 11:35:06 +09001312 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001313 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001314 this(ctx, handler, cleanupDelayMs, new Dependencies());
1315 }
1316
1317 @VisibleForTesting
1318 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001319 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001320 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001321 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001322 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001323 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1324 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001325 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001326
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001327 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1328 mMdnsSocketClient =
1329 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1330 mMdnsDiscoveryManager =
1331 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1332 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1333 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1334 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001335 }
1336
1337 /**
1338 * Dependencies of NsdService, for injection in tests.
1339 */
1340 @VisibleForTesting
1341 public static class Dependencies {
1342 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001343 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001344 *
1345 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001346 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001347 */
1348 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001349 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1350 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1351 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001352 }
1353
1354 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001355 * Check whether the MdnsAdvertiser feature is enabled.
1356 *
1357 * @param context The global context information about an app environment.
1358 * @return true if the MdnsAdvertiser feature is enabled.
1359 */
1360 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001361 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1362 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001363 }
1364
1365 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001366 * Get the type allowlist flag value.
1367 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1368 */
1369 @Nullable
1370 public String getTypeAllowlistFlags() {
1371 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1372 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1373 }
1374
1375 /**
1376 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1377 */
1378 public boolean isFeatureEnabled(Context context, String feature) {
1379 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1380 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1381 }
1382
1383 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001384 * @see MdnsDiscoveryManager
1385 */
1386 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1387 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1388 return new MdnsDiscoveryManager(executorProvider, socketClient);
1389 }
1390
1391 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001392 * @see MdnsAdvertiser
1393 */
1394 public MdnsAdvertiser makeMdnsAdvertiser(
1395 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1396 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1397 return new MdnsAdvertiser(looper, socketProvider, cb);
1398 }
1399
1400 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001401 * @see MdnsSocketProvider
1402 */
1403 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1404 return new MdnsSocketProvider(context, looper);
1405 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001406 }
1407
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001408 /**
1409 * Return whether a type is allowlisted to use the Java backend.
1410 * @param type The service type
1411 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1412 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1413 */
1414 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1415 @NonNull String flagPrefix) {
1416 if (type == null) return false;
1417 final String typesConfig = mDeps.getTypeAllowlistFlags();
1418 if (TextUtils.isEmpty(typesConfig)) return false;
1419
1420 final String mappingPrefix = type + ":";
1421 String mappedFlag = null;
1422 for (String mapping : TextUtils.split(typesConfig, ",")) {
1423 if (mapping.startsWith(mappingPrefix)) {
1424 mappedFlag = mapping.substring(mappingPrefix.length());
1425 break;
1426 }
1427 }
1428
1429 if (mappedFlag == null) return false;
1430
1431 return mDeps.isFeatureEnabled(mContext,
1432 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1433 }
1434
1435 private boolean useDiscoveryManagerForType(@Nullable String type) {
1436 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1437 }
1438
1439 private boolean useAdvertiserForType(@Nullable String type) {
1440 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1441 }
1442
paulhu1b35e822022-04-08 14:48:41 +08001443 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001444 HandlerThread thread = new HandlerThread(TAG);
1445 thread.start();
1446 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001447 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001448 return service;
1449 }
1450
paulhu2b9ed952022-02-10 21:58:32 +08001451 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1452 private final StateMachine mStateMachine;
1453
1454 MDnsEventCallback(StateMachine sm) {
1455 mStateMachine = sm;
1456 }
1457
1458 @Override
1459 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1460 mStateMachine.sendMessage(
1461 MDNS_SERVICE_EVENT, status.result, status.id, status);
1462 }
1463
1464 @Override
1465 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1466 mStateMachine.sendMessage(
1467 MDNS_SERVICE_EVENT, status.result, status.id, status);
1468 }
1469
1470 @Override
1471 public void onServiceResolutionStatus(final ResolutionInfo status) {
1472 mStateMachine.sendMessage(
1473 MDNS_SERVICE_EVENT, status.result, status.id, status);
1474 }
1475
1476 @Override
1477 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1478 mStateMachine.sendMessage(
1479 MDNS_SERVICE_EVENT, status.result, status.id, status);
1480 }
1481
1482 @Override
1483 public int getInterfaceVersion() throws RemoteException {
1484 return this.VERSION;
1485 }
1486
1487 @Override
1488 public String getInterfaceHash() throws RemoteException {
1489 return this.HASH;
1490 }
1491 }
1492
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001493 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1494 @Override
1495 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1496 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1497 if (clientInfo == null) return;
1498
1499 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1500 if (clientId < 0) return;
1501
1502 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1503 // historical behavior.
1504 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1505 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1506 }
1507
1508 @Override
1509 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1510 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1511 if (clientInfo == null) return;
1512
1513 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1514 if (clientId < 0) return;
1515
1516 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1517 }
1518
1519 private ClientInfo getClientInfoOrLog(int serviceId) {
1520 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1521 if (clientInfo == null) {
1522 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1523 }
1524 return clientInfo;
1525 }
1526
1527 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1528 final int clientId = info.getClientId(serviceId);
1529 if (clientId < 0) {
1530 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1531 }
1532 return clientId;
1533 }
1534 }
1535
Paul Hu2e0a88c2023-03-09 16:05:01 +08001536 private static class ConnectorArgs {
1537 @NonNull public final NsdServiceConnector connector;
1538 @NonNull public final INsdManagerCallback callback;
1539 public final boolean useJavaBackend;
1540
1541 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
1542 boolean useJavaBackend) {
1543 this.connector = connector;
1544 this.callback = callback;
1545 this.useJavaBackend = useJavaBackend;
1546 }
1547 }
1548
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001549 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001550 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001552 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001553 final INsdServiceConnector connector = new NsdServiceConnector();
1554 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
Paul Hu2e0a88c2023-03-09 16:05:01 +08001555 NsdManager.REGISTER_CLIENT,
1556 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001557 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001558 }
1559
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001560 private static class ListenerArgs {
1561 public final NsdServiceConnector connector;
1562 public final NsdServiceInfo serviceInfo;
1563 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1564 this.connector = connector;
1565 this.serviceInfo = serviceInfo;
1566 }
1567 }
1568
1569 private class NsdServiceConnector extends INsdServiceConnector.Stub
1570 implements IBinder.DeathRecipient {
1571 @Override
1572 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1573 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1574 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1575 new ListenerArgs(this, serviceInfo)));
1576 }
1577
1578 @Override
1579 public void unregisterService(int listenerKey) {
1580 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1581 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1582 new ListenerArgs(this, null)));
1583 }
1584
1585 @Override
1586 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1587 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1588 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1589 new ListenerArgs(this, serviceInfo)));
1590 }
1591
1592 @Override
1593 public void stopDiscovery(int listenerKey) {
1594 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1595 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1596 }
1597
1598 @Override
1599 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1600 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1601 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1602 new ListenerArgs(this, serviceInfo)));
1603 }
1604
1605 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001606 public void stopResolution(int listenerKey) {
1607 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1608 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1609 }
1610
1611 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001612 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1613 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1614 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1615 new ListenerArgs(this, serviceInfo)));
1616 }
1617
1618 @Override
1619 public void unregisterServiceInfoCallback(int listenerKey) {
1620 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1621 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1622 new ListenerArgs(this, null)));
1623 }
1624
1625 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001626 public void startDaemon() {
1627 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1628 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1629 }
1630
1631 @Override
1632 public void binderDied() {
1633 mNsdStateMachine.sendMessage(
1634 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1635 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001636 }
1637
Hugo Benichi912db992017-04-24 16:41:03 +09001638 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001639 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001640 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001641 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1642 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001643 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001644 }
1645
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001646 private int getUniqueId() {
1647 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1648 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001649 }
1650
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001651 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001652 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001653 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001654 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001655 String name = service.getServiceName();
1656 String type = service.getServiceType();
1657 int port = service.getPort();
1658 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001659 final int registerInterface = getNetworkInterfaceIndex(service);
1660 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001661 Log.e(TAG, "Interface to register service on not found");
1662 return false;
1663 }
1664 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001665 }
1666
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001667 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001668 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001669 }
1670
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001671 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001672 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001673 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1674 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001675 Log.e(TAG, "Interface to discover service on not found");
1676 return false;
1677 }
paulhu2b9ed952022-02-10 21:58:32 +08001678 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001679 }
1680
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001681 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001682 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001683 }
1684
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001685 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001686 final String name = service.getServiceName();
1687 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001688 final int resolveInterface = getNetworkInterfaceIndex(service);
1689 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001690 Log.e(TAG, "Interface to resolve service on not found");
1691 return false;
1692 }
paulhu2b9ed952022-02-10 21:58:32 +08001693 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001694 }
1695
1696 /**
1697 * Guess the interface to use to resolve or discover a service on a specific network.
1698 *
1699 * This is an imperfect guess, as for example the network may be gone or not yet fully
1700 * registered. This is fine as failing is correct if the network is gone, and a client
1701 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1702 * this is to support the legacy mdnsresponder implementation, which historically resolved
1703 * services on an unspecified network.
1704 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001705 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1706 final Network network = serviceInfo.getNetwork();
1707 if (network == null) {
1708 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1709 // provided by NsdService from discovery results, and the service was found on an
1710 // interface that has no app-usable Network).
1711 if (serviceInfo.getInterfaceIndex() != 0) {
1712 return serviceInfo.getInterfaceIndex();
1713 }
1714 return IFACE_IDX_ANY;
1715 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001716
1717 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1718 if (cm == null) {
1719 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1720 return IFACE_IDX_ANY;
1721 }
1722 final LinkProperties lp = cm.getLinkProperties(network);
1723 if (lp == null) return IFACE_IDX_ANY;
1724
1725 // Only resolve on non-stacked interfaces
1726 final NetworkInterface iface;
1727 try {
1728 iface = NetworkInterface.getByName(lp.getInterfaceName());
1729 } catch (SocketException e) {
1730 Log.e(TAG, "Error querying interface", e);
1731 return IFACE_IDX_ANY;
1732 }
1733
1734 if (iface == null) {
1735 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1736 return IFACE_IDX_ANY;
1737 }
1738
1739 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001740 }
1741
1742 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001743 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001744 }
1745
paulhu2b9ed952022-02-10 21:58:32 +08001746 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1747 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001748 }
1749
1750 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001751 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001752 }
1753
1754 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001755 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001756 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001757
Irfan Sheriff75006652012-04-17 23:15:29 -07001758 for (ClientInfo client : mClients.values()) {
1759 pw.println("Client Info");
1760 pw.println(client);
1761 }
1762
1763 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001764 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001765
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001766 private abstract static class ClientRequest {
1767 private final int mGlobalId;
1768
1769 private ClientRequest(int globalId) {
1770 mGlobalId = globalId;
1771 }
1772 }
1773
1774 private static class LegacyClientRequest extends ClientRequest {
1775 private final int mRequestCode;
1776
1777 private LegacyClientRequest(int globalId, int requestCode) {
1778 super(globalId);
1779 mRequestCode = requestCode;
1780 }
1781 }
1782
1783 private static class AdvertiserClientRequest extends ClientRequest {
1784 private AdvertiserClientRequest(int globalId) {
1785 super(globalId);
1786 }
1787 }
1788
1789 private static class DiscoveryManagerRequest extends ClientRequest {
1790 @NonNull
1791 private final MdnsListener mListener;
1792
1793 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1794 super(globalId);
1795 mListener = listener;
1796 }
1797 }
1798
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001799 /* Information tracked per client */
1800 private class ClientInfo {
1801
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001802 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001803 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001804 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001805 private NsdServiceInfo mResolvedService;
1806
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001807 /* A map from client-side ID (listenerKey) to the request */
1808 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001809
Luke Huangf7277ed2021-07-12 21:15:10 +08001810 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001811 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001812 // The flag of using java backend if the client's target SDK >= U
1813 private final boolean mUseJavaBackend;
Luke Huangf7277ed2021-07-12 21:15:10 +08001814
Paul Hu2e0a88c2023-03-09 16:05:01 +08001815 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001816 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001817 mUseJavaBackend = useJavaBackend;
paulhub2225702021-11-17 09:35:33 +08001818 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001819 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001820
1821 @Override
1822 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001823 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001824 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001825 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1826 for (int i = 0; i < mClientRequests.size(); i++) {
1827 int clientID = mClientRequests.keyAt(i);
1828 sb.append("clientId ")
1829 .append(clientID)
1830 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1831 .append(" type ").append(
1832 mClientRequests.valueAt(i).getClass().getSimpleName())
1833 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001834 }
1835 return sb.toString();
1836 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001837
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001838 private boolean isPreSClient() {
1839 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001840 }
1841
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001842 private void setPreSClient() {
1843 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001844 }
1845
Paul Hue4f5f252023-02-16 21:13:47 +08001846 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1847 final MdnsListener listener =
1848 ((DiscoveryManagerRequest) request).mListener;
1849 mMdnsDiscoveryManager.unregisterListener(
1850 listener.getListenedServiceType(), listener);
1851 }
1852
Dave Plattfeff2af2014-03-07 14:48:22 -08001853 // Remove any pending requests from the global map when we get rid of a client,
1854 // and send cancellations to the daemon.
1855 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001856 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001857 for (int i = 0; i < mClientRequests.size(); i++) {
1858 final int clientId = mClientRequests.keyAt(i);
1859 final ClientRequest request = mClientRequests.valueAt(i);
1860 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001861 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001862 if (DBG) {
1863 Log.d(TAG, "Terminating client-ID " + clientId
1864 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1865 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001866
1867 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001868 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001869 continue;
1870 }
1871
1872 if (request instanceof AdvertiserClientRequest) {
1873 mAdvertiser.removeService(globalId);
1874 continue;
1875 }
1876
1877 if (!(request instanceof LegacyClientRequest)) {
1878 throw new IllegalStateException("Unknown request type: " + request.getClass());
1879 }
1880
1881 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001882 case NsdManager.DISCOVER_SERVICES:
1883 stopServiceDiscovery(globalId);
1884 break;
1885 case NsdManager.RESOLVE_SERVICE:
1886 stopResolveService(globalId);
1887 break;
1888 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001889 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001890 break;
1891 default:
1892 break;
1893 }
1894 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001895 mClientRequests.clear();
1896 }
1897
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001898 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1899 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1900 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001901 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001902 for (int i = 0; i < mClientRequests.size(); i++) {
1903 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1904 return mClientRequests.keyAt(i);
1905 }
Christopher Lane74411222014-04-25 18:39:07 -07001906 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001907 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001908 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001909
1910 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1911 try {
1912 mCb.onDiscoverServicesStarted(listenerKey, info);
1913 } catch (RemoteException e) {
1914 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1915 }
1916 }
1917
1918 void onDiscoverServicesFailed(int listenerKey, int error) {
1919 try {
1920 mCb.onDiscoverServicesFailed(listenerKey, error);
1921 } catch (RemoteException e) {
1922 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1923 }
1924 }
1925
1926 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1927 try {
1928 mCb.onServiceFound(listenerKey, info);
1929 } catch (RemoteException e) {
1930 Log.e(TAG, "Error calling onServiceFound(", e);
1931 }
1932 }
1933
1934 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1935 try {
1936 mCb.onServiceLost(listenerKey, info);
1937 } catch (RemoteException e) {
1938 Log.e(TAG, "Error calling onServiceLost(", e);
1939 }
1940 }
1941
1942 void onStopDiscoveryFailed(int listenerKey, int error) {
1943 try {
1944 mCb.onStopDiscoveryFailed(listenerKey, error);
1945 } catch (RemoteException e) {
1946 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1947 }
1948 }
1949
1950 void onStopDiscoverySucceeded(int listenerKey) {
1951 try {
1952 mCb.onStopDiscoverySucceeded(listenerKey);
1953 } catch (RemoteException e) {
1954 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1955 }
1956 }
1957
1958 void onRegisterServiceFailed(int listenerKey, int error) {
1959 try {
1960 mCb.onRegisterServiceFailed(listenerKey, error);
1961 } catch (RemoteException e) {
1962 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1963 }
1964 }
1965
1966 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1967 try {
1968 mCb.onRegisterServiceSucceeded(listenerKey, info);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1971 }
1972 }
1973
1974 void onUnregisterServiceFailed(int listenerKey, int error) {
1975 try {
1976 mCb.onUnregisterServiceFailed(listenerKey, error);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1979 }
1980 }
1981
1982 void onUnregisterServiceSucceeded(int listenerKey) {
1983 try {
1984 mCb.onUnregisterServiceSucceeded(listenerKey);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1987 }
1988 }
1989
1990 void onResolveServiceFailed(int listenerKey, int error) {
1991 try {
1992 mCb.onResolveServiceFailed(listenerKey, error);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1995 }
1996 }
1997
1998 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1999 try {
2000 mCb.onResolveServiceSucceeded(listenerKey, info);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2003 }
2004 }
Paul Hub58deb72022-12-26 09:24:42 +00002005
2006 void onStopResolutionFailed(int listenerKey, int error) {
2007 try {
2008 mCb.onStopResolutionFailed(listenerKey, error);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2011 }
2012 }
2013
2014 void onStopResolutionSucceeded(int listenerKey) {
2015 try {
2016 mCb.onStopResolutionSucceeded(listenerKey);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2019 }
2020 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002021
2022 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2023 try {
2024 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2027 }
2028 }
2029
2030 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2031 try {
2032 mCb.onServiceUpdated(listenerKey, info);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onServiceUpdated", e);
2035 }
2036 }
2037
2038 void onServiceUpdatedLost(int listenerKey) {
2039 try {
2040 mCb.onServiceUpdatedLost(listenerKey);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2043 }
2044 }
2045
2046 void onServiceInfoCallbackUnregistered(int listenerKey) {
2047 try {
2048 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2051 }
2052 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002053 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002054}