blob: ce105cef4a45c4dec8eaaac32fe0124ae9ac31fe [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 VAN1a8ee102022-05-30 12:42:24 +0900846 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900847 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700848 break;
paulhu2b9ed952022-02-10 21:58:32 +0800849 }
850 case IMDnsEventListener.SERVICE_LOST: {
851 final DiscoveryInfo info = (DiscoveryInfo) obj;
852 final String name = info.serviceName;
853 final String type = info.registrationType;
854 final int lostNetId = info.netId;
855 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900856 // The network could be set to null (netId 0) if it was torn down when the
857 // service is lost
858 // TODO: avoid returning null in that case, possibly by remembering
859 // found services on the same interface index and their network at the time
860 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900861 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700862 break;
paulhu2b9ed952022-02-10 21:58:32 +0800863 }
864 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900865 clientInfo.onDiscoverServicesFailed(
866 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700867 break;
paulhu2b9ed952022-02-10 21:58:32 +0800868 case IMDnsEventListener.SERVICE_REGISTERED: {
869 final RegistrationInfo info = (RegistrationInfo) obj;
870 final String name = info.serviceName;
871 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900872 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700873 break;
paulhu2b9ed952022-02-10 21:58:32 +0800874 }
875 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900876 clientInfo.onRegisterServiceFailed(
877 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700878 break;
paulhu2b9ed952022-02-10 21:58:32 +0800879 case IMDnsEventListener.SERVICE_RESOLVED: {
880 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700881 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800882 final String fullName = info.serviceFullName;
883 while (index < fullName.length() && fullName.charAt(index) != '.') {
884 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700885 ++index;
886 }
887 ++index;
888 }
paulhu2b9ed952022-02-10 21:58:32 +0800889 if (index >= fullName.length()) {
890 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700891 break;
892 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900893
paulhube186602022-04-12 07:18:23 +0000894 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800895 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700896 String type = rest.replace(".local.", "");
897
898 clientInfo.mResolvedService.setServiceName(name);
899 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800900 clientInfo.mResolvedService.setPort(info.port);
901 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900902 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700903
904 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800905 removeRequestMap(clientId, id, clientInfo);
906
paulhu2b9ed952022-02-10 21:58:32 +0800907 final int id2 = getUniqueId();
908 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800909 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800910 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900911 clientInfo.onResolveServiceFailed(
912 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700913 clientInfo.mResolvedService = null;
914 }
915 break;
paulhu2b9ed952022-02-10 21:58:32 +0800916 }
917 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700918 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700919 stopResolveService(id);
920 removeRequestMap(clientId, id, clientInfo);
921 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900922 clientInfo.onResolveServiceFailed(
923 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700924 break;
paulhu2b9ed952022-02-10 21:58:32 +0800925 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700926 /* NNN resolveId errorCode */
927 stopGetAddrInfo(id);
928 removeRequestMap(clientId, id, clientInfo);
929 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900930 clientInfo.onResolveServiceFailed(
931 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700932 break;
paulhu2b9ed952022-02-10 21:58:32 +0800933 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900934 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800935 final GetAddressInfo info = (GetAddressInfo) obj;
936 final String address = info.address;
937 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900938 InetAddress serviceHost = null;
939 try {
paulhu2b9ed952022-02-10 21:58:32 +0800940 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900941 } catch (UnknownHostException e) {
942 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
943 }
944
945 // If the resolved service is on an interface without a network, consider it
946 // as a failure: it would not be usable by apps as they would need
947 // privileged permissions.
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900948 if (netId != NETID_UNSET && serviceHost != null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900949 clientInfo.mResolvedService.setHost(serviceHost);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900950 setServiceNetworkForCallback(clientInfo.mResolvedService,
951 netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900952 clientInfo.onResolveServiceSucceeded(
953 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900954 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900955 clientInfo.onResolveServiceFailed(
956 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700957 }
958 stopGetAddrInfo(id);
959 removeRequestMap(clientId, id, clientInfo);
960 clientInfo.mResolvedService = null;
961 break;
paulhu2b9ed952022-02-10 21:58:32 +0800962 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900964 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700965 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900966 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700967 }
Paul Hu019621e2023-01-13 23:26:49 +0800968
969 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
970 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
971 final String serviceType = event.mRequestedServiceType;
972 final String serviceName = serviceInfo.getServiceInstanceName();
973 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
974 final Network network = serviceInfo.getNetwork();
975 setServiceNetworkForCallback(
976 servInfo,
977 network == null ? NETID_UNSET : network.netId,
978 serviceInfo.getInterfaceIndex());
979 return servInfo;
980 }
981
982 private boolean handleMdnsDiscoveryManagerEvent(
983 int transactionId, int code, Object obj) {
984 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
985 if (clientInfo == null) {
986 Log.e(TAG, String.format(
987 "id %d for %d has no client mapping", transactionId, code));
988 return false;
989 }
990
991 final MdnsEvent event = (MdnsEvent) obj;
992 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +0800993 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +0800994 if (DBG) {
995 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
996 NsdManager.nameOf(code), transactionId));
997 }
998 switch (code) {
999 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001000 clientInfo.onServiceFound(clientId, info);
1001 break;
1002 case NsdManager.SERVICE_LOST:
1003 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001004 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001005 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1006 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1007 // Add '.' in front of the service type that aligns with historical behavior
1008 info.setServiceType("." + event.mRequestedServiceType);
1009 info.setPort(serviceInfo.getPort());
1010
1011 Map<String, String> attrs = serviceInfo.getAttributes();
1012 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1013 final String key = kv.getKey();
1014 try {
1015 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1016 } catch (IllegalArgumentException e) {
1017 Log.e(TAG, "Invalid attribute", e);
1018 }
1019 }
1020 try {
1021 if (serviceInfo.getIpv4Address() != null) {
1022 info.setHost(InetAddresses.parseNumericAddress(
1023 serviceInfo.getIpv4Address()));
1024 } else {
1025 info.setHost(InetAddresses.parseNumericAddress(
1026 serviceInfo.getIpv6Address()));
1027 }
1028 clientInfo.onResolveServiceSucceeded(clientId, info);
1029 } catch (IllegalArgumentException e) {
1030 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1031 clientInfo.onResolveServiceFailed(
1032 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1033 }
1034
1035 // Unregister the listener immediately like IMDnsEventListener design
1036 final MdnsListener listener = clientInfo.mListeners.get(clientId);
1037 mMdnsDiscoveryManager.unregisterListener(
1038 listener.getListenedServiceType(), listener);
1039 removeListenerMap(clientId, transactionId, clientInfo);
1040 break;
1041 }
Paul Hu019621e2023-01-13 23:26:49 +08001042 default:
1043 return false;
1044 }
1045 return true;
1046 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001047 }
1048 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001049
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001050 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1051 switch (netId) {
1052 case NETID_UNSET:
1053 info.setNetwork(null);
1054 break;
1055 case INetd.LOCAL_NET_ID:
1056 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1057 // visible / usable for apps, so do not return it. Store the interface
1058 // index instead, so at least if the client tries to resolve the service
1059 // with that NsdServiceInfo, it will be done on the same interface.
1060 // If they recreate the NsdServiceInfo themselves, resolution would be
1061 // done on all interfaces as before T, which should also work.
1062 info.setNetwork(null);
1063 info.setInterfaceIndex(ifaceIdx);
1064 break;
1065 default:
1066 info.setNetwork(new Network(netId));
1067 }
1068 }
1069
paulhube186602022-04-12 07:18:23 +00001070 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1071 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1072 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1073 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1074 private String unescape(String s) {
1075 StringBuilder sb = new StringBuilder(s.length());
1076 for (int i = 0; i < s.length(); ++i) {
1077 char c = s.charAt(i);
1078 if (c == '\\') {
1079 if (++i >= s.length()) {
1080 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1081 break;
1082 }
1083 c = s.charAt(i);
1084 if (c != '.' && c != '\\') {
1085 if (i + 2 >= s.length()) {
1086 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1087 break;
1088 }
1089 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1090 + (s.charAt(i + 2) - '0'));
1091 i += 2;
1092 }
1093 }
1094 sb.append(c);
1095 }
1096 return sb.toString();
1097 }
1098
Hugo Benichi803a2f02017-04-24 11:35:06 +09001099 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001100 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001101 this(ctx, handler, cleanupDelayMs, new Dependencies());
1102 }
1103
1104 @VisibleForTesting
1105 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001106 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001107 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001108 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001109 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001110 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1111 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001112
1113 final boolean discoveryManagerEnabled = deps.isMdnsDiscoveryManagerEnabled(ctx);
1114 final boolean advertiserEnabled = deps.isMdnsAdvertiserEnabled(ctx);
1115 if (discoveryManagerEnabled || advertiserEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001116 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001117 } else {
1118 mMdnsSocketProvider = null;
1119 }
1120
1121 if (discoveryManagerEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001122 mMdnsSocketClient =
1123 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1124 mMdnsDiscoveryManager =
1125 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1126 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1127 } else {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001128 mMdnsSocketClient = null;
1129 mMdnsDiscoveryManager = null;
1130 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001131
1132 if (advertiserEnabled) {
1133 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1134 new AdvertiserCallback());
1135 } else {
1136 mAdvertiser = null;
1137 }
Paul Hu4bd98ef2023-01-12 13:42:07 +08001138 }
1139
1140 /**
1141 * Dependencies of NsdService, for injection in tests.
1142 */
1143 @VisibleForTesting
1144 public static class Dependencies {
1145 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001146 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001147 *
1148 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001149 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001150 */
1151 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1152 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1153 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1154 }
1155
1156 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001157 * Check whether the MdnsAdvertiser feature is enabled.
1158 *
1159 * @param context The global context information about an app environment.
1160 * @return true if the MdnsAdvertiser feature is enabled.
1161 */
1162 public boolean isMdnsAdvertiserEnabled(Context context) {
1163 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1164 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1165 }
1166
1167 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001168 * @see MdnsDiscoveryManager
1169 */
1170 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1171 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1172 return new MdnsDiscoveryManager(executorProvider, socketClient);
1173 }
1174
1175 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001176 * @see MdnsAdvertiser
1177 */
1178 public MdnsAdvertiser makeMdnsAdvertiser(
1179 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1180 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1181 return new MdnsAdvertiser(looper, socketProvider, cb);
1182 }
1183
1184 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001185 * @see MdnsSocketProvider
1186 */
1187 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1188 return new MdnsSocketProvider(context, looper);
1189 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001190 }
1191
paulhu1b35e822022-04-08 14:48:41 +08001192 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001193 HandlerThread thread = new HandlerThread(TAG);
1194 thread.start();
1195 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001196 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001197 return service;
1198 }
1199
paulhu2b9ed952022-02-10 21:58:32 +08001200 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1201 private final StateMachine mStateMachine;
1202
1203 MDnsEventCallback(StateMachine sm) {
1204 mStateMachine = sm;
1205 }
1206
1207 @Override
1208 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1209 mStateMachine.sendMessage(
1210 MDNS_SERVICE_EVENT, status.result, status.id, status);
1211 }
1212
1213 @Override
1214 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1215 mStateMachine.sendMessage(
1216 MDNS_SERVICE_EVENT, status.result, status.id, status);
1217 }
1218
1219 @Override
1220 public void onServiceResolutionStatus(final ResolutionInfo status) {
1221 mStateMachine.sendMessage(
1222 MDNS_SERVICE_EVENT, status.result, status.id, status);
1223 }
1224
1225 @Override
1226 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1227 mStateMachine.sendMessage(
1228 MDNS_SERVICE_EVENT, status.result, status.id, status);
1229 }
1230
1231 @Override
1232 public int getInterfaceVersion() throws RemoteException {
1233 return this.VERSION;
1234 }
1235
1236 @Override
1237 public String getInterfaceHash() throws RemoteException {
1238 return this.HASH;
1239 }
1240 }
1241
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001242 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1243 @Override
1244 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1245 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1246 if (clientInfo == null) return;
1247
1248 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1249 if (clientId < 0) return;
1250
1251 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1252 // historical behavior.
1253 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1254 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1255 }
1256
1257 @Override
1258 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1259 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1260 if (clientInfo == null) return;
1261
1262 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1263 if (clientId < 0) return;
1264
1265 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1266 }
1267
1268 private ClientInfo getClientInfoOrLog(int serviceId) {
1269 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1270 if (clientInfo == null) {
1271 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1272 }
1273 return clientInfo;
1274 }
1275
1276 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1277 final int clientId = info.getClientId(serviceId);
1278 if (clientId < 0) {
1279 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1280 }
1281 return clientId;
1282 }
1283 }
1284
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001285 @Override
1286 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001288 final INsdServiceConnector connector = new NsdServiceConnector();
1289 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1290 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1291 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001292 }
1293
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001294 private static class ListenerArgs {
1295 public final NsdServiceConnector connector;
1296 public final NsdServiceInfo serviceInfo;
1297 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1298 this.connector = connector;
1299 this.serviceInfo = serviceInfo;
1300 }
1301 }
1302
1303 private class NsdServiceConnector extends INsdServiceConnector.Stub
1304 implements IBinder.DeathRecipient {
1305 @Override
1306 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1307 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1308 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1309 new ListenerArgs(this, serviceInfo)));
1310 }
1311
1312 @Override
1313 public void unregisterService(int listenerKey) {
1314 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1315 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1316 new ListenerArgs(this, null)));
1317 }
1318
1319 @Override
1320 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1321 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1322 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1323 new ListenerArgs(this, serviceInfo)));
1324 }
1325
1326 @Override
1327 public void stopDiscovery(int listenerKey) {
1328 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1329 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1330 }
1331
1332 @Override
1333 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1334 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1335 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1336 new ListenerArgs(this, serviceInfo)));
1337 }
1338
1339 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001340 public void stopResolution(int listenerKey) {
1341 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1342 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1343 }
1344
1345 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001346 public void startDaemon() {
1347 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1348 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1349 }
1350
1351 @Override
1352 public void binderDied() {
1353 mNsdStateMachine.sendMessage(
1354 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1355 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001356 }
1357
Hugo Benichi912db992017-04-24 16:41:03 +09001358 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001359 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001360 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001361 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1362 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001363 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001364 }
1365
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001366 private int getUniqueId() {
1367 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1368 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001369 }
1370
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001371 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001372 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001373 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001374 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001375 String name = service.getServiceName();
1376 String type = service.getServiceType();
1377 int port = service.getPort();
1378 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001379 final int registerInterface = getNetworkInterfaceIndex(service);
1380 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001381 Log.e(TAG, "Interface to register service on not found");
1382 return false;
1383 }
1384 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001385 }
1386
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001387 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001388 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001389 }
1390
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001391 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001392 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001393 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1394 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001395 Log.e(TAG, "Interface to discover service on not found");
1396 return false;
1397 }
paulhu2b9ed952022-02-10 21:58:32 +08001398 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001399 }
1400
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001401 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001402 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001403 }
1404
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001405 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001406 final String name = service.getServiceName();
1407 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001408 final int resolveInterface = getNetworkInterfaceIndex(service);
1409 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001410 Log.e(TAG, "Interface to resolve service on not found");
1411 return false;
1412 }
paulhu2b9ed952022-02-10 21:58:32 +08001413 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001414 }
1415
1416 /**
1417 * Guess the interface to use to resolve or discover a service on a specific network.
1418 *
1419 * This is an imperfect guess, as for example the network may be gone or not yet fully
1420 * registered. This is fine as failing is correct if the network is gone, and a client
1421 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1422 * this is to support the legacy mdnsresponder implementation, which historically resolved
1423 * services on an unspecified network.
1424 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001425 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1426 final Network network = serviceInfo.getNetwork();
1427 if (network == null) {
1428 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1429 // provided by NsdService from discovery results, and the service was found on an
1430 // interface that has no app-usable Network).
1431 if (serviceInfo.getInterfaceIndex() != 0) {
1432 return serviceInfo.getInterfaceIndex();
1433 }
1434 return IFACE_IDX_ANY;
1435 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001436
1437 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1438 if (cm == null) {
1439 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1440 return IFACE_IDX_ANY;
1441 }
1442 final LinkProperties lp = cm.getLinkProperties(network);
1443 if (lp == null) return IFACE_IDX_ANY;
1444
1445 // Only resolve on non-stacked interfaces
1446 final NetworkInterface iface;
1447 try {
1448 iface = NetworkInterface.getByName(lp.getInterfaceName());
1449 } catch (SocketException e) {
1450 Log.e(TAG, "Error querying interface", e);
1451 return IFACE_IDX_ANY;
1452 }
1453
1454 if (iface == null) {
1455 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1456 return IFACE_IDX_ANY;
1457 }
1458
1459 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001460 }
1461
1462 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001463 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001464 }
1465
paulhu2b9ed952022-02-10 21:58:32 +08001466 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1467 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001468 }
1469
1470 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001471 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001472 }
1473
1474 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001475 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001476 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001477
Irfan Sheriff75006652012-04-17 23:15:29 -07001478 for (ClientInfo client : mClients.values()) {
1479 pw.println("Client Info");
1480 pw.println(client);
1481 }
1482
1483 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001484 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001485
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001486 /* Information tracked per client */
1487 private class ClientInfo {
1488
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001489 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001490 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001491 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001492 private NsdServiceInfo mResolvedService;
1493
1494 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001495 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001496
Dave Plattfeff2af2014-03-07 14:48:22 -08001497 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001498 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -08001499
Paul Hu23fa2022023-01-13 22:57:24 +08001500 /* A map from client id to the MdnsListener */
1501 private final SparseArray<MdnsListener> mListeners = new SparseArray<>();
1502
Luke Huangf7277ed2021-07-12 21:15:10 +08001503 // The target SDK of this client < Build.VERSION_CODES.S
1504 private boolean mIsLegacy = false;
1505
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001506 private ClientInfo(INsdManagerCallback cb) {
1507 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001508 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001509 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001510
1511 @Override
1512 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001513 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001514 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +08001515 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001516 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001517 int clientID = mClientIds.keyAt(i);
1518 sb.append("clientId ").append(clientID).
1519 append(" mDnsId ").append(mClientIds.valueAt(i)).
1520 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001521 }
1522 return sb.toString();
1523 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001524
Luke Huangf7277ed2021-07-12 21:15:10 +08001525 private boolean isLegacy() {
1526 return mIsLegacy;
1527 }
1528
1529 private void setLegacy() {
1530 mIsLegacy = true;
1531 }
1532
Dave Plattfeff2af2014-03-07 14:48:22 -08001533 // Remove any pending requests from the global map when we get rid of a client,
1534 // and send cancellations to the daemon.
1535 private void expungeAllRequests() {
1536 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +09001537 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -08001538 for (i = 0; i < mClientIds.size(); i++) {
1539 clientId = mClientIds.keyAt(i);
1540 globalId = mClientIds.valueAt(i);
1541 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001542 if (DBG) {
1543 Log.d(TAG, "Terminating client-ID " + clientId
1544 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1545 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001546 switch (mClientRequests.get(clientId)) {
1547 case NsdManager.DISCOVER_SERVICES:
1548 stopServiceDiscovery(globalId);
1549 break;
1550 case NsdManager.RESOLVE_SERVICE:
1551 stopResolveService(globalId);
1552 break;
1553 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001554 if (mAdvertiser != null) {
1555 mAdvertiser.removeService(globalId);
1556 } else {
1557 unregisterService(globalId);
1558 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001559 break;
1560 default:
1561 break;
1562 }
1563 }
1564 mClientIds.clear();
1565 mClientRequests.clear();
1566 }
1567
Paul Hu23fa2022023-01-13 22:57:24 +08001568 void unregisterAllListeners() {
1569 for (int i = 0; i < mListeners.size(); i++) {
1570 final MdnsListener listener = mListeners.valueAt(i);
1571 mMdnsDiscoveryManager.unregisterListener(
1572 listener.getListenedServiceType(), listener);
1573 }
1574 mListeners.clear();
1575 }
1576
Christopher Lane74411222014-04-25 18:39:07 -07001577 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
1578 // return the corresponding listener id. mDnsClient id is also called a global id.
1579 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001580 int idx = mClientIds.indexOfValue(globalId);
1581 if (idx < 0) {
1582 return idx;
Christopher Lane74411222014-04-25 18:39:07 -07001583 }
Hugo Benichid2552ae2017-04-11 14:42:47 +09001584 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -07001585 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001586
1587 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1588 try {
1589 mCb.onDiscoverServicesStarted(listenerKey, info);
1590 } catch (RemoteException e) {
1591 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1592 }
1593 }
1594
1595 void onDiscoverServicesFailed(int listenerKey, int error) {
1596 try {
1597 mCb.onDiscoverServicesFailed(listenerKey, error);
1598 } catch (RemoteException e) {
1599 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1600 }
1601 }
1602
1603 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1604 try {
1605 mCb.onServiceFound(listenerKey, info);
1606 } catch (RemoteException e) {
1607 Log.e(TAG, "Error calling onServiceFound(", e);
1608 }
1609 }
1610
1611 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1612 try {
1613 mCb.onServiceLost(listenerKey, info);
1614 } catch (RemoteException e) {
1615 Log.e(TAG, "Error calling onServiceLost(", e);
1616 }
1617 }
1618
1619 void onStopDiscoveryFailed(int listenerKey, int error) {
1620 try {
1621 mCb.onStopDiscoveryFailed(listenerKey, error);
1622 } catch (RemoteException e) {
1623 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1624 }
1625 }
1626
1627 void onStopDiscoverySucceeded(int listenerKey) {
1628 try {
1629 mCb.onStopDiscoverySucceeded(listenerKey);
1630 } catch (RemoteException e) {
1631 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1632 }
1633 }
1634
1635 void onRegisterServiceFailed(int listenerKey, int error) {
1636 try {
1637 mCb.onRegisterServiceFailed(listenerKey, error);
1638 } catch (RemoteException e) {
1639 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1640 }
1641 }
1642
1643 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1644 try {
1645 mCb.onRegisterServiceSucceeded(listenerKey, info);
1646 } catch (RemoteException e) {
1647 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1648 }
1649 }
1650
1651 void onUnregisterServiceFailed(int listenerKey, int error) {
1652 try {
1653 mCb.onUnregisterServiceFailed(listenerKey, error);
1654 } catch (RemoteException e) {
1655 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1656 }
1657 }
1658
1659 void onUnregisterServiceSucceeded(int listenerKey) {
1660 try {
1661 mCb.onUnregisterServiceSucceeded(listenerKey);
1662 } catch (RemoteException e) {
1663 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1664 }
1665 }
1666
1667 void onResolveServiceFailed(int listenerKey, int error) {
1668 try {
1669 mCb.onResolveServiceFailed(listenerKey, error);
1670 } catch (RemoteException e) {
1671 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1672 }
1673 }
1674
1675 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1676 try {
1677 mCb.onResolveServiceSucceeded(listenerKey, info);
1678 } catch (RemoteException e) {
1679 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1680 }
1681 }
Paul Hub58deb72022-12-26 09:24:42 +00001682
1683 void onStopResolutionFailed(int listenerKey, int error) {
1684 try {
1685 mCb.onStopResolutionFailed(listenerKey, error);
1686 } catch (RemoteException e) {
1687 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1688 }
1689 }
1690
1691 void onStopResolutionSucceeded(int listenerKey) {
1692 try {
1693 mCb.onStopResolutionSucceeded(listenerKey);
1694 } catch (RemoteException e) {
1695 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1696 }
1697 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001698 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001699}