blob: 6885d03c2d6a731a8001c6fac007b8bbb9aa252a [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;
paulhu2b9ed952022-02-10 21:58:32 +080023
Paul Hu23fa2022023-01-13 22:57:24 +080024import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080025import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080026import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070027import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090028import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090029import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080030import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.LinkProperties;
32import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080033import android.net.mdns.aidl.DiscoveryInfo;
34import android.net.mdns.aidl.GetAddressInfo;
35import android.net.mdns.aidl.IMDnsEventListener;
36import android.net.mdns.aidl.RegistrationInfo;
37import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070038import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090039import android.net.nsd.INsdManagerCallback;
40import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080041import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080043import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090044import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080045import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080047import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070048import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090049import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070050import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080051import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.util.Log;
53import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070054import android.util.SparseArray;
Hugo Benichid2552ae2017-04-11 14:42:47 +090055import android.util.SparseIntArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070056
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.util.State;
59import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080060import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080061import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080062import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090063import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080064import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
65import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080066import com.android.server.connectivity.mdns.MdnsSearchOptions;
67import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
68import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.MdnsSocketClientBase;
70import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080071
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070074import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090075import java.net.NetworkInterface;
76import java.net.SocketException;
77import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090078import java.nio.ByteBuffer;
79import java.nio.CharBuffer;
80import java.nio.charset.Charset;
81import java.nio.charset.CharsetEncoder;
82import java.nio.charset.StandardCharsets;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070083import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080084import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080085import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080086import java.util.regex.Matcher;
87import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070088
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089/**
90 * Network Service Discovery Service handles remote service discovery operation requests by
91 * implementing the INsdManager interface.
92 *
93 * @hide
94 */
95public class NsdService extends INsdManager.Stub {
96 private static final String TAG = "NsdService";
97 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090098 /**
99 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
100 * implementation.
101 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800103 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900104 // Max label length as per RFC 1034/1035
105 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700106
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900107 /**
108 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
109 * implementation.
110 */
111 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
112
113 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000114 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900115 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Hugo Benichi32be63d2017-04-05 14:06:11 +0900117 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900118 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800119 private final MDnsManager mMDnsManager;
120 private final MDnsEventCallback mMDnsEventCallback;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800121 @Nullable
122 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
123 @Nullable
124 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
125 @Nullable
126 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900127 @Nullable
128 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800129 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800130 // state machine thread. If change this outside state machine, it will need to introduce
131 // synchronization.
132 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800133 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700134
135 /**
136 * Clients receiving asynchronous messages
137 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900138 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700139
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700140 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900141 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700142
Luke Huang05298582021-06-13 16:52:05 +0000143 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700144
Hugo Benichi32be63d2017-04-05 14:06:11 +0900145 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700146 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800147 // The count of the connected legacy clients.
148 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700149
Paul Hu23fa2022023-01-13 22:57:24 +0800150 private static class MdnsListener implements MdnsServiceBrowserListener {
151 protected final int mClientId;
152 protected final int mTransactionId;
153 @NonNull
154 protected final NsdServiceInfo mReqServiceInfo;
155 @NonNull
156 protected final String mListenedServiceType;
157
158 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
159 @NonNull String listenedServiceType) {
160 mClientId = clientId;
161 mTransactionId = transactionId;
162 mReqServiceInfo = reqServiceInfo;
163 mListenedServiceType = listenedServiceType;
164 }
165
166 @NonNull
167 public String getListenedServiceType() {
168 return mListenedServiceType;
169 }
170
171 @Override
172 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
173
174 @Override
175 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
176
177 @Override
178 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
179
180 @Override
181 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
182
183 @Override
184 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
185
186 @Override
187 public void onSearchStoppedWithError(int error) { }
188
189 @Override
190 public void onSearchFailedToStart() { }
191
192 @Override
193 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
194
195 @Override
196 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
197 }
198
199 private class DiscoveryListener extends MdnsListener {
200
201 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
202 @NonNull String listenServiceType) {
203 super(clientId, transactionId, reqServiceInfo, listenServiceType);
204 }
205
206 @Override
207 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800208 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
209 NsdManager.SERVICE_FOUND,
210 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800211 }
212
213 @Override
214 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800215 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
216 NsdManager.SERVICE_LOST,
217 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800218 }
219 }
220
Paul Hu75069ed2023-01-14 00:31:09 +0800221 private class ResolutionListener extends MdnsListener {
222
223 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
224 @NonNull String listenServiceType) {
225 super(clientId, transactionId, reqServiceInfo, listenServiceType);
226 }
227
228 @Override
229 public void onServiceFound(MdnsServiceInfo serviceInfo) {
230 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
231 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
232 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
233 }
234 }
235
Paul Hu019621e2023-01-13 23:26:49 +0800236 /**
237 * Data class of mdns service callback information.
238 */
239 private static class MdnsEvent {
240 final int mClientId;
241 @NonNull
242 final String mRequestedServiceType;
243 @NonNull
244 final MdnsServiceInfo mMdnsServiceInfo;
245
246 MdnsEvent(int clientId, @NonNull String requestedServiceType,
247 @NonNull MdnsServiceInfo mdnsServiceInfo) {
248 mClientId = clientId;
249 mRequestedServiceType = requestedServiceType;
250 mMdnsServiceInfo = mdnsServiceInfo;
251 }
252 }
253
Irfan Sheriff75006652012-04-17 23:15:29 -0700254 private class NsdStateMachine extends StateMachine {
255
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700256 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700257 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700258
259 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700260 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900261 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700262 }
263
Luke Huang92860f92021-06-23 06:29:30 +0000264 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800265 if (mIsDaemonStarted) {
266 if (DBG) Log.d(TAG, "Daemon is already started.");
267 return;
268 }
269 mMDnsManager.registerEventListener(mMDnsEventCallback);
270 mMDnsManager.startDaemon();
271 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000272 maybeScheduleStop();
273 }
274
paulhu2b9ed952022-02-10 21:58:32 +0800275 private void maybeStopDaemon() {
276 if (!mIsDaemonStarted) {
277 if (DBG) Log.d(TAG, "Daemon has not been started.");
278 return;
279 }
280 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
281 mMDnsManager.stopDaemon();
282 mIsDaemonStarted = false;
283 }
284
Luke Huang92860f92021-06-23 06:29:30 +0000285 private boolean isAnyRequestActive() {
286 return mIdToClientInfoMap.size() != 0;
287 }
288
289 private void scheduleStop() {
290 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
291 }
292 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800293 // The native daemon should stay alive and can't be cleanup
294 // if any legacy client connected.
295 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000296 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000297 }
298 }
299
Luke Huang92860f92021-06-23 06:29:30 +0000300 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000301 this.removeMessages(NsdManager.DAEMON_CLEANUP);
302 }
303
Paul Hu23fa2022023-01-13 22:57:24 +0800304 private void maybeStartMonitoringSockets() {
305 if (mIsMonitoringSocketsStarted) {
306 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
307 return;
308 }
309
310 mMdnsSocketProvider.startMonitoringSockets();
311 mIsMonitoringSocketsStarted = true;
312 }
313
314 private void maybeStopMonitoringSockets() {
315 if (!mIsMonitoringSocketsStarted) {
316 if (DBG) Log.d(TAG, "Socket monitoring has not been started.");
317 return;
318 }
319 mMdnsSocketProvider.stopMonitoringSockets();
320 mIsMonitoringSocketsStarted = false;
321 }
322
323 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
324 if (!isAnyRequestActive()) {
325 maybeStopMonitoringSockets();
326 }
327 }
328
Hugo Benichi803a2f02017-04-24 11:35:06 +0900329 NsdStateMachine(String name, Handler handler) {
330 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700331 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700332 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800333 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900334 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700335 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700336 }
337
338 class DefaultState extends State {
339 @Override
340 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900341 final ClientInfo cInfo;
342 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700343 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900344 case NsdManager.REGISTER_CLIENT:
345 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
346 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
347 final INsdManagerCallback cb = arg.second;
348 try {
349 cb.asBinder().linkToDeath(arg.first, 0);
350 cInfo = new ClientInfo(cb);
351 mClients.put(arg.first, cInfo);
352 } catch (RemoteException e) {
353 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700354 }
355 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900356 case NsdManager.UNREGISTER_CLIENT:
357 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
358 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800359 if (cInfo != null) {
Paul Hu23fa2022023-01-13 22:57:24 +0800360 if (mMdnsDiscoveryManager != null) {
361 cInfo.unregisterAllListeners();
362 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800363 cInfo.expungeAllRequests();
Luke Huangf7277ed2021-07-12 21:15:10 +0800364 if (cInfo.isLegacy()) {
365 mLegacyClientCount -= 1;
366 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800367 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900368 if (mMdnsDiscoveryManager != null || mAdvertiser != null) {
Paul Hu23fa2022023-01-13 22:57:24 +0800369 maybeStopMonitoringSocketsIfNoActiveRequest();
370 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800371 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700372 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700373 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900374 cInfo = getClientInfoForReply(msg);
375 if (cInfo != null) {
376 cInfo.onDiscoverServicesFailed(
377 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
378 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700379 break;
380 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900381 cInfo = getClientInfoForReply(msg);
382 if (cInfo != null) {
383 cInfo.onStopDiscoveryFailed(
384 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
385 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700386 break;
387 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900388 cInfo = getClientInfoForReply(msg);
389 if (cInfo != null) {
390 cInfo.onRegisterServiceFailed(
391 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
392 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700393 break;
394 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900395 cInfo = getClientInfoForReply(msg);
396 if (cInfo != null) {
397 cInfo.onUnregisterServiceFailed(
398 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
399 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700400 break;
401 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900402 cInfo = getClientInfoForReply(msg);
403 if (cInfo != null) {
404 cInfo.onResolveServiceFailed(
405 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
406 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700407 break;
Paul Hub58deb72022-12-26 09:24:42 +0000408 case NsdManager.STOP_RESOLUTION:
409 cInfo = getClientInfoForReply(msg);
410 if (cInfo != null) {
411 cInfo.onStopResolutionFailed(
412 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
413 }
414 break;
Luke Huang05298582021-06-13 16:52:05 +0000415 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800416 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000417 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800418 // This event should be only sent by the legacy (target SDK < S) clients.
419 // Mark the sending client as legacy.
420 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900421 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800422 if (cInfo != null) {
423 cancelStop();
424 cInfo.setLegacy();
425 mLegacyClientCount += 1;
426 maybeStartDaemon();
427 }
428 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700429 default:
paulhub2225702021-11-17 09:35:33 +0800430 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700431 return NOT_HANDLED;
432 }
433 return HANDLED;
434 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900435
436 private ClientInfo getClientInfoForReply(Message msg) {
437 final ListenerArgs args = (ListenerArgs) msg.obj;
438 return mClients.get(args.connector);
439 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700440 }
441
Irfan Sheriff75006652012-04-17 23:15:29 -0700442 class EnabledState extends State {
443 @Override
444 public void enter() {
445 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 }
447
448 @Override
449 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000450 // TODO: it is incorrect to stop the daemon without expunging all requests
451 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000452 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 }
454
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700455 private boolean requestLimitReached(ClientInfo clientInfo) {
456 if (clientInfo.mClientIds.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800457 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700458 return true;
459 }
460 return false;
461 }
462
Dave Plattfeff2af2014-03-07 14:48:22 -0800463 private void storeRequestMap(int clientId, int globalId, ClientInfo clientInfo, int what) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700464 clientInfo.mClientIds.put(clientId, globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -0800465 clientInfo.mClientRequests.put(clientId, what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700466 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000467 // Remove the cleanup event because here comes a new request.
468 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700469 }
470
471 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900472 clientInfo.mClientIds.delete(clientId);
473 clientInfo.mClientRequests.delete(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700474 mIdToClientInfoMap.remove(globalId);
Luke Huang05298582021-06-13 16:52:05 +0000475 maybeScheduleStop();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900476 maybeStopMonitoringSocketsIfNoActiveRequest();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700477 }
478
Paul Hu23fa2022023-01-13 22:57:24 +0800479 private void storeListenerMap(int clientId, int transactionId, MdnsListener listener,
480 ClientInfo clientInfo) {
481 clientInfo.mClientIds.put(clientId, transactionId);
482 clientInfo.mListeners.put(clientId, listener);
483 mIdToClientInfoMap.put(transactionId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800484 }
485
486 private void removeListenerMap(int clientId, int transactionId, ClientInfo clientInfo) {
487 clientInfo.mClientIds.delete(clientId);
488 clientInfo.mListeners.delete(clientId);
489 mIdToClientInfoMap.remove(transactionId);
490 maybeStopMonitoringSocketsIfNoActiveRequest();
491 }
492
493 /**
494 * Check the given service type is valid and construct it to a service type
495 * which can use for discovery / resolution service.
496 *
497 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
498 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
499 * underscore; they are alphanumerical characters or dashes or underscore, except the
500 * last one that is just alphanumerical. The last label must be _tcp or _udp.
501 *
502 * @param serviceType the request service type for discovery / resolution service
503 * @return constructed service type or null if the given service type is invalid.
504 */
505 @Nullable
506 private String constructServiceType(String serviceType) {
507 if (TextUtils.isEmpty(serviceType)) return null;
508
509 final Pattern serviceTypePattern = Pattern.compile(
510 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
511 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
512 final Matcher matcher = serviceTypePattern.matcher(serviceType);
513 if (!matcher.matches()) return null;
514 return matcher.group(1) == null
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900515 ? serviceType
516 : matcher.group(1) + "_sub." + matcher.group(2);
517 }
518
519 /**
520 * Truncate a service name to up to 63 UTF-8 bytes.
521 *
522 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
523 * names used in registerService follows historical behavior (see mdnsresponder
524 * handle_regservice_request).
525 */
526 @NonNull
527 private String truncateServiceName(@NonNull String originalName) {
528 // UTF-8 is at most 4 bytes per character; return early in the common case where
529 // the name can't possibly be over the limit given its string length.
530 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
531
532 final Charset utf8 = StandardCharsets.UTF_8;
533 final CharsetEncoder encoder = utf8.newEncoder();
534 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
535 // encode will write as many characters as possible to the out buffer, and just
536 // return an overflow code if there were too many characters (no need to check the
537 // return code here, this method truncates the name on purpose).
538 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
539 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800540 }
541
Irfan Sheriff75006652012-04-17 23:15:29 -0700542 @Override
543 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900544 final ClientInfo clientInfo;
545 final int id;
546 final int clientId = msg.arg2;
547 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700548 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800549 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800550 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900551 args = (ListenerArgs) msg.obj;
552 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000553 // If the binder death notification for a INsdManagerCallback was received
554 // before any calls are received by NsdService, the clientInfo would be
555 // cleared and cause NPE. Add a null check here to prevent this corner case.
556 if (clientInfo == null) {
557 Log.e(TAG, "Unknown connector in discovery");
558 break;
559 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700560
561 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900562 clientInfo.onDiscoverServicesFailed(
563 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700564 break;
565 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700566
Paul Hu23fa2022023-01-13 22:57:24 +0800567 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700568 id = getUniqueId();
Paul Hu23fa2022023-01-13 22:57:24 +0800569 if (mMdnsDiscoveryManager != null) {
570 final String serviceType = constructServiceType(info.getServiceType());
571 if (serviceType == null) {
572 clientInfo.onDiscoverServicesFailed(clientId,
573 NsdManager.FAILURE_INTERNAL_ERROR);
574 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700575 }
Paul Hu23fa2022023-01-13 22:57:24 +0800576
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900577 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800578 maybeStartMonitoringSockets();
579 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900580 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800581 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
582 .setNetwork(info.getNetwork())
583 .setIsPassiveMode(true)
584 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900585 mMdnsDiscoveryManager.registerListener(
586 listenServiceType, listener, options);
Paul Hu23fa2022023-01-13 22:57:24 +0800587 storeListenerMap(clientId, id, listener, clientInfo);
588 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700589 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800590 maybeStartDaemon();
591 if (discoverServices(id, info)) {
592 if (DBG) {
593 Log.d(TAG, "Discover " + msg.arg2 + " " + id
594 + info.getServiceType());
595 }
596 storeRequestMap(clientId, id, clientInfo, msg.what);
597 clientInfo.onDiscoverServicesStarted(clientId, info);
598 } else {
599 stopServiceDiscovery(id);
600 clientInfo.onDiscoverServicesFailed(clientId,
601 NsdManager.FAILURE_INTERNAL_ERROR);
602 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700603 }
604 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800605 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700606 case NsdManager.STOP_DISCOVERY:
paulhub2225702021-11-17 09:35:33 +0800607 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900608 args = (ListenerArgs) msg.obj;
609 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000610 // If the binder death notification for a INsdManagerCallback was received
611 // before any calls are received by NsdService, the clientInfo would be
612 // cleared and cause NPE. Add a null check here to prevent this corner case.
613 if (clientInfo == null) {
614 Log.e(TAG, "Unknown connector in stop discovery");
615 break;
616 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617
618 try {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900619 id = clientInfo.mClientIds.get(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700620 } catch (NullPointerException e) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900621 clientInfo.onStopDiscoveryFailed(
622 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700623 break;
624 }
Paul Hu23fa2022023-01-13 22:57:24 +0800625 if (mMdnsDiscoveryManager != null) {
626 final MdnsListener listener = clientInfo.mListeners.get(clientId);
627 if (listener == null) {
628 clientInfo.onStopDiscoveryFailed(
629 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
630 break;
631 }
632 mMdnsDiscoveryManager.unregisterListener(
633 listener.getListenedServiceType(), listener);
634 removeListenerMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900635 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700636 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800637 removeRequestMap(clientId, id, clientInfo);
638 if (stopServiceDiscovery(id)) {
639 clientInfo.onStopDiscoverySucceeded(clientId);
640 } else {
641 clientInfo.onStopDiscoveryFailed(
642 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
643 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 }
645 break;
646 case NsdManager.REGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800647 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900648 args = (ListenerArgs) msg.obj;
649 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000650 // If the binder death notification for a INsdManagerCallback was received
651 // before any calls are received by NsdService, the clientInfo would be
652 // cleared and cause NPE. Add a null check here to prevent this corner case.
653 if (clientInfo == null) {
654 Log.e(TAG, "Unknown connector in registration");
655 break;
656 }
657
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700658 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900659 clientInfo.onRegisterServiceFailed(
660 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700661 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700662 }
663
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700664 id = getUniqueId();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900665 if (mAdvertiser != null) {
666 final NsdServiceInfo serviceInfo = args.serviceInfo;
667 final String serviceType = serviceInfo.getServiceType();
668 final String registerServiceType = constructServiceType(serviceType);
669 if (registerServiceType == null) {
670 Log.e(TAG, "Invalid service type: " + serviceType);
671 clientInfo.onRegisterServiceFailed(clientId,
672 NsdManager.FAILURE_INTERNAL_ERROR);
673 break;
674 }
675 serviceInfo.setServiceType(registerServiceType);
676 serviceInfo.setServiceName(truncateServiceName(
677 serviceInfo.getServiceName()));
678
679 maybeStartMonitoringSockets();
680 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900681 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700682 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900683 maybeStartDaemon();
684 if (registerService(id, args.serviceInfo)) {
685 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
686 storeRequestMap(clientId, id, clientInfo, msg.what);
687 // Return success after mDns reports success
688 } else {
689 unregisterService(id);
690 clientInfo.onRegisterServiceFailed(
691 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
692 }
693
Irfan Sheriff75006652012-04-17 23:15:29 -0700694 }
695 break;
696 case NsdManager.UNREGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800697 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900698 args = (ListenerArgs) msg.obj;
699 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000700 // If the binder death notification for a INsdManagerCallback was received
701 // before any calls are received by NsdService, the clientInfo would be
702 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900703 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800704 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700705 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700706 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900707 id = clientInfo.mClientIds.get(clientId);
708 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900709
710 if (mAdvertiser != null) {
711 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900712 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700713 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900714 if (unregisterService(id)) {
715 clientInfo.onUnregisterServiceSucceeded(clientId);
716 } else {
717 clientInfo.onUnregisterServiceFailed(
718 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
719 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700720 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700721 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800722 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800723 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900724 args = (ListenerArgs) msg.obj;
725 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000726 // If the binder death notification for a INsdManagerCallback was received
727 // before any calls are received by NsdService, the clientInfo would be
728 // cleared and cause NPE. Add a null check here to prevent this corner case.
729 if (clientInfo == null) {
730 Log.e(TAG, "Unknown connector in resolution");
731 break;
732 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700733
Paul Hu75069ed2023-01-14 00:31:09 +0800734 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700735 id = getUniqueId();
Paul Hu75069ed2023-01-14 00:31:09 +0800736 if (mMdnsDiscoveryManager != null) {
737 final String serviceType = constructServiceType(info.getServiceType());
738 if (serviceType == null) {
739 clientInfo.onResolveServiceFailed(clientId,
740 NsdManager.FAILURE_INTERNAL_ERROR);
741 break;
742 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900743 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800744
745 maybeStartMonitoringSockets();
746 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900747 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800748 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
749 .setNetwork(info.getNetwork())
750 .setIsPassiveMode(true)
751 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900752 mMdnsDiscoveryManager.registerListener(
753 resolveServiceType, listener, options);
Paul Hu75069ed2023-01-14 00:31:09 +0800754 storeListenerMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700755 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800756 if (clientInfo.mResolvedService != null) {
757 clientInfo.onResolveServiceFailed(
758 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
759 break;
760 }
761
762 maybeStartDaemon();
763 if (resolveService(id, args.serviceInfo)) {
764 clientInfo.mResolvedService = new NsdServiceInfo();
765 storeRequestMap(clientId, id, clientInfo, msg.what);
766 } else {
767 clientInfo.onResolveServiceFailed(
768 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
769 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700770 }
771 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800772 }
Paul Hub58deb72022-12-26 09:24:42 +0000773 case NsdManager.STOP_RESOLUTION:
774 if (DBG) Log.d(TAG, "Stop service resolution");
775 args = (ListenerArgs) msg.obj;
776 clientInfo = mClients.get(args.connector);
777 // If the binder death notification for a INsdManagerCallback was received
778 // before any calls are received by NsdService, the clientInfo would be
779 // cleared and cause NPE. Add a null check here to prevent this corner case.
780 if (clientInfo == null) {
781 Log.e(TAG, "Unknown connector in stop resolution");
782 break;
783 }
784
785 id = clientInfo.mClientIds.get(clientId);
786 removeRequestMap(clientId, id, clientInfo);
787 if (stopResolveService(id)) {
788 clientInfo.onStopResolutionSucceeded(clientId);
789 } else {
790 clientInfo.onStopResolutionFailed(
791 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
792 }
793 clientInfo.mResolvedService = null;
794 // TODO: Implement the stop resolution with MdnsDiscoveryManager.
795 break;
paulhu2b9ed952022-02-10 21:58:32 +0800796 case MDNS_SERVICE_EVENT:
797 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900798 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700799 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700800 break;
Paul Hu019621e2023-01-13 23:26:49 +0800801 case MDNS_DISCOVERY_MANAGER_EVENT:
802 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
803 return NOT_HANDLED;
804 }
805 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700806 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900807 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700808 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900809 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700810 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700811
paulhu2b9ed952022-02-10 21:58:32 +0800812 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700813 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700814 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
815 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800816 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900817 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700818 }
819
820 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700821 int clientId = clientInfo.getClientId(id);
822 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700823 // This can happen because of race conditions. For example,
824 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
825 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800826 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
827 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900828 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700829 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900830 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800831 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900832 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700833 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800834 case IMDnsEventListener.SERVICE_FOUND: {
835 final DiscoveryInfo info = (DiscoveryInfo) obj;
836 final String name = info.serviceName;
837 final String type = info.registrationType;
838 servInfo = new NsdServiceInfo(name, type);
839 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900840 if (foundNetId == 0L) {
841 // Ignore services that do not have a Network: they are not usable
842 // by apps, as they would need privileged permissions to use
843 // interfaces that do not have an associated Network.
844 break;
845 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900846 if (foundNetId == INetd.DUMMY_NET_ID) {
847 // Ignore services on the dummy0 interface: they are only seen when
848 // discovering locally advertised services, and are not reachable
849 // through that interface.
850 break;
851 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900852 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900853 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700854 break;
paulhu2b9ed952022-02-10 21:58:32 +0800855 }
856 case IMDnsEventListener.SERVICE_LOST: {
857 final DiscoveryInfo info = (DiscoveryInfo) obj;
858 final String name = info.serviceName;
859 final String type = info.registrationType;
860 final int lostNetId = info.netId;
861 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900862 // The network could be set to null (netId 0) if it was torn down when the
863 // service is lost
864 // TODO: avoid returning null in that case, possibly by remembering
865 // found services on the same interface index and their network at the time
866 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900867 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700868 break;
paulhu2b9ed952022-02-10 21:58:32 +0800869 }
870 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900871 clientInfo.onDiscoverServicesFailed(
872 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700873 break;
paulhu2b9ed952022-02-10 21:58:32 +0800874 case IMDnsEventListener.SERVICE_REGISTERED: {
875 final RegistrationInfo info = (RegistrationInfo) obj;
876 final String name = info.serviceName;
877 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900878 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700879 break;
paulhu2b9ed952022-02-10 21:58:32 +0800880 }
881 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900882 clientInfo.onRegisterServiceFailed(
883 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700884 break;
paulhu2b9ed952022-02-10 21:58:32 +0800885 case IMDnsEventListener.SERVICE_RESOLVED: {
886 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700887 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800888 final String fullName = info.serviceFullName;
889 while (index < fullName.length() && fullName.charAt(index) != '.') {
890 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700891 ++index;
892 }
893 ++index;
894 }
paulhu2b9ed952022-02-10 21:58:32 +0800895 if (index >= fullName.length()) {
896 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700897 break;
898 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900899
paulhube186602022-04-12 07:18:23 +0000900 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800901 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700902 String type = rest.replace(".local.", "");
903
904 clientInfo.mResolvedService.setServiceName(name);
905 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800906 clientInfo.mResolvedService.setPort(info.port);
907 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900908 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700909
910 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800911 removeRequestMap(clientId, id, clientInfo);
912
paulhu2b9ed952022-02-10 21:58:32 +0800913 final int id2 = getUniqueId();
914 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800915 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800916 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900917 clientInfo.onResolveServiceFailed(
918 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700919 clientInfo.mResolvedService = null;
920 }
921 break;
paulhu2b9ed952022-02-10 21:58:32 +0800922 }
923 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700924 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700925 stopResolveService(id);
926 removeRequestMap(clientId, id, clientInfo);
927 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900928 clientInfo.onResolveServiceFailed(
929 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700930 break;
paulhu2b9ed952022-02-10 21:58:32 +0800931 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700932 /* NNN resolveId errorCode */
933 stopGetAddrInfo(id);
934 removeRequestMap(clientId, id, clientInfo);
935 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900936 clientInfo.onResolveServiceFailed(
937 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700938 break;
paulhu2b9ed952022-02-10 21:58:32 +0800939 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900940 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800941 final GetAddressInfo info = (GetAddressInfo) obj;
942 final String address = info.address;
943 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900944 InetAddress serviceHost = null;
945 try {
paulhu2b9ed952022-02-10 21:58:32 +0800946 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900947 } catch (UnknownHostException e) {
948 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
949 }
950
951 // If the resolved service is on an interface without a network, consider it
952 // as a failure: it would not be usable by apps as they would need
953 // privileged permissions.
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900954 if (netId != NETID_UNSET && serviceHost != null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900955 clientInfo.mResolvedService.setHost(serviceHost);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900956 setServiceNetworkForCallback(clientInfo.mResolvedService,
957 netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900958 clientInfo.onResolveServiceSucceeded(
959 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900960 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900961 clientInfo.onResolveServiceFailed(
962 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 }
964 stopGetAddrInfo(id);
965 removeRequestMap(clientId, id, clientInfo);
966 clientInfo.mResolvedService = null;
967 break;
paulhu2b9ed952022-02-10 21:58:32 +0800968 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700969 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900970 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700971 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900972 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700973 }
Paul Hu019621e2023-01-13 23:26:49 +0800974
975 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
976 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
977 final String serviceType = event.mRequestedServiceType;
978 final String serviceName = serviceInfo.getServiceInstanceName();
979 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
980 final Network network = serviceInfo.getNetwork();
981 setServiceNetworkForCallback(
982 servInfo,
983 network == null ? NETID_UNSET : network.netId,
984 serviceInfo.getInterfaceIndex());
985 return servInfo;
986 }
987
988 private boolean handleMdnsDiscoveryManagerEvent(
989 int transactionId, int code, Object obj) {
990 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
991 if (clientInfo == null) {
992 Log.e(TAG, String.format(
993 "id %d for %d has no client mapping", transactionId, code));
994 return false;
995 }
996
997 final MdnsEvent event = (MdnsEvent) obj;
998 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +0800999 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001000 if (DBG) {
1001 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1002 NsdManager.nameOf(code), transactionId));
1003 }
1004 switch (code) {
1005 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001006 clientInfo.onServiceFound(clientId, info);
1007 break;
1008 case NsdManager.SERVICE_LOST:
1009 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001010 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001011 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1012 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1013 // Add '.' in front of the service type that aligns with historical behavior
1014 info.setServiceType("." + event.mRequestedServiceType);
1015 info.setPort(serviceInfo.getPort());
1016
1017 Map<String, String> attrs = serviceInfo.getAttributes();
1018 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1019 final String key = kv.getKey();
1020 try {
1021 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1022 } catch (IllegalArgumentException e) {
1023 Log.e(TAG, "Invalid attribute", e);
1024 }
1025 }
1026 try {
1027 if (serviceInfo.getIpv4Address() != null) {
1028 info.setHost(InetAddresses.parseNumericAddress(
1029 serviceInfo.getIpv4Address()));
1030 } else {
1031 info.setHost(InetAddresses.parseNumericAddress(
1032 serviceInfo.getIpv6Address()));
1033 }
1034 clientInfo.onResolveServiceSucceeded(clientId, info);
1035 } catch (IllegalArgumentException e) {
1036 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1037 clientInfo.onResolveServiceFailed(
1038 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1039 }
1040
1041 // Unregister the listener immediately like IMDnsEventListener design
1042 final MdnsListener listener = clientInfo.mListeners.get(clientId);
1043 mMdnsDiscoveryManager.unregisterListener(
1044 listener.getListenedServiceType(), listener);
1045 removeListenerMap(clientId, transactionId, clientInfo);
1046 break;
1047 }
Paul Hu019621e2023-01-13 23:26:49 +08001048 default:
1049 return false;
1050 }
1051 return true;
1052 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001053 }
1054 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001055
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001056 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1057 switch (netId) {
1058 case NETID_UNSET:
1059 info.setNetwork(null);
1060 break;
1061 case INetd.LOCAL_NET_ID:
1062 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1063 // visible / usable for apps, so do not return it. Store the interface
1064 // index instead, so at least if the client tries to resolve the service
1065 // with that NsdServiceInfo, it will be done on the same interface.
1066 // If they recreate the NsdServiceInfo themselves, resolution would be
1067 // done on all interfaces as before T, which should also work.
1068 info.setNetwork(null);
1069 info.setInterfaceIndex(ifaceIdx);
1070 break;
1071 default:
1072 info.setNetwork(new Network(netId));
1073 }
1074 }
1075
paulhube186602022-04-12 07:18:23 +00001076 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1077 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1078 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1079 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1080 private String unescape(String s) {
1081 StringBuilder sb = new StringBuilder(s.length());
1082 for (int i = 0; i < s.length(); ++i) {
1083 char c = s.charAt(i);
1084 if (c == '\\') {
1085 if (++i >= s.length()) {
1086 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1087 break;
1088 }
1089 c = s.charAt(i);
1090 if (c != '.' && c != '\\') {
1091 if (i + 2 >= s.length()) {
1092 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1093 break;
1094 }
1095 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1096 + (s.charAt(i + 2) - '0'));
1097 i += 2;
1098 }
1099 }
1100 sb.append(c);
1101 }
1102 return sb.toString();
1103 }
1104
Hugo Benichi803a2f02017-04-24 11:35:06 +09001105 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001106 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001107 this(ctx, handler, cleanupDelayMs, new Dependencies());
1108 }
1109
1110 @VisibleForTesting
1111 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001112 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001113 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001114 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001115 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001116 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1117 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001118
1119 final boolean discoveryManagerEnabled = deps.isMdnsDiscoveryManagerEnabled(ctx);
1120 final boolean advertiserEnabled = deps.isMdnsAdvertiserEnabled(ctx);
1121 if (discoveryManagerEnabled || advertiserEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001122 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001123 } else {
1124 mMdnsSocketProvider = null;
1125 }
1126
1127 if (discoveryManagerEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001128 mMdnsSocketClient =
1129 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1130 mMdnsDiscoveryManager =
1131 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1132 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1133 } else {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001134 mMdnsSocketClient = null;
1135 mMdnsDiscoveryManager = null;
1136 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001137
1138 if (advertiserEnabled) {
1139 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1140 new AdvertiserCallback());
1141 } else {
1142 mAdvertiser = null;
1143 }
Paul Hu4bd98ef2023-01-12 13:42:07 +08001144 }
1145
1146 /**
1147 * Dependencies of NsdService, for injection in tests.
1148 */
1149 @VisibleForTesting
1150 public static class Dependencies {
1151 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001152 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001153 *
1154 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001155 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001156 */
1157 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1158 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1159 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1160 }
1161
1162 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001163 * Check whether the MdnsAdvertiser feature is enabled.
1164 *
1165 * @param context The global context information about an app environment.
1166 * @return true if the MdnsAdvertiser feature is enabled.
1167 */
1168 public boolean isMdnsAdvertiserEnabled(Context context) {
1169 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1170 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1171 }
1172
1173 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001174 * @see MdnsDiscoveryManager
1175 */
1176 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1177 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1178 return new MdnsDiscoveryManager(executorProvider, socketClient);
1179 }
1180
1181 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001182 * @see MdnsAdvertiser
1183 */
1184 public MdnsAdvertiser makeMdnsAdvertiser(
1185 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1186 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1187 return new MdnsAdvertiser(looper, socketProvider, cb);
1188 }
1189
1190 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001191 * @see MdnsSocketProvider
1192 */
1193 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1194 return new MdnsSocketProvider(context, looper);
1195 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001196 }
1197
paulhu1b35e822022-04-08 14:48:41 +08001198 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001199 HandlerThread thread = new HandlerThread(TAG);
1200 thread.start();
1201 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001202 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001203 return service;
1204 }
1205
paulhu2b9ed952022-02-10 21:58:32 +08001206 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1207 private final StateMachine mStateMachine;
1208
1209 MDnsEventCallback(StateMachine sm) {
1210 mStateMachine = sm;
1211 }
1212
1213 @Override
1214 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1215 mStateMachine.sendMessage(
1216 MDNS_SERVICE_EVENT, status.result, status.id, status);
1217 }
1218
1219 @Override
1220 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1221 mStateMachine.sendMessage(
1222 MDNS_SERVICE_EVENT, status.result, status.id, status);
1223 }
1224
1225 @Override
1226 public void onServiceResolutionStatus(final ResolutionInfo status) {
1227 mStateMachine.sendMessage(
1228 MDNS_SERVICE_EVENT, status.result, status.id, status);
1229 }
1230
1231 @Override
1232 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1233 mStateMachine.sendMessage(
1234 MDNS_SERVICE_EVENT, status.result, status.id, status);
1235 }
1236
1237 @Override
1238 public int getInterfaceVersion() throws RemoteException {
1239 return this.VERSION;
1240 }
1241
1242 @Override
1243 public String getInterfaceHash() throws RemoteException {
1244 return this.HASH;
1245 }
1246 }
1247
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001248 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1249 @Override
1250 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1251 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1252 if (clientInfo == null) return;
1253
1254 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1255 if (clientId < 0) return;
1256
1257 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1258 // historical behavior.
1259 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1260 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1261 }
1262
1263 @Override
1264 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1265 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1266 if (clientInfo == null) return;
1267
1268 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1269 if (clientId < 0) return;
1270
1271 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1272 }
1273
1274 private ClientInfo getClientInfoOrLog(int serviceId) {
1275 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1276 if (clientInfo == null) {
1277 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1278 }
1279 return clientInfo;
1280 }
1281
1282 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1283 final int clientId = info.getClientId(serviceId);
1284 if (clientId < 0) {
1285 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1286 }
1287 return clientId;
1288 }
1289 }
1290
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001291 @Override
1292 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001294 final INsdServiceConnector connector = new NsdServiceConnector();
1295 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1296 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1297 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001298 }
1299
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001300 private static class ListenerArgs {
1301 public final NsdServiceConnector connector;
1302 public final NsdServiceInfo serviceInfo;
1303 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1304 this.connector = connector;
1305 this.serviceInfo = serviceInfo;
1306 }
1307 }
1308
1309 private class NsdServiceConnector extends INsdServiceConnector.Stub
1310 implements IBinder.DeathRecipient {
1311 @Override
1312 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1313 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1314 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1315 new ListenerArgs(this, serviceInfo)));
1316 }
1317
1318 @Override
1319 public void unregisterService(int listenerKey) {
1320 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1321 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1322 new ListenerArgs(this, null)));
1323 }
1324
1325 @Override
1326 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1327 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1328 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1329 new ListenerArgs(this, serviceInfo)));
1330 }
1331
1332 @Override
1333 public void stopDiscovery(int listenerKey) {
1334 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1335 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1336 }
1337
1338 @Override
1339 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1340 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1341 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1342 new ListenerArgs(this, serviceInfo)));
1343 }
1344
1345 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001346 public void stopResolution(int listenerKey) {
1347 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1348 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1349 }
1350
1351 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001352 public void startDaemon() {
1353 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1354 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1355 }
1356
1357 @Override
1358 public void binderDied() {
1359 mNsdStateMachine.sendMessage(
1360 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1361 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001362 }
1363
Hugo Benichi912db992017-04-24 16:41:03 +09001364 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001365 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001366 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001367 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1368 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001369 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001370 }
1371
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001372 private int getUniqueId() {
1373 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1374 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001375 }
1376
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001377 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001378 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001379 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001380 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001381 String name = service.getServiceName();
1382 String type = service.getServiceType();
1383 int port = service.getPort();
1384 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001385 final int registerInterface = getNetworkInterfaceIndex(service);
1386 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001387 Log.e(TAG, "Interface to register service on not found");
1388 return false;
1389 }
1390 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001391 }
1392
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001393 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001394 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001395 }
1396
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001397 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001398 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001399 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1400 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001401 Log.e(TAG, "Interface to discover service on not found");
1402 return false;
1403 }
paulhu2b9ed952022-02-10 21:58:32 +08001404 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001405 }
1406
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001407 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001408 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001409 }
1410
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001411 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001412 final String name = service.getServiceName();
1413 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001414 final int resolveInterface = getNetworkInterfaceIndex(service);
1415 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001416 Log.e(TAG, "Interface to resolve service on not found");
1417 return false;
1418 }
paulhu2b9ed952022-02-10 21:58:32 +08001419 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001420 }
1421
1422 /**
1423 * Guess the interface to use to resolve or discover a service on a specific network.
1424 *
1425 * This is an imperfect guess, as for example the network may be gone or not yet fully
1426 * registered. This is fine as failing is correct if the network is gone, and a client
1427 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1428 * this is to support the legacy mdnsresponder implementation, which historically resolved
1429 * services on an unspecified network.
1430 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001431 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1432 final Network network = serviceInfo.getNetwork();
1433 if (network == null) {
1434 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1435 // provided by NsdService from discovery results, and the service was found on an
1436 // interface that has no app-usable Network).
1437 if (serviceInfo.getInterfaceIndex() != 0) {
1438 return serviceInfo.getInterfaceIndex();
1439 }
1440 return IFACE_IDX_ANY;
1441 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001442
1443 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1444 if (cm == null) {
1445 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1446 return IFACE_IDX_ANY;
1447 }
1448 final LinkProperties lp = cm.getLinkProperties(network);
1449 if (lp == null) return IFACE_IDX_ANY;
1450
1451 // Only resolve on non-stacked interfaces
1452 final NetworkInterface iface;
1453 try {
1454 iface = NetworkInterface.getByName(lp.getInterfaceName());
1455 } catch (SocketException e) {
1456 Log.e(TAG, "Error querying interface", e);
1457 return IFACE_IDX_ANY;
1458 }
1459
1460 if (iface == null) {
1461 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1462 return IFACE_IDX_ANY;
1463 }
1464
1465 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001466 }
1467
1468 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001469 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001470 }
1471
paulhu2b9ed952022-02-10 21:58:32 +08001472 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1473 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001474 }
1475
1476 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001477 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001478 }
1479
1480 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001481 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001482 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001483
Irfan Sheriff75006652012-04-17 23:15:29 -07001484 for (ClientInfo client : mClients.values()) {
1485 pw.println("Client Info");
1486 pw.println(client);
1487 }
1488
1489 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001490 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001491
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001492 /* Information tracked per client */
1493 private class ClientInfo {
1494
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001495 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001496 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001497 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001498 private NsdServiceInfo mResolvedService;
1499
1500 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001501 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001502
Dave Plattfeff2af2014-03-07 14:48:22 -08001503 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001504 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -08001505
Paul Hu23fa2022023-01-13 22:57:24 +08001506 /* A map from client id to the MdnsListener */
1507 private final SparseArray<MdnsListener> mListeners = new SparseArray<>();
1508
Luke Huangf7277ed2021-07-12 21:15:10 +08001509 // The target SDK of this client < Build.VERSION_CODES.S
1510 private boolean mIsLegacy = false;
1511
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001512 private ClientInfo(INsdManagerCallback cb) {
1513 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001514 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001515 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001516
1517 @Override
1518 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001519 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001520 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +08001521 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001522 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001523 int clientID = mClientIds.keyAt(i);
1524 sb.append("clientId ").append(clientID).
1525 append(" mDnsId ").append(mClientIds.valueAt(i)).
1526 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001527 }
1528 return sb.toString();
1529 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001530
Luke Huangf7277ed2021-07-12 21:15:10 +08001531 private boolean isLegacy() {
1532 return mIsLegacy;
1533 }
1534
1535 private void setLegacy() {
1536 mIsLegacy = true;
1537 }
1538
Dave Plattfeff2af2014-03-07 14:48:22 -08001539 // Remove any pending requests from the global map when we get rid of a client,
1540 // and send cancellations to the daemon.
1541 private void expungeAllRequests() {
1542 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +09001543 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -08001544 for (i = 0; i < mClientIds.size(); i++) {
1545 clientId = mClientIds.keyAt(i);
1546 globalId = mClientIds.valueAt(i);
1547 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001548 if (DBG) {
1549 Log.d(TAG, "Terminating client-ID " + clientId
1550 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1551 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001552 switch (mClientRequests.get(clientId)) {
1553 case NsdManager.DISCOVER_SERVICES:
1554 stopServiceDiscovery(globalId);
1555 break;
1556 case NsdManager.RESOLVE_SERVICE:
1557 stopResolveService(globalId);
1558 break;
1559 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001560 if (mAdvertiser != null) {
1561 mAdvertiser.removeService(globalId);
1562 } else {
1563 unregisterService(globalId);
1564 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001565 break;
1566 default:
1567 break;
1568 }
1569 }
1570 mClientIds.clear();
1571 mClientRequests.clear();
1572 }
1573
Paul Hu23fa2022023-01-13 22:57:24 +08001574 void unregisterAllListeners() {
1575 for (int i = 0; i < mListeners.size(); i++) {
1576 final MdnsListener listener = mListeners.valueAt(i);
1577 mMdnsDiscoveryManager.unregisterListener(
1578 listener.getListenedServiceType(), listener);
1579 }
1580 mListeners.clear();
1581 }
1582
Christopher Lane74411222014-04-25 18:39:07 -07001583 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
1584 // return the corresponding listener id. mDnsClient id is also called a global id.
1585 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001586 int idx = mClientIds.indexOfValue(globalId);
1587 if (idx < 0) {
1588 return idx;
Christopher Lane74411222014-04-25 18:39:07 -07001589 }
Hugo Benichid2552ae2017-04-11 14:42:47 +09001590 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -07001591 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001592
1593 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1594 try {
1595 mCb.onDiscoverServicesStarted(listenerKey, info);
1596 } catch (RemoteException e) {
1597 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1598 }
1599 }
1600
1601 void onDiscoverServicesFailed(int listenerKey, int error) {
1602 try {
1603 mCb.onDiscoverServicesFailed(listenerKey, error);
1604 } catch (RemoteException e) {
1605 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1606 }
1607 }
1608
1609 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1610 try {
1611 mCb.onServiceFound(listenerKey, info);
1612 } catch (RemoteException e) {
1613 Log.e(TAG, "Error calling onServiceFound(", e);
1614 }
1615 }
1616
1617 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1618 try {
1619 mCb.onServiceLost(listenerKey, info);
1620 } catch (RemoteException e) {
1621 Log.e(TAG, "Error calling onServiceLost(", e);
1622 }
1623 }
1624
1625 void onStopDiscoveryFailed(int listenerKey, int error) {
1626 try {
1627 mCb.onStopDiscoveryFailed(listenerKey, error);
1628 } catch (RemoteException e) {
1629 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1630 }
1631 }
1632
1633 void onStopDiscoverySucceeded(int listenerKey) {
1634 try {
1635 mCb.onStopDiscoverySucceeded(listenerKey);
1636 } catch (RemoteException e) {
1637 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1638 }
1639 }
1640
1641 void onRegisterServiceFailed(int listenerKey, int error) {
1642 try {
1643 mCb.onRegisterServiceFailed(listenerKey, error);
1644 } catch (RemoteException e) {
1645 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1646 }
1647 }
1648
1649 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1650 try {
1651 mCb.onRegisterServiceSucceeded(listenerKey, info);
1652 } catch (RemoteException e) {
1653 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1654 }
1655 }
1656
1657 void onUnregisterServiceFailed(int listenerKey, int error) {
1658 try {
1659 mCb.onUnregisterServiceFailed(listenerKey, error);
1660 } catch (RemoteException e) {
1661 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1662 }
1663 }
1664
1665 void onUnregisterServiceSucceeded(int listenerKey) {
1666 try {
1667 mCb.onUnregisterServiceSucceeded(listenerKey);
1668 } catch (RemoteException e) {
1669 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1670 }
1671 }
1672
1673 void onResolveServiceFailed(int listenerKey, int error) {
1674 try {
1675 mCb.onResolveServiceFailed(listenerKey, error);
1676 } catch (RemoteException e) {
1677 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1678 }
1679 }
1680
1681 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1682 try {
1683 mCb.onResolveServiceSucceeded(listenerKey, info);
1684 } catch (RemoteException e) {
1685 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1686 }
1687 }
Paul Hub58deb72022-12-26 09:24:42 +00001688
1689 void onStopResolutionFailed(int listenerKey, int error) {
1690 try {
1691 mCb.onStopResolutionFailed(listenerKey, error);
1692 } catch (RemoteException e) {
1693 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1694 }
1695 }
1696
1697 void onStopResolutionSucceeded(int listenerKey) {
1698 try {
1699 mCb.onStopResolutionSucceeded(listenerKey);
1700 } catch (RemoteException e) {
1701 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1702 }
1703 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001704 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001705}