blob: 383ed2cf9273458a644072d043d53e044c73799c [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090025import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
26
Paul Hu23fa2022023-01-13 22:57:24 +080027import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080028import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080029import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070030import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090032import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080033import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090034import android.net.LinkProperties;
35import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080036import android.net.mdns.aidl.DiscoveryInfo;
37import android.net.mdns.aidl.GetAddressInfo;
38import android.net.mdns.aidl.IMDnsEventListener;
39import android.net.mdns.aidl.RegistrationInfo;
40import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070041import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090042import android.net.nsd.INsdManagerCallback;
43import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080044import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080046import android.net.nsd.NsdServiceInfo;
Paul Hub2e67d32023-04-18 05:50:14 +000047import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090048import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080049import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090050import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080051import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070054import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080055import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090056import android.util.Log;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070057import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058
paulhua262cc12019-08-12 16:25:11 +080059import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000060import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080061import com.android.internal.util.State;
62import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080064import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000065import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080066import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090067import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
69import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080070import com.android.server.connectivity.mdns.MdnsSearchOptions;
71import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
72import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080073import com.android.server.connectivity.mdns.MdnsSocketClientBase;
74import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080075
Irfan Sheriff77ec5582012-03-22 17:01:39 -070076import java.io.FileDescriptor;
77import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090078import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070079import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090080import java.net.NetworkInterface;
81import java.net.SocketException;
82import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090083import java.nio.ByteBuffer;
84import java.nio.CharBuffer;
85import java.nio.charset.Charset;
86import java.nio.charset.CharsetEncoder;
87import java.nio.charset.StandardCharsets;
Paul Hu2b865912023-03-06 14:27:53 +080088import java.util.ArrayList;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070089import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080090import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080091import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080092import java.util.regex.Matcher;
93import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094
Irfan Sheriff77ec5582012-03-22 17:01:39 -070095/**
96 * Network Service Discovery Service handles remote service discovery operation requests by
97 * implementing the INsdManager interface.
98 *
99 * @hide
100 */
101public class NsdService extends INsdManager.Stub {
102 private static final String TAG = "NsdService";
103 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900104 /**
105 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
106 * implementation.
107 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800108 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800109 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900110 // Max label length as per RFC 1034/1035
111 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700112
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900113 /**
114 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
115 * implementation.
116 */
117 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
118
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900119 /**
120 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
121 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
122 *
123 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
124 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
125 *
126 * In which case the flags:
127 * "mdns_discovery_manager_allowlist_mytype_version",
128 * "mdns_advertiser_allowlist_mytype_version",
129 * "mdns_discovery_manager_allowlist_othertype_version",
130 * "mdns_advertiser_allowlist_othertype_version"
131 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
132 * be read with
133 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
134 *
135 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
136 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
137 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
138 */
139 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
140
141 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
142 "mdns_discovery_manager_allowlist_";
143 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
144 "mdns_advertiser_allowlist_";
145 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
146
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900147 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000148 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900149 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700150
Hugo Benichi32be63d2017-04-05 14:06:11 +0900151 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900152 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800153 private final MDnsManager mMDnsManager;
154 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900155 @NonNull
156 private final Dependencies mDeps;
157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800160 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900161 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800162 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900163 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900164 private final MdnsAdvertiser mAdvertiser;
Paul Hub2e67d32023-04-18 05:50:14 +0000165 private final SharedLog mServiceLogs = new SharedLog(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800166 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800167 // state machine thread. If change this outside state machine, it will need to introduce
168 // synchronization.
169 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800170 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700171
172 /**
173 * Clients receiving asynchronous messages
174 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900175 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700176
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700177 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900178 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700179
Luke Huang05298582021-06-13 16:52:05 +0000180 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700181
Hugo Benichi32be63d2017-04-05 14:06:11 +0900182 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700183 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800184 // The count of the connected legacy clients.
185 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000186 // The number of client that ever connected.
187 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700188
Paul Hu23fa2022023-01-13 22:57:24 +0800189 private static class MdnsListener implements MdnsServiceBrowserListener {
190 protected final int mClientId;
191 protected final int mTransactionId;
192 @NonNull
193 protected final NsdServiceInfo mReqServiceInfo;
194 @NonNull
195 protected final String mListenedServiceType;
196
197 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
198 @NonNull String listenedServiceType) {
199 mClientId = clientId;
200 mTransactionId = transactionId;
201 mReqServiceInfo = reqServiceInfo;
202 mListenedServiceType = listenedServiceType;
203 }
204
205 @NonNull
206 public String getListenedServiceType() {
207 return mListenedServiceType;
208 }
209
210 @Override
211 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
212
213 @Override
214 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
215
216 @Override
217 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
218
219 @Override
220 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
221
222 @Override
223 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
224
225 @Override
226 public void onSearchStoppedWithError(int error) { }
227
228 @Override
229 public void onSearchFailedToStart() { }
230
231 @Override
232 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
233
234 @Override
235 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
236 }
237
238 private class DiscoveryListener extends MdnsListener {
239
240 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
241 @NonNull String listenServiceType) {
242 super(clientId, transactionId, reqServiceInfo, listenServiceType);
243 }
244
245 @Override
246 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800247 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
248 NsdManager.SERVICE_FOUND,
249 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800250 }
251
252 @Override
253 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800254 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
255 NsdManager.SERVICE_LOST,
256 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800257 }
258 }
259
Paul Hu75069ed2023-01-14 00:31:09 +0800260 private class ResolutionListener extends MdnsListener {
261
262 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
263 @NonNull String listenServiceType) {
264 super(clientId, transactionId, reqServiceInfo, listenServiceType);
265 }
266
267 @Override
268 public void onServiceFound(MdnsServiceInfo serviceInfo) {
269 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
270 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
271 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
272 }
273 }
274
Paul Hu30bd70d2023-02-07 13:20:56 +0000275 private class ServiceInfoListener extends MdnsListener {
276
277 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
278 @NonNull String listenServiceType) {
279 super(clientId, transactionId, reqServiceInfo, listenServiceType);
280 }
281
282 @Override
283 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
284 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
285 NsdManager.SERVICE_UPDATED,
286 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
287 }
288
289 @Override
290 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
291 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
292 NsdManager.SERVICE_UPDATED,
293 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
294 }
295
296 @Override
297 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
298 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
299 NsdManager.SERVICE_UPDATED_LOST,
300 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
301 }
302 }
303
Paul Hu019621e2023-01-13 23:26:49 +0800304 /**
305 * Data class of mdns service callback information.
306 */
307 private static class MdnsEvent {
308 final int mClientId;
309 @NonNull
310 final String mRequestedServiceType;
311 @NonNull
312 final MdnsServiceInfo mMdnsServiceInfo;
313
314 MdnsEvent(int clientId, @NonNull String requestedServiceType,
315 @NonNull MdnsServiceInfo mdnsServiceInfo) {
316 mClientId = clientId;
317 mRequestedServiceType = requestedServiceType;
318 mMdnsServiceInfo = mdnsServiceInfo;
319 }
320 }
321
Irfan Sheriff75006652012-04-17 23:15:29 -0700322 private class NsdStateMachine extends StateMachine {
323
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700324 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700325 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700326
327 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700328 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900329 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700330 }
331
Luke Huang92860f92021-06-23 06:29:30 +0000332 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800333 if (mIsDaemonStarted) {
334 if (DBG) Log.d(TAG, "Daemon is already started.");
335 return;
336 }
337 mMDnsManager.registerEventListener(mMDnsEventCallback);
338 mMDnsManager.startDaemon();
339 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000340 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000341 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000342 }
343
paulhu2b9ed952022-02-10 21:58:32 +0800344 private void maybeStopDaemon() {
345 if (!mIsDaemonStarted) {
346 if (DBG) Log.d(TAG, "Daemon has not been started.");
347 return;
348 }
349 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
350 mMDnsManager.stopDaemon();
351 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000352 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800353 }
354
Luke Huang92860f92021-06-23 06:29:30 +0000355 private boolean isAnyRequestActive() {
356 return mIdToClientInfoMap.size() != 0;
357 }
358
359 private void scheduleStop() {
360 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
361 }
362 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800363 // The native daemon should stay alive and can't be cleanup
364 // if any legacy client connected.
365 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000366 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000367 }
368 }
369
Luke Huang92860f92021-06-23 06:29:30 +0000370 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000371 this.removeMessages(NsdManager.DAEMON_CLEANUP);
372 }
373
Paul Hu23fa2022023-01-13 22:57:24 +0800374 private void maybeStartMonitoringSockets() {
375 if (mIsMonitoringSocketsStarted) {
376 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
377 return;
378 }
379
380 mMdnsSocketProvider.startMonitoringSockets();
381 mIsMonitoringSocketsStarted = true;
382 }
383
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900384 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
385 if (!mIsMonitoringSocketsStarted) return;
386 if (isAnyRequestActive()) return;
387
Paul Hu58f20602023-02-18 11:41:07 +0800388 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800389 mIsMonitoringSocketsStarted = false;
390 }
391
Hugo Benichi803a2f02017-04-24 11:35:06 +0900392 NsdStateMachine(String name, Handler handler) {
393 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700394 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700395 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800396 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900397 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700398 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700399 }
400
401 class DefaultState extends State {
402 @Override
403 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900404 final ClientInfo cInfo;
405 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700406 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900407 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800408 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
409 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900410 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800411 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000412 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
413 cInfo = new ClientInfo(cb, arg.useJavaBackend,
414 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800415 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900416 } catch (RemoteException e) {
417 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700418 }
419 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900420 case NsdManager.UNREGISTER_CLIENT:
421 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
422 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800423 if (cInfo != null) {
424 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900425 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800426 mLegacyClientCount -= 1;
427 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800428 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900429 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800430 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700431 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700432 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900433 cInfo = getClientInfoForReply(msg);
434 if (cInfo != null) {
435 cInfo.onDiscoverServicesFailed(
436 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
437 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700438 break;
439 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900440 cInfo = getClientInfoForReply(msg);
441 if (cInfo != null) {
442 cInfo.onStopDiscoveryFailed(
443 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
444 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700445 break;
446 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900447 cInfo = getClientInfoForReply(msg);
448 if (cInfo != null) {
449 cInfo.onRegisterServiceFailed(
450 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
451 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700452 break;
453 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900454 cInfo = getClientInfoForReply(msg);
455 if (cInfo != null) {
456 cInfo.onUnregisterServiceFailed(
457 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
458 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700459 break;
460 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900461 cInfo = getClientInfoForReply(msg);
462 if (cInfo != null) {
463 cInfo.onResolveServiceFailed(
464 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
465 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700466 break;
Paul Hub58deb72022-12-26 09:24:42 +0000467 case NsdManager.STOP_RESOLUTION:
468 cInfo = getClientInfoForReply(msg);
469 if (cInfo != null) {
470 cInfo.onStopResolutionFailed(
471 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
472 }
473 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000474 case NsdManager.REGISTER_SERVICE_CALLBACK:
475 cInfo = getClientInfoForReply(msg);
476 if (cInfo != null) {
477 cInfo.onServiceInfoCallbackRegistrationFailed(
478 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
479 }
480 break;
Luke Huang05298582021-06-13 16:52:05 +0000481 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800482 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000483 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800484 // This event should be only sent by the legacy (target SDK < S) clients.
485 // Mark the sending client as legacy.
486 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900487 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800488 if (cInfo != null) {
489 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900490 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800491 mLegacyClientCount += 1;
492 maybeStartDaemon();
493 }
494 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700495 default:
paulhub2225702021-11-17 09:35:33 +0800496 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700497 return NOT_HANDLED;
498 }
499 return HANDLED;
500 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900501
502 private ClientInfo getClientInfoForReply(Message msg) {
503 final ListenerArgs args = (ListenerArgs) msg.obj;
504 return mClients.get(args.connector);
505 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700506 }
507
Irfan Sheriff75006652012-04-17 23:15:29 -0700508 class EnabledState extends State {
509 @Override
510 public void enter() {
511 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700512 }
513
514 @Override
515 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000516 // TODO: it is incorrect to stop the daemon without expunging all requests
517 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000518 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700519 }
520
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700521 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900522 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800523 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700524 return true;
525 }
526 return false;
527 }
528
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900529 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
530 int what) {
531 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700532 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000533 // Remove the cleanup event because here comes a new request.
534 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700535 }
536
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900537 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800538 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900539 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
540 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800541 }
542
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900543 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
544 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
545 if (existing == null) return;
546 clientInfo.mClientRequests.remove(clientId);
547 mIdToClientInfoMap.remove(globalId);
548
549 if (existing instanceof LegacyClientRequest) {
550 maybeScheduleStop();
551 } else {
552 maybeStopMonitoringSocketsIfNoActiveRequest();
553 }
554 }
555
556 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
557 MdnsListener listener, ClientInfo clientInfo) {
558 clientInfo.mClientRequests.put(clientId,
559 new DiscoveryManagerRequest(globalId, listener));
560 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800561 }
562
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900563 /**
564 * Truncate a service name to up to 63 UTF-8 bytes.
565 *
566 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
567 * names used in registerService follows historical behavior (see mdnsresponder
568 * handle_regservice_request).
569 */
570 @NonNull
571 private String truncateServiceName(@NonNull String originalName) {
572 // UTF-8 is at most 4 bytes per character; return early in the common case where
573 // the name can't possibly be over the limit given its string length.
574 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
575
576 final Charset utf8 = StandardCharsets.UTF_8;
577 final CharsetEncoder encoder = utf8.newEncoder();
578 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
579 // encode will write as many characters as possible to the out buffer, and just
580 // return an overflow code if there were too many characters (no need to check the
581 // return code here, this method truncates the name on purpose).
582 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
583 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800584 }
585
Paul Hue4f5f252023-02-16 21:13:47 +0800586 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
587 ClientInfo clientInfo) {
588 clientInfo.unregisterMdnsListenerFromRequest(request);
589 removeRequestMap(clientId, id, clientInfo);
590 }
591
Irfan Sheriff75006652012-04-17 23:15:29 -0700592 @Override
593 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900594 final ClientInfo clientInfo;
595 final int id;
596 final int clientId = msg.arg2;
597 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800599 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800600 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900601 args = (ListenerArgs) msg.obj;
602 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000603 // If the binder death notification for a INsdManagerCallback was received
604 // before any calls are received by NsdService, the clientInfo would be
605 // cleared and cause NPE. Add a null check here to prevent this corner case.
606 if (clientInfo == null) {
607 Log.e(TAG, "Unknown connector in discovery");
608 break;
609 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700610
611 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900612 clientInfo.onDiscoverServicesFailed(
613 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700614 break;
615 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700616
Paul Hu23fa2022023-01-13 22:57:24 +0800617 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700618 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900619 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800620 if (clientInfo.mUseJavaBackend
621 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900622 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800623 if (serviceType == null) {
624 clientInfo.onDiscoverServicesFailed(clientId,
625 NsdManager.FAILURE_INTERNAL_ERROR);
626 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700627 }
Paul Hu23fa2022023-01-13 22:57:24 +0800628
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900629 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800630 maybeStartMonitoringSockets();
631 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900632 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800633 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
634 .setNetwork(info.getNetwork())
635 .setIsPassiveMode(true)
636 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900637 mMdnsDiscoveryManager.registerListener(
638 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900639 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800640 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000641 clientInfo.log("Register a DiscoveryListener " + id
642 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700643 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800644 maybeStartDaemon();
645 if (discoverServices(id, info)) {
646 if (DBG) {
647 Log.d(TAG, "Discover " + msg.arg2 + " " + id
648 + info.getServiceType());
649 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900650 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800651 clientInfo.onDiscoverServicesStarted(clientId, info);
652 } else {
653 stopServiceDiscovery(id);
654 clientInfo.onDiscoverServicesFailed(clientId,
655 NsdManager.FAILURE_INTERNAL_ERROR);
656 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700657 }
658 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800659 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900660 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800661 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900662 args = (ListenerArgs) msg.obj;
663 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000664 // If the binder death notification for a INsdManagerCallback was received
665 // before any calls are received by NsdService, the clientInfo would be
666 // cleared and cause NPE. Add a null check here to prevent this corner case.
667 if (clientInfo == null) {
668 Log.e(TAG, "Unknown connector in stop discovery");
669 break;
670 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700671
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900672 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
673 if (request == null) {
674 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700675 break;
676 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900677 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900678 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
679 // point, so this needs to check the type of the original request to
680 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900681 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800682 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900683 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000684 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700685 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800686 removeRequestMap(clientId, id, clientInfo);
687 if (stopServiceDiscovery(id)) {
688 clientInfo.onStopDiscoverySucceeded(clientId);
689 } else {
690 clientInfo.onStopDiscoveryFailed(
691 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
692 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700693 }
694 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900695 }
696 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800697 if (DBG) Log.d(TAG, "Register 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.
703 if (clientInfo == null) {
704 Log.e(TAG, "Unknown connector in registration");
705 break;
706 }
707
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700708 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900709 clientInfo.onRegisterServiceFailed(
710 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700711 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 }
713
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700714 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900715 final NsdServiceInfo serviceInfo = args.serviceInfo;
716 final String serviceType = serviceInfo.getServiceType();
717 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800718 if (clientInfo.mUseJavaBackend
719 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900720 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900721 if (registerServiceType == null) {
722 Log.e(TAG, "Invalid service type: " + serviceType);
723 clientInfo.onRegisterServiceFailed(clientId,
724 NsdManager.FAILURE_INTERNAL_ERROR);
725 break;
726 }
727 serviceInfo.setServiceType(registerServiceType);
728 serviceInfo.setServiceName(truncateServiceName(
729 serviceInfo.getServiceName()));
730
731 maybeStartMonitoringSockets();
732 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900733 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700734 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900735 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900736 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900737 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900738 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900739 // Return success after mDns reports success
740 } else {
741 unregisterService(id);
742 clientInfo.onRegisterServiceFailed(
743 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
744 }
745
Irfan Sheriff75006652012-04-17 23:15:29 -0700746 }
747 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900748 }
749 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800750 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900751 args = (ListenerArgs) msg.obj;
752 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000753 // If the binder death notification for a INsdManagerCallback was received
754 // before any calls are received by NsdService, the clientInfo would be
755 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900756 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800757 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700758 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700759 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900760 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
761 if (request == null) {
762 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
763 break;
764 }
765 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900766 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900767
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900768 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
769 // so this needs to check the type of the original request to unregister
770 // instead of looking at the flag value.
771 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900772 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900773 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700774 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900775 if (unregisterService(id)) {
776 clientInfo.onUnregisterServiceSucceeded(clientId);
777 } else {
778 clientInfo.onUnregisterServiceFailed(
779 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
780 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700781 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700782 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900783 }
Paul Hu75069ed2023-01-14 00:31:09 +0800784 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800785 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900786 args = (ListenerArgs) msg.obj;
787 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000788 // If the binder death notification for a INsdManagerCallback was received
789 // before any calls are received by NsdService, the clientInfo would be
790 // cleared and cause NPE. Add a null check here to prevent this corner case.
791 if (clientInfo == null) {
792 Log.e(TAG, "Unknown connector in resolution");
793 break;
794 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700795
Paul Hu75069ed2023-01-14 00:31:09 +0800796 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700797 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900798 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800799 if (clientInfo.mUseJavaBackend
800 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900801 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800802 if (serviceType == null) {
803 clientInfo.onResolveServiceFailed(clientId,
804 NsdManager.FAILURE_INTERNAL_ERROR);
805 break;
806 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900807 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800808
809 maybeStartMonitoringSockets();
810 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900811 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800812 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
813 .setNetwork(info.getNetwork())
814 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900815 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800816 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900817 mMdnsDiscoveryManager.registerListener(
818 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900819 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000820 clientInfo.log("Register a ResolutionListener " + id
821 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800823 if (clientInfo.mResolvedService != null) {
824 clientInfo.onResolveServiceFailed(
825 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
826 break;
827 }
828
829 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900830 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800831 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800833 } else {
834 clientInfo.onResolveServiceFailed(
835 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
836 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700837 }
838 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800839 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900840 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000841 if (DBG) Log.d(TAG, "Stop service resolution");
842 args = (ListenerArgs) msg.obj;
843 clientInfo = mClients.get(args.connector);
844 // If the binder death notification for a INsdManagerCallback was received
845 // before any calls are received by NsdService, the clientInfo would be
846 // cleared and cause NPE. Add a null check here to prevent this corner case.
847 if (clientInfo == null) {
848 Log.e(TAG, "Unknown connector in stop resolution");
849 break;
850 }
851
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900852 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
853 if (request == null) {
854 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
855 break;
856 }
857 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800858 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
859 // point, so this needs to check the type of the original request to
860 // unregister instead of looking at the flag value.
861 if (request instanceof DiscoveryManagerRequest) {
862 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000863 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000864 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000865 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800866 removeRequestMap(clientId, id, clientInfo);
867 if (stopResolveService(id)) {
868 clientInfo.onStopResolutionSucceeded(clientId);
869 } else {
870 clientInfo.onStopResolutionFailed(
871 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
872 }
873 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000874 }
Paul Hub58deb72022-12-26 09:24:42 +0000875 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900876 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000877 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000878 if (DBG) Log.d(TAG, "Register a service callback");
879 args = (ListenerArgs) msg.obj;
880 clientInfo = mClients.get(args.connector);
881 // If the binder death notification for a INsdManagerCallback was received
882 // before any calls are received by NsdService, the clientInfo would be
883 // cleared and cause NPE. Add a null check here to prevent this corner case.
884 if (clientInfo == null) {
885 Log.e(TAG, "Unknown connector in callback registration");
886 break;
887 }
888
Paul Hu30bd70d2023-02-07 13:20:56 +0000889 final NsdServiceInfo info = args.serviceInfo;
890 id = getUniqueId();
891 final String serviceType = constructServiceType(info.getServiceType());
892 if (serviceType == null) {
893 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
894 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000895 break;
896 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000897 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000898
Paul Hu30bd70d2023-02-07 13:20:56 +0000899 maybeStartMonitoringSockets();
900 final MdnsListener listener =
901 new ServiceInfoListener(clientId, id, info, resolveServiceType);
902 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
903 .setNetwork(info.getNetwork())
904 .setIsPassiveMode(true)
905 .setResolveInstanceName(info.getServiceName())
906 .build();
907 mMdnsDiscoveryManager.registerListener(
908 resolveServiceType, listener, options);
909 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000910 clientInfo.log("Register a ServiceInfoListener " + id
911 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000912 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000913 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900914 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000915 if (DBG) Log.d(TAG, "Unregister a service callback");
916 args = (ListenerArgs) msg.obj;
917 clientInfo = mClients.get(args.connector);
918 // If the binder death notification for a INsdManagerCallback was received
919 // before any calls are received by NsdService, the clientInfo would be
920 // cleared and cause NPE. Add a null check here to prevent this corner case.
921 if (clientInfo == null) {
922 Log.e(TAG, "Unknown connector in callback unregistration");
923 break;
924 }
925
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900926 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
927 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000928 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900929 break;
930 }
931 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000932 if (request instanceof DiscoveryManagerRequest) {
933 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000934 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000935 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000936 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000937 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000938 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000939 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900940 }
paulhu2b9ed952022-02-10 21:58:32 +0800941 case MDNS_SERVICE_EVENT:
942 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900943 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700944 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700945 break;
Paul Hu019621e2023-01-13 23:26:49 +0800946 case MDNS_DISCOVERY_MANAGER_EVENT:
947 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
948 return NOT_HANDLED;
949 }
950 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700951 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900952 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700953 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900954 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700955 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700956
paulhu2b9ed952022-02-10 21:58:32 +0800957 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700958 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700959 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
960 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800961 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900962 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 }
964
965 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700966 int clientId = clientInfo.getClientId(id);
967 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700968 // This can happen because of race conditions. For example,
969 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
970 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800971 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
972 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900973 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700974 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900975 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800976 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900977 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700978 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800979 case IMDnsEventListener.SERVICE_FOUND: {
980 final DiscoveryInfo info = (DiscoveryInfo) obj;
981 final String name = info.serviceName;
982 final String type = info.registrationType;
983 servInfo = new NsdServiceInfo(name, type);
984 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900985 if (foundNetId == 0L) {
986 // Ignore services that do not have a Network: they are not usable
987 // by apps, as they would need privileged permissions to use
988 // interfaces that do not have an associated Network.
989 break;
990 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900991 if (foundNetId == INetd.DUMMY_NET_ID) {
992 // Ignore services on the dummy0 interface: they are only seen when
993 // discovering locally advertised services, and are not reachable
994 // through that interface.
995 break;
996 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900997 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900998 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700999 break;
paulhu2b9ed952022-02-10 21:58:32 +08001000 }
1001 case IMDnsEventListener.SERVICE_LOST: {
1002 final DiscoveryInfo info = (DiscoveryInfo) obj;
1003 final String name = info.serviceName;
1004 final String type = info.registrationType;
1005 final int lostNetId = info.netId;
1006 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001007 // The network could be set to null (netId 0) if it was torn down when the
1008 // service is lost
1009 // TODO: avoid returning null in that case, possibly by remembering
1010 // found services on the same interface index and their network at the time
1011 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001012 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001013 break;
paulhu2b9ed952022-02-10 21:58:32 +08001014 }
1015 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001016 clientInfo.onDiscoverServicesFailed(
1017 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001018 break;
paulhu2b9ed952022-02-10 21:58:32 +08001019 case IMDnsEventListener.SERVICE_REGISTERED: {
1020 final RegistrationInfo info = (RegistrationInfo) obj;
1021 final String name = info.serviceName;
1022 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001023 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001024 break;
paulhu2b9ed952022-02-10 21:58:32 +08001025 }
1026 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001027 clientInfo.onRegisterServiceFailed(
1028 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001029 break;
paulhu2b9ed952022-02-10 21:58:32 +08001030 case IMDnsEventListener.SERVICE_RESOLVED: {
1031 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001032 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001033 final String fullName = info.serviceFullName;
1034 while (index < fullName.length() && fullName.charAt(index) != '.') {
1035 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001036 ++index;
1037 }
1038 ++index;
1039 }
paulhu2b9ed952022-02-10 21:58:32 +08001040 if (index >= fullName.length()) {
1041 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001042 break;
1043 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001044
paulhube186602022-04-12 07:18:23 +00001045 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001046 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001047 String type = rest.replace(".local.", "");
1048
Paul Hu30bd70d2023-02-07 13:20:56 +00001049 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001050 serviceInfo.setServiceName(name);
1051 serviceInfo.setServiceType(type);
1052 serviceInfo.setPort(info.port);
1053 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001054 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001055
1056 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001057 removeRequestMap(clientId, id, clientInfo);
1058
paulhu2b9ed952022-02-10 21:58:32 +08001059 final int id2 = getUniqueId();
1060 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001061 storeLegacyRequestMap(clientId, id2, clientInfo,
1062 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001063 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001064 clientInfo.onResolveServiceFailed(
1065 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1066 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001067 }
1068 break;
paulhu2b9ed952022-02-10 21:58:32 +08001069 }
1070 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001071 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001072 stopResolveService(id);
1073 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001074 clientInfo.onResolveServiceFailed(
1075 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1076 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001077 break;
paulhu2b9ed952022-02-10 21:58:32 +08001078 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001079 /* NNN resolveId errorCode */
1080 stopGetAddrInfo(id);
1081 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001082 clientInfo.onResolveServiceFailed(
1083 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1084 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001085 break;
paulhu2b9ed952022-02-10 21:58:32 +08001086 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001087 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001088 final GetAddressInfo info = (GetAddressInfo) obj;
1089 final String address = info.address;
1090 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001091 InetAddress serviceHost = null;
1092 try {
paulhu2b9ed952022-02-10 21:58:32 +08001093 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001094 } catch (UnknownHostException e) {
1095 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1096 }
1097
1098 // If the resolved service is on an interface without a network, consider it
1099 // as a failure: it would not be usable by apps as they would need
1100 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001101 if (netId != NETID_UNSET && serviceHost != null) {
1102 clientInfo.mResolvedService.setHost(serviceHost);
1103 setServiceNetworkForCallback(clientInfo.mResolvedService,
1104 netId, info.interfaceIdx);
1105 clientInfo.onResolveServiceSucceeded(
1106 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001107 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001108 clientInfo.onResolveServiceFailed(
1109 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001110 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001111 stopGetAddrInfo(id);
1112 removeRequestMap(clientId, id, clientInfo);
1113 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001114 break;
paulhu2b9ed952022-02-10 21:58:32 +08001115 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001116 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001117 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001118 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001119 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001120 }
Paul Hu019621e2023-01-13 23:26:49 +08001121
1122 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1123 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1124 final String serviceType = event.mRequestedServiceType;
1125 final String serviceName = serviceInfo.getServiceInstanceName();
1126 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1127 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001128 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1129 // network for Tethering interface. In other words, the network == null means the
1130 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001131 setServiceNetworkForCallback(
1132 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001133 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001134 serviceInfo.getInterfaceIndex());
1135 return servInfo;
1136 }
1137
1138 private boolean handleMdnsDiscoveryManagerEvent(
1139 int transactionId, int code, Object obj) {
1140 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1141 if (clientInfo == null) {
1142 Log.e(TAG, String.format(
1143 "id %d for %d has no client mapping", transactionId, code));
1144 return false;
1145 }
1146
1147 final MdnsEvent event = (MdnsEvent) obj;
1148 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001149 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001150 if (DBG) {
1151 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1152 NsdManager.nameOf(code), transactionId));
1153 }
1154 switch (code) {
1155 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001156 clientInfo.onServiceFound(clientId, info);
1157 break;
1158 case NsdManager.SERVICE_LOST:
1159 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001160 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001161 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001162 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1163 if (request == null) {
1164 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1165 break;
1166 }
Paul Hu75069ed2023-01-14 00:31:09 +08001167 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1168 // Add '.' in front of the service type that aligns with historical behavior
1169 info.setServiceType("." + event.mRequestedServiceType);
1170 info.setPort(serviceInfo.getPort());
1171
1172 Map<String, String> attrs = serviceInfo.getAttributes();
1173 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1174 final String key = kv.getKey();
1175 try {
1176 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1177 } catch (IllegalArgumentException e) {
1178 Log.e(TAG, "Invalid attribute", e);
1179 }
1180 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001181 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001182 if (addresses.size() != 0) {
1183 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001184 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001185 } else {
1186 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001187 clientInfo.onResolveServiceFailed(
1188 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1189 }
1190
1191 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001192 if (!(request instanceof DiscoveryManagerRequest)) {
1193 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1194 break;
1195 }
Paul Hue4f5f252023-02-16 21:13:47 +08001196 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001197 break;
1198 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001199 case NsdManager.SERVICE_UPDATED: {
1200 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1201 info.setPort(serviceInfo.getPort());
1202
1203 Map<String, String> attrs = serviceInfo.getAttributes();
1204 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1205 final String key = kv.getKey();
1206 try {
1207 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1208 } catch (IllegalArgumentException e) {
1209 Log.e(TAG, "Invalid attribute", e);
1210 }
1211 }
1212
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001213 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001214 info.setHostAddresses(addresses);
1215 clientInfo.onServiceUpdated(clientId, info);
1216 break;
1217 }
1218 case NsdManager.SERVICE_UPDATED_LOST:
1219 clientInfo.onServiceUpdatedLost(clientId);
1220 break;
Paul Hu019621e2023-01-13 23:26:49 +08001221 default:
1222 return false;
1223 }
1224 return true;
1225 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001226 }
1227 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001228
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001229 @NonNull
1230 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1231 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1232 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1233 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1234 for (String ipv4Address : v4Addrs) {
1235 try {
1236 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1237 } catch (IllegalArgumentException e) {
1238 Log.wtf(TAG, "Invalid ipv4 address", e);
1239 }
1240 }
1241 for (String ipv6Address : v6Addrs) {
1242 try {
1243 final InetAddress addr = InetAddresses.parseNumericAddress(ipv6Address);
1244 if (addr.isLinkLocalAddress()) {
1245 final Inet6Address v6Addr = Inet6Address.getByAddress(
1246 null /* host */, addr.getAddress(),
1247 serviceInfo.getInterfaceIndex());
1248 addresses.add(v6Addr);
1249 } else {
1250 addresses.add(addr);
1251 }
1252 } catch (IllegalArgumentException | UnknownHostException e) {
1253 Log.wtf(TAG, "Invalid ipv6 address", e);
1254 }
1255 }
1256 return addresses;
1257 }
1258
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001259 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1260 switch (netId) {
1261 case NETID_UNSET:
1262 info.setNetwork(null);
1263 break;
1264 case INetd.LOCAL_NET_ID:
1265 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1266 // visible / usable for apps, so do not return it. Store the interface
1267 // index instead, so at least if the client tries to resolve the service
1268 // with that NsdServiceInfo, it will be done on the same interface.
1269 // If they recreate the NsdServiceInfo themselves, resolution would be
1270 // done on all interfaces as before T, which should also work.
1271 info.setNetwork(null);
1272 info.setInterfaceIndex(ifaceIdx);
1273 break;
1274 default:
1275 info.setNetwork(new Network(netId));
1276 }
1277 }
1278
paulhube186602022-04-12 07:18:23 +00001279 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1280 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1281 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1282 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1283 private String unescape(String s) {
1284 StringBuilder sb = new StringBuilder(s.length());
1285 for (int i = 0; i < s.length(); ++i) {
1286 char c = s.charAt(i);
1287 if (c == '\\') {
1288 if (++i >= s.length()) {
1289 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1290 break;
1291 }
1292 c = s.charAt(i);
1293 if (c != '.' && c != '\\') {
1294 if (i + 2 >= s.length()) {
1295 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1296 break;
1297 }
1298 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1299 + (s.charAt(i + 2) - '0'));
1300 i += 2;
1301 }
1302 }
1303 sb.append(c);
1304 }
1305 return sb.toString();
1306 }
1307
Paul Hu7445e3d2023-03-03 15:14:00 +08001308 /**
1309 * Check the given service type is valid and construct it to a service type
1310 * which can use for discovery / resolution service.
1311 *
1312 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1313 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1314 * underscore; they are alphanumerical characters or dashes or underscore, except the
1315 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1316 *
1317 * @param serviceType the request service type for discovery / resolution service
1318 * @return constructed service type or null if the given service type is invalid.
1319 */
1320 @Nullable
1321 public static String constructServiceType(String serviceType) {
1322 if (TextUtils.isEmpty(serviceType)) return null;
1323
1324 final Pattern serviceTypePattern = Pattern.compile(
1325 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1326 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1327 // Drop '.' at the end of service type that is compatible with old backend.
1328 + "\\.?$");
1329 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1330 if (!matcher.matches()) return null;
1331 return matcher.group(1) == null
1332 ? matcher.group(2)
1333 : matcher.group(1) + "_sub." + matcher.group(2);
1334 }
1335
Hugo Benichi803a2f02017-04-24 11:35:06 +09001336 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001337 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001338 this(ctx, handler, cleanupDelayMs, new Dependencies());
1339 }
1340
1341 @VisibleForTesting
1342 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001343 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001344 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001345 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001346 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001347 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1348 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001349 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001350
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001351 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Yuyang Huang700778b2023-03-08 16:17:05 +09001352 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1353 // address events are received.
1354 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001355 mMdnsSocketClient =
1356 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1357 mMdnsDiscoveryManager =
1358 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1359 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1360 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1361 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001362 }
1363
1364 /**
1365 * Dependencies of NsdService, for injection in tests.
1366 */
1367 @VisibleForTesting
1368 public static class Dependencies {
1369 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001370 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001371 *
1372 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001373 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001374 */
1375 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001376 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1377 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1378 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001379 }
1380
1381 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001382 * Check whether the MdnsAdvertiser feature is enabled.
1383 *
1384 * @param context The global context information about an app environment.
1385 * @return true if the MdnsAdvertiser feature is enabled.
1386 */
1387 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001388 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1389 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001390 }
1391
1392 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001393 * Get the type allowlist flag value.
1394 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1395 */
1396 @Nullable
1397 public String getTypeAllowlistFlags() {
1398 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1399 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1400 }
1401
1402 /**
1403 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1404 */
1405 public boolean isFeatureEnabled(Context context, String feature) {
1406 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1407 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1408 }
1409
1410 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001411 * @see MdnsDiscoveryManager
1412 */
1413 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1414 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1415 return new MdnsDiscoveryManager(executorProvider, socketClient);
1416 }
1417
1418 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001419 * @see MdnsAdvertiser
1420 */
1421 public MdnsAdvertiser makeMdnsAdvertiser(
1422 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1423 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1424 return new MdnsAdvertiser(looper, socketProvider, cb);
1425 }
1426
1427 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001428 * @see MdnsSocketProvider
1429 */
1430 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1431 return new MdnsSocketProvider(context, looper);
1432 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001433 }
1434
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001435 /**
1436 * Return whether a type is allowlisted to use the Java backend.
1437 * @param type The service type
1438 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1439 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1440 */
1441 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1442 @NonNull String flagPrefix) {
1443 if (type == null) return false;
1444 final String typesConfig = mDeps.getTypeAllowlistFlags();
1445 if (TextUtils.isEmpty(typesConfig)) return false;
1446
1447 final String mappingPrefix = type + ":";
1448 String mappedFlag = null;
1449 for (String mapping : TextUtils.split(typesConfig, ",")) {
1450 if (mapping.startsWith(mappingPrefix)) {
1451 mappedFlag = mapping.substring(mappingPrefix.length());
1452 break;
1453 }
1454 }
1455
1456 if (mappedFlag == null) return false;
1457
1458 return mDeps.isFeatureEnabled(mContext,
1459 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1460 }
1461
1462 private boolean useDiscoveryManagerForType(@Nullable String type) {
1463 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1464 }
1465
1466 private boolean useAdvertiserForType(@Nullable String type) {
1467 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1468 }
1469
paulhu1b35e822022-04-08 14:48:41 +08001470 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001471 HandlerThread thread = new HandlerThread(TAG);
1472 thread.start();
1473 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001474 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001475 return service;
1476 }
1477
paulhu2b9ed952022-02-10 21:58:32 +08001478 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1479 private final StateMachine mStateMachine;
1480
1481 MDnsEventCallback(StateMachine sm) {
1482 mStateMachine = sm;
1483 }
1484
1485 @Override
1486 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1487 mStateMachine.sendMessage(
1488 MDNS_SERVICE_EVENT, status.result, status.id, status);
1489 }
1490
1491 @Override
1492 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1493 mStateMachine.sendMessage(
1494 MDNS_SERVICE_EVENT, status.result, status.id, status);
1495 }
1496
1497 @Override
1498 public void onServiceResolutionStatus(final ResolutionInfo status) {
1499 mStateMachine.sendMessage(
1500 MDNS_SERVICE_EVENT, status.result, status.id, status);
1501 }
1502
1503 @Override
1504 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1505 mStateMachine.sendMessage(
1506 MDNS_SERVICE_EVENT, status.result, status.id, status);
1507 }
1508
1509 @Override
1510 public int getInterfaceVersion() throws RemoteException {
1511 return this.VERSION;
1512 }
1513
1514 @Override
1515 public String getInterfaceHash() throws RemoteException {
1516 return this.HASH;
1517 }
1518 }
1519
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001520 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1521 @Override
1522 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1523 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1524 if (clientInfo == null) return;
1525
1526 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1527 if (clientId < 0) return;
1528
1529 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1530 // historical behavior.
1531 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1532 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1533 }
1534
1535 @Override
1536 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1537 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1538 if (clientInfo == null) return;
1539
1540 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1541 if (clientId < 0) return;
1542
1543 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1544 }
1545
1546 private ClientInfo getClientInfoOrLog(int serviceId) {
1547 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1548 if (clientInfo == null) {
1549 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1550 }
1551 return clientInfo;
1552 }
1553
1554 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1555 final int clientId = info.getClientId(serviceId);
1556 if (clientId < 0) {
1557 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1558 }
1559 return clientId;
1560 }
1561 }
1562
Paul Hu2e0a88c2023-03-09 16:05:01 +08001563 private static class ConnectorArgs {
1564 @NonNull public final NsdServiceConnector connector;
1565 @NonNull public final INsdManagerCallback callback;
1566 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001567 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001568
1569 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001570 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001571 this.connector = connector;
1572 this.callback = callback;
1573 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001574 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001575 }
1576 }
1577
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001578 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001579 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001581 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001582 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001583 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1584 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1585 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001586 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001587 }
1588
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001589 private static class ListenerArgs {
1590 public final NsdServiceConnector connector;
1591 public final NsdServiceInfo serviceInfo;
1592 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1593 this.connector = connector;
1594 this.serviceInfo = serviceInfo;
1595 }
1596 }
1597
1598 private class NsdServiceConnector extends INsdServiceConnector.Stub
1599 implements IBinder.DeathRecipient {
1600 @Override
1601 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1602 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1603 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1604 new ListenerArgs(this, serviceInfo)));
1605 }
1606
1607 @Override
1608 public void unregisterService(int listenerKey) {
1609 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1610 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1611 new ListenerArgs(this, null)));
1612 }
1613
1614 @Override
1615 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1616 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1617 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1618 new ListenerArgs(this, serviceInfo)));
1619 }
1620
1621 @Override
1622 public void stopDiscovery(int listenerKey) {
1623 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1624 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1625 }
1626
1627 @Override
1628 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1629 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1630 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1631 new ListenerArgs(this, serviceInfo)));
1632 }
1633
1634 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001635 public void stopResolution(int listenerKey) {
1636 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1637 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1638 }
1639
1640 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001641 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1642 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1643 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1644 new ListenerArgs(this, serviceInfo)));
1645 }
1646
1647 @Override
1648 public void unregisterServiceInfoCallback(int listenerKey) {
1649 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1650 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1651 new ListenerArgs(this, null)));
1652 }
1653
1654 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001655 public void startDaemon() {
1656 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1657 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1658 }
1659
1660 @Override
1661 public void binderDied() {
1662 mNsdStateMachine.sendMessage(
1663 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1664 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001665 }
1666
Hugo Benichi912db992017-04-24 16:41:03 +09001667 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001668 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001669 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001670 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1671 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001672 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001673 }
1674
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001675 private int getUniqueId() {
1676 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1677 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001678 }
1679
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001680 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001681 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001682 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001683 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001684 String name = service.getServiceName();
1685 String type = service.getServiceType();
1686 int port = service.getPort();
1687 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001688 final int registerInterface = getNetworkInterfaceIndex(service);
1689 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001690 Log.e(TAG, "Interface to register service on not found");
1691 return false;
1692 }
1693 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001694 }
1695
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001696 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001697 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001698 }
1699
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001700 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001701 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001702 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1703 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001704 Log.e(TAG, "Interface to discover service on not found");
1705 return false;
1706 }
paulhu2b9ed952022-02-10 21:58:32 +08001707 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001708 }
1709
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001710 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001711 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001712 }
1713
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001714 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001715 final String name = service.getServiceName();
1716 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001717 final int resolveInterface = getNetworkInterfaceIndex(service);
1718 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001719 Log.e(TAG, "Interface to resolve service on not found");
1720 return false;
1721 }
paulhu2b9ed952022-02-10 21:58:32 +08001722 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001723 }
1724
1725 /**
1726 * Guess the interface to use to resolve or discover a service on a specific network.
1727 *
1728 * This is an imperfect guess, as for example the network may be gone or not yet fully
1729 * registered. This is fine as failing is correct if the network is gone, and a client
1730 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1731 * this is to support the legacy mdnsresponder implementation, which historically resolved
1732 * services on an unspecified network.
1733 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001734 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1735 final Network network = serviceInfo.getNetwork();
1736 if (network == null) {
1737 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1738 // provided by NsdService from discovery results, and the service was found on an
1739 // interface that has no app-usable Network).
1740 if (serviceInfo.getInterfaceIndex() != 0) {
1741 return serviceInfo.getInterfaceIndex();
1742 }
1743 return IFACE_IDX_ANY;
1744 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001745
1746 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1747 if (cm == null) {
1748 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1749 return IFACE_IDX_ANY;
1750 }
1751 final LinkProperties lp = cm.getLinkProperties(network);
1752 if (lp == null) return IFACE_IDX_ANY;
1753
1754 // Only resolve on non-stacked interfaces
1755 final NetworkInterface iface;
1756 try {
1757 iface = NetworkInterface.getByName(lp.getInterfaceName());
1758 } catch (SocketException e) {
1759 Log.e(TAG, "Error querying interface", e);
1760 return IFACE_IDX_ANY;
1761 }
1762
1763 if (iface == null) {
1764 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1765 return IFACE_IDX_ANY;
1766 }
1767
1768 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001769 }
1770
1771 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001772 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001773 }
1774
paulhu2b9ed952022-02-10 21:58:32 +08001775 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1776 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001777 }
1778
1779 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001780 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001781 }
1782
1783 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001784 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1785 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001786
Paul Hub2e67d32023-04-18 05:50:14 +00001787 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1788 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001789 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001790
1791 // Dump service and clients logs
1792 pw.println();
1793 pw.increaseIndent();
1794 mServiceLogs.reverseDump(pw);
1795 pw.decreaseIndent();
1796
1797 // Dump advertiser related logs
1798 pw.println();
1799 pw.println("Advertiser:");
1800 pw.increaseIndent();
1801 mAdvertiser.dump(pw);
1802 pw.decreaseIndent();
1803
1804 // Dump discoverymanager related logs
1805 pw.println();
1806 pw.println("DiscoveryManager:");
1807 pw.increaseIndent();
1808 mMdnsDiscoveryManager.dump(pw);
1809 pw.decreaseIndent();
1810
1811 // Dump socketprovider related logs
1812 pw.println();
1813 pw.println("SocketProvider:");
1814 pw.increaseIndent();
1815 mMdnsSocketProvider.dump(pw);
1816 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001817 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001818
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001819 private abstract static class ClientRequest {
1820 private final int mGlobalId;
1821
1822 private ClientRequest(int globalId) {
1823 mGlobalId = globalId;
1824 }
1825 }
1826
1827 private static class LegacyClientRequest extends ClientRequest {
1828 private final int mRequestCode;
1829
1830 private LegacyClientRequest(int globalId, int requestCode) {
1831 super(globalId);
1832 mRequestCode = requestCode;
1833 }
1834 }
1835
1836 private static class AdvertiserClientRequest extends ClientRequest {
1837 private AdvertiserClientRequest(int globalId) {
1838 super(globalId);
1839 }
1840 }
1841
1842 private static class DiscoveryManagerRequest extends ClientRequest {
1843 @NonNull
1844 private final MdnsListener mListener;
1845
1846 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1847 super(globalId);
1848 mListener = listener;
1849 }
1850 }
1851
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001852 /* Information tracked per client */
1853 private class ClientInfo {
1854
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001855 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001856 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001857 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001858 private NsdServiceInfo mResolvedService;
1859
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001860 /* A map from client-side ID (listenerKey) to the request */
1861 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001862
Luke Huangf7277ed2021-07-12 21:15:10 +08001863 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001864 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001865 // The flag of using java backend if the client's target SDK >= U
1866 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001867 // Store client logs
1868 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001869
Paul Hub2e67d32023-04-18 05:50:14 +00001870 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001871 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001872 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001873 mClientLogs = sharedLog;
1874 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001875 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001876
1877 @Override
1878 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001879 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001880 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001881 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1882 for (int i = 0; i < mClientRequests.size(); i++) {
1883 int clientID = mClientRequests.keyAt(i);
1884 sb.append("clientId ")
1885 .append(clientID)
1886 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1887 .append(" type ").append(
1888 mClientRequests.valueAt(i).getClass().getSimpleName())
1889 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001890 }
1891 return sb.toString();
1892 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001893
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001894 private boolean isPreSClient() {
1895 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001896 }
1897
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001898 private void setPreSClient() {
1899 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001900 }
1901
Paul Hue4f5f252023-02-16 21:13:47 +08001902 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1903 final MdnsListener listener =
1904 ((DiscoveryManagerRequest) request).mListener;
1905 mMdnsDiscoveryManager.unregisterListener(
1906 listener.getListenedServiceType(), listener);
1907 }
1908
Dave Plattfeff2af2014-03-07 14:48:22 -08001909 // Remove any pending requests from the global map when we get rid of a client,
1910 // and send cancellations to the daemon.
1911 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001912 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001913 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001914 for (int i = 0; i < mClientRequests.size(); i++) {
1915 final int clientId = mClientRequests.keyAt(i);
1916 final ClientRequest request = mClientRequests.valueAt(i);
1917 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001918 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001919 if (DBG) {
1920 Log.d(TAG, "Terminating client-ID " + clientId
1921 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1922 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001923
1924 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001925 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001926 continue;
1927 }
1928
1929 if (request instanceof AdvertiserClientRequest) {
1930 mAdvertiser.removeService(globalId);
1931 continue;
1932 }
1933
1934 if (!(request instanceof LegacyClientRequest)) {
1935 throw new IllegalStateException("Unknown request type: " + request.getClass());
1936 }
1937
1938 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001939 case NsdManager.DISCOVER_SERVICES:
1940 stopServiceDiscovery(globalId);
1941 break;
1942 case NsdManager.RESOLVE_SERVICE:
1943 stopResolveService(globalId);
1944 break;
1945 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001946 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001947 break;
1948 default:
1949 break;
1950 }
1951 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001952 mClientRequests.clear();
1953 }
1954
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001955 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1956 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1957 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001958 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001959 for (int i = 0; i < mClientRequests.size(); i++) {
1960 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1961 return mClientRequests.keyAt(i);
1962 }
Christopher Lane74411222014-04-25 18:39:07 -07001963 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001964 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001965 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001966
Paul Hub2e67d32023-04-18 05:50:14 +00001967 private void log(String message) {
1968 mClientLogs.log(message);
1969 }
1970
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001971 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1972 try {
1973 mCb.onDiscoverServicesStarted(listenerKey, info);
1974 } catch (RemoteException e) {
1975 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1976 }
1977 }
1978
1979 void onDiscoverServicesFailed(int listenerKey, int error) {
1980 try {
1981 mCb.onDiscoverServicesFailed(listenerKey, error);
1982 } catch (RemoteException e) {
1983 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1984 }
1985 }
1986
1987 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1988 try {
1989 mCb.onServiceFound(listenerKey, info);
1990 } catch (RemoteException e) {
1991 Log.e(TAG, "Error calling onServiceFound(", e);
1992 }
1993 }
1994
1995 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1996 try {
1997 mCb.onServiceLost(listenerKey, info);
1998 } catch (RemoteException e) {
1999 Log.e(TAG, "Error calling onServiceLost(", e);
2000 }
2001 }
2002
2003 void onStopDiscoveryFailed(int listenerKey, int error) {
2004 try {
2005 mCb.onStopDiscoveryFailed(listenerKey, error);
2006 } catch (RemoteException e) {
2007 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2008 }
2009 }
2010
2011 void onStopDiscoverySucceeded(int listenerKey) {
2012 try {
2013 mCb.onStopDiscoverySucceeded(listenerKey);
2014 } catch (RemoteException e) {
2015 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2016 }
2017 }
2018
2019 void onRegisterServiceFailed(int listenerKey, int error) {
2020 try {
2021 mCb.onRegisterServiceFailed(listenerKey, error);
2022 } catch (RemoteException e) {
2023 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2024 }
2025 }
2026
2027 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2028 try {
2029 mCb.onRegisterServiceSucceeded(listenerKey, info);
2030 } catch (RemoteException e) {
2031 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2032 }
2033 }
2034
2035 void onUnregisterServiceFailed(int listenerKey, int error) {
2036 try {
2037 mCb.onUnregisterServiceFailed(listenerKey, error);
2038 } catch (RemoteException e) {
2039 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2040 }
2041 }
2042
2043 void onUnregisterServiceSucceeded(int listenerKey) {
2044 try {
2045 mCb.onUnregisterServiceSucceeded(listenerKey);
2046 } catch (RemoteException e) {
2047 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2048 }
2049 }
2050
2051 void onResolveServiceFailed(int listenerKey, int error) {
2052 try {
2053 mCb.onResolveServiceFailed(listenerKey, error);
2054 } catch (RemoteException e) {
2055 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2056 }
2057 }
2058
2059 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2060 try {
2061 mCb.onResolveServiceSucceeded(listenerKey, info);
2062 } catch (RemoteException e) {
2063 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2064 }
2065 }
Paul Hub58deb72022-12-26 09:24:42 +00002066
2067 void onStopResolutionFailed(int listenerKey, int error) {
2068 try {
2069 mCb.onStopResolutionFailed(listenerKey, error);
2070 } catch (RemoteException e) {
2071 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2072 }
2073 }
2074
2075 void onStopResolutionSucceeded(int listenerKey) {
2076 try {
2077 mCb.onStopResolutionSucceeded(listenerKey);
2078 } catch (RemoteException e) {
2079 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2080 }
2081 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002082
2083 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2084 try {
2085 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2086 } catch (RemoteException e) {
2087 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2088 }
2089 }
2090
2091 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2092 try {
2093 mCb.onServiceUpdated(listenerKey, info);
2094 } catch (RemoteException e) {
2095 Log.e(TAG, "Error calling onServiceUpdated", e);
2096 }
2097 }
2098
2099 void onServiceUpdatedLost(int listenerKey) {
2100 try {
2101 mCb.onServiceUpdatedLost(listenerKey);
2102 } catch (RemoteException e) {
2103 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2104 }
2105 }
2106
2107 void onServiceInfoCallbackUnregistered(int listenerKey) {
2108 try {
2109 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2110 } catch (RemoteException e) {
2111 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2112 }
2113 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002114 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002115}