blob: 1882cf4404f400cb7d5cf0f4f75468f177242e3d [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;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090022import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080023
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090024import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
25
Paul Hu23fa2022023-01-13 22:57:24 +080026import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080027import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080028import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070029import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090030import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090031import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080032import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090033import android.net.LinkProperties;
34import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080035import android.net.mdns.aidl.DiscoveryInfo;
36import android.net.mdns.aidl.GetAddressInfo;
37import android.net.mdns.aidl.IMDnsEventListener;
38import android.net.mdns.aidl.RegistrationInfo;
39import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070040import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090041import android.net.nsd.INsdManagerCallback;
42import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080043import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070044import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080045import android.net.nsd.NsdServiceInfo;
Paul Hub2e67d32023-04-18 05:50:14 +000046import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090047import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080048import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090049import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080050import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070051import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070053import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080054import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.util.Log;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070056import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000059import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080060import com.android.internal.util.State;
61import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080062import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090063import com.android.net.module.util.InetAddressUtils;
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 {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001243 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1244 ipv6Address);
1245 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1246 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001247 Log.wtf(TAG, "Invalid ipv6 address", e);
1248 }
1249 }
1250 return addresses;
1251 }
1252
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001253 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1254 switch (netId) {
1255 case NETID_UNSET:
1256 info.setNetwork(null);
1257 break;
1258 case INetd.LOCAL_NET_ID:
1259 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1260 // visible / usable for apps, so do not return it. Store the interface
1261 // index instead, so at least if the client tries to resolve the service
1262 // with that NsdServiceInfo, it will be done on the same interface.
1263 // If they recreate the NsdServiceInfo themselves, resolution would be
1264 // done on all interfaces as before T, which should also work.
1265 info.setNetwork(null);
1266 info.setInterfaceIndex(ifaceIdx);
1267 break;
1268 default:
1269 info.setNetwork(new Network(netId));
1270 }
1271 }
1272
paulhube186602022-04-12 07:18:23 +00001273 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1274 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1275 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1276 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1277 private String unescape(String s) {
1278 StringBuilder sb = new StringBuilder(s.length());
1279 for (int i = 0; i < s.length(); ++i) {
1280 char c = s.charAt(i);
1281 if (c == '\\') {
1282 if (++i >= s.length()) {
1283 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1284 break;
1285 }
1286 c = s.charAt(i);
1287 if (c != '.' && c != '\\') {
1288 if (i + 2 >= s.length()) {
1289 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1290 break;
1291 }
1292 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1293 + (s.charAt(i + 2) - '0'));
1294 i += 2;
1295 }
1296 }
1297 sb.append(c);
1298 }
1299 return sb.toString();
1300 }
1301
Paul Hu7445e3d2023-03-03 15:14:00 +08001302 /**
1303 * Check the given service type is valid and construct it to a service type
1304 * which can use for discovery / resolution service.
1305 *
1306 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1307 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1308 * underscore; they are alphanumerical characters or dashes or underscore, except the
1309 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1310 *
1311 * @param serviceType the request service type for discovery / resolution service
1312 * @return constructed service type or null if the given service type is invalid.
1313 */
1314 @Nullable
1315 public static String constructServiceType(String serviceType) {
1316 if (TextUtils.isEmpty(serviceType)) return null;
1317
1318 final Pattern serviceTypePattern = Pattern.compile(
1319 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1320 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1321 // Drop '.' at the end of service type that is compatible with old backend.
1322 + "\\.?$");
1323 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1324 if (!matcher.matches()) return null;
1325 return matcher.group(1) == null
1326 ? matcher.group(2)
1327 : matcher.group(1) + "_sub." + matcher.group(2);
1328 }
1329
Hugo Benichi803a2f02017-04-24 11:35:06 +09001330 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001331 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001332 this(ctx, handler, cleanupDelayMs, new Dependencies());
1333 }
1334
1335 @VisibleForTesting
1336 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001337 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001338 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001339 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001340 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001341 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1342 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001343 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001344
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001345 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Yuyang Huang700778b2023-03-08 16:17:05 +09001346 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1347 // address events are received.
1348 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001349 mMdnsSocketClient =
1350 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1351 mMdnsDiscoveryManager =
1352 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1353 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1354 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1355 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001356 }
1357
1358 /**
1359 * Dependencies of NsdService, for injection in tests.
1360 */
1361 @VisibleForTesting
1362 public static class Dependencies {
1363 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001364 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001365 *
1366 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001367 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001368 */
1369 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001370 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1371 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001372 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001373 }
1374
1375 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001376 * Check whether the MdnsAdvertiser feature is enabled.
1377 *
1378 * @param context The global context information about an app environment.
1379 * @return true if the MdnsAdvertiser feature is enabled.
1380 */
1381 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001382 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1383 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1384 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001385 }
1386
1387 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001388 * Get the type allowlist flag value.
1389 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1390 */
1391 @Nullable
1392 public String getTypeAllowlistFlags() {
1393 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1394 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1395 }
1396
1397 /**
1398 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1399 */
1400 public boolean isFeatureEnabled(Context context, String feature) {
1401 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1402 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1403 }
1404
1405 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001406 * @see MdnsDiscoveryManager
1407 */
1408 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1409 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1410 return new MdnsDiscoveryManager(executorProvider, socketClient);
1411 }
1412
1413 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001414 * @see MdnsAdvertiser
1415 */
1416 public MdnsAdvertiser makeMdnsAdvertiser(
1417 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1418 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1419 return new MdnsAdvertiser(looper, socketProvider, cb);
1420 }
1421
1422 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001423 * @see MdnsSocketProvider
1424 */
1425 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1426 return new MdnsSocketProvider(context, looper);
1427 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001428 }
1429
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001430 /**
1431 * Return whether a type is allowlisted to use the Java backend.
1432 * @param type The service type
1433 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1434 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1435 */
1436 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1437 @NonNull String flagPrefix) {
1438 if (type == null) return false;
1439 final String typesConfig = mDeps.getTypeAllowlistFlags();
1440 if (TextUtils.isEmpty(typesConfig)) return false;
1441
1442 final String mappingPrefix = type + ":";
1443 String mappedFlag = null;
1444 for (String mapping : TextUtils.split(typesConfig, ",")) {
1445 if (mapping.startsWith(mappingPrefix)) {
1446 mappedFlag = mapping.substring(mappingPrefix.length());
1447 break;
1448 }
1449 }
1450
1451 if (mappedFlag == null) return false;
1452
1453 return mDeps.isFeatureEnabled(mContext,
1454 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1455 }
1456
1457 private boolean useDiscoveryManagerForType(@Nullable String type) {
1458 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1459 }
1460
1461 private boolean useAdvertiserForType(@Nullable String type) {
1462 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1463 }
1464
paulhu1b35e822022-04-08 14:48:41 +08001465 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001466 HandlerThread thread = new HandlerThread(TAG);
1467 thread.start();
1468 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001469 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001470 return service;
1471 }
1472
paulhu2b9ed952022-02-10 21:58:32 +08001473 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1474 private final StateMachine mStateMachine;
1475
1476 MDnsEventCallback(StateMachine sm) {
1477 mStateMachine = sm;
1478 }
1479
1480 @Override
1481 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1482 mStateMachine.sendMessage(
1483 MDNS_SERVICE_EVENT, status.result, status.id, status);
1484 }
1485
1486 @Override
1487 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1488 mStateMachine.sendMessage(
1489 MDNS_SERVICE_EVENT, status.result, status.id, status);
1490 }
1491
1492 @Override
1493 public void onServiceResolutionStatus(final ResolutionInfo status) {
1494 mStateMachine.sendMessage(
1495 MDNS_SERVICE_EVENT, status.result, status.id, status);
1496 }
1497
1498 @Override
1499 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1500 mStateMachine.sendMessage(
1501 MDNS_SERVICE_EVENT, status.result, status.id, status);
1502 }
1503
1504 @Override
1505 public int getInterfaceVersion() throws RemoteException {
1506 return this.VERSION;
1507 }
1508
1509 @Override
1510 public String getInterfaceHash() throws RemoteException {
1511 return this.HASH;
1512 }
1513 }
1514
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001515 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1516 @Override
1517 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1518 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1519 if (clientInfo == null) return;
1520
1521 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1522 if (clientId < 0) return;
1523
1524 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1525 // historical behavior.
1526 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1527 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1528 }
1529
1530 @Override
1531 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1532 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1533 if (clientInfo == null) return;
1534
1535 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1536 if (clientId < 0) return;
1537
1538 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1539 }
1540
1541 private ClientInfo getClientInfoOrLog(int serviceId) {
1542 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1543 if (clientInfo == null) {
1544 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1545 }
1546 return clientInfo;
1547 }
1548
1549 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1550 final int clientId = info.getClientId(serviceId);
1551 if (clientId < 0) {
1552 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1553 }
1554 return clientId;
1555 }
1556 }
1557
Paul Hu2e0a88c2023-03-09 16:05:01 +08001558 private static class ConnectorArgs {
1559 @NonNull public final NsdServiceConnector connector;
1560 @NonNull public final INsdManagerCallback callback;
1561 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001562 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001563
1564 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001565 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001566 this.connector = connector;
1567 this.callback = callback;
1568 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001569 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001570 }
1571 }
1572
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001573 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001574 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001575 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001576 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001577 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001578 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1579 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1580 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001581 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001582 }
1583
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001584 private static class ListenerArgs {
1585 public final NsdServiceConnector connector;
1586 public final NsdServiceInfo serviceInfo;
1587 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1588 this.connector = connector;
1589 this.serviceInfo = serviceInfo;
1590 }
1591 }
1592
1593 private class NsdServiceConnector extends INsdServiceConnector.Stub
1594 implements IBinder.DeathRecipient {
1595 @Override
1596 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1597 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1598 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1599 new ListenerArgs(this, serviceInfo)));
1600 }
1601
1602 @Override
1603 public void unregisterService(int listenerKey) {
1604 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1605 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1606 new ListenerArgs(this, null)));
1607 }
1608
1609 @Override
1610 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1611 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1612 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1613 new ListenerArgs(this, serviceInfo)));
1614 }
1615
1616 @Override
1617 public void stopDiscovery(int listenerKey) {
1618 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1619 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1620 }
1621
1622 @Override
1623 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1624 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1625 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1626 new ListenerArgs(this, serviceInfo)));
1627 }
1628
1629 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001630 public void stopResolution(int listenerKey) {
1631 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1632 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1633 }
1634
1635 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001636 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1637 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1638 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1639 new ListenerArgs(this, serviceInfo)));
1640 }
1641
1642 @Override
1643 public void unregisterServiceInfoCallback(int listenerKey) {
1644 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1645 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1646 new ListenerArgs(this, null)));
1647 }
1648
1649 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001650 public void startDaemon() {
1651 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1652 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1653 }
1654
1655 @Override
1656 public void binderDied() {
1657 mNsdStateMachine.sendMessage(
1658 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1659 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001660 }
1661
Hugo Benichi912db992017-04-24 16:41:03 +09001662 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001663 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001665 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1666 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001667 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001668 }
1669
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001670 private int getUniqueId() {
1671 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1672 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001673 }
1674
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001675 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001676 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001677 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001678 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001679 String name = service.getServiceName();
1680 String type = service.getServiceType();
1681 int port = service.getPort();
1682 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001683 final int registerInterface = getNetworkInterfaceIndex(service);
1684 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001685 Log.e(TAG, "Interface to register service on not found");
1686 return false;
1687 }
1688 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001689 }
1690
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001691 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001692 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001693 }
1694
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001695 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001696 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001697 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1698 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001699 Log.e(TAG, "Interface to discover service on not found");
1700 return false;
1701 }
paulhu2b9ed952022-02-10 21:58:32 +08001702 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001703 }
1704
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001705 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001706 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001707 }
1708
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001709 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001710 final String name = service.getServiceName();
1711 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001712 final int resolveInterface = getNetworkInterfaceIndex(service);
1713 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001714 Log.e(TAG, "Interface to resolve service on not found");
1715 return false;
1716 }
paulhu2b9ed952022-02-10 21:58:32 +08001717 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001718 }
1719
1720 /**
1721 * Guess the interface to use to resolve or discover a service on a specific network.
1722 *
1723 * This is an imperfect guess, as for example the network may be gone or not yet fully
1724 * registered. This is fine as failing is correct if the network is gone, and a client
1725 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1726 * this is to support the legacy mdnsresponder implementation, which historically resolved
1727 * services on an unspecified network.
1728 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001729 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1730 final Network network = serviceInfo.getNetwork();
1731 if (network == null) {
1732 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1733 // provided by NsdService from discovery results, and the service was found on an
1734 // interface that has no app-usable Network).
1735 if (serviceInfo.getInterfaceIndex() != 0) {
1736 return serviceInfo.getInterfaceIndex();
1737 }
1738 return IFACE_IDX_ANY;
1739 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001740
1741 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1742 if (cm == null) {
1743 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1744 return IFACE_IDX_ANY;
1745 }
1746 final LinkProperties lp = cm.getLinkProperties(network);
1747 if (lp == null) return IFACE_IDX_ANY;
1748
1749 // Only resolve on non-stacked interfaces
1750 final NetworkInterface iface;
1751 try {
1752 iface = NetworkInterface.getByName(lp.getInterfaceName());
1753 } catch (SocketException e) {
1754 Log.e(TAG, "Error querying interface", e);
1755 return IFACE_IDX_ANY;
1756 }
1757
1758 if (iface == null) {
1759 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1760 return IFACE_IDX_ANY;
1761 }
1762
1763 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001764 }
1765
1766 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001767 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001768 }
1769
paulhu2b9ed952022-02-10 21:58:32 +08001770 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1771 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001772 }
1773
1774 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001775 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001776 }
1777
1778 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001779 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1780 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001781
Paul Hub2e67d32023-04-18 05:50:14 +00001782 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1783 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001784 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001785
1786 // Dump service and clients logs
1787 pw.println();
1788 pw.increaseIndent();
1789 mServiceLogs.reverseDump(pw);
1790 pw.decreaseIndent();
1791
1792 // Dump advertiser related logs
1793 pw.println();
1794 pw.println("Advertiser:");
1795 pw.increaseIndent();
1796 mAdvertiser.dump(pw);
1797 pw.decreaseIndent();
1798
1799 // Dump discoverymanager related logs
1800 pw.println();
1801 pw.println("DiscoveryManager:");
1802 pw.increaseIndent();
1803 mMdnsDiscoveryManager.dump(pw);
1804 pw.decreaseIndent();
1805
1806 // Dump socketprovider related logs
1807 pw.println();
1808 pw.println("SocketProvider:");
1809 pw.increaseIndent();
1810 mMdnsSocketProvider.dump(pw);
1811 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001812 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001813
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001814 private abstract static class ClientRequest {
1815 private final int mGlobalId;
1816
1817 private ClientRequest(int globalId) {
1818 mGlobalId = globalId;
1819 }
1820 }
1821
1822 private static class LegacyClientRequest extends ClientRequest {
1823 private final int mRequestCode;
1824
1825 private LegacyClientRequest(int globalId, int requestCode) {
1826 super(globalId);
1827 mRequestCode = requestCode;
1828 }
1829 }
1830
1831 private static class AdvertiserClientRequest extends ClientRequest {
1832 private AdvertiserClientRequest(int globalId) {
1833 super(globalId);
1834 }
1835 }
1836
1837 private static class DiscoveryManagerRequest extends ClientRequest {
1838 @NonNull
1839 private final MdnsListener mListener;
1840
1841 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1842 super(globalId);
1843 mListener = listener;
1844 }
1845 }
1846
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001847 /* Information tracked per client */
1848 private class ClientInfo {
1849
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001850 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001851 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001852 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001853 private NsdServiceInfo mResolvedService;
1854
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001855 /* A map from client-side ID (listenerKey) to the request */
1856 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001857
Luke Huangf7277ed2021-07-12 21:15:10 +08001858 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001859 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001860 // The flag of using java backend if the client's target SDK >= U
1861 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001862 // Store client logs
1863 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001864
Paul Hub2e67d32023-04-18 05:50:14 +00001865 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001866 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001867 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001868 mClientLogs = sharedLog;
1869 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001870 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001871
1872 @Override
1873 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001874 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001875 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001876 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1877 for (int i = 0; i < mClientRequests.size(); i++) {
1878 int clientID = mClientRequests.keyAt(i);
1879 sb.append("clientId ")
1880 .append(clientID)
1881 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1882 .append(" type ").append(
1883 mClientRequests.valueAt(i).getClass().getSimpleName())
1884 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001885 }
1886 return sb.toString();
1887 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001888
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001889 private boolean isPreSClient() {
1890 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001891 }
1892
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001893 private void setPreSClient() {
1894 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001895 }
1896
Paul Hue4f5f252023-02-16 21:13:47 +08001897 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1898 final MdnsListener listener =
1899 ((DiscoveryManagerRequest) request).mListener;
1900 mMdnsDiscoveryManager.unregisterListener(
1901 listener.getListenedServiceType(), listener);
1902 }
1903
Dave Plattfeff2af2014-03-07 14:48:22 -08001904 // Remove any pending requests from the global map when we get rid of a client,
1905 // and send cancellations to the daemon.
1906 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001907 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001908 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001909 for (int i = 0; i < mClientRequests.size(); i++) {
1910 final int clientId = mClientRequests.keyAt(i);
1911 final ClientRequest request = mClientRequests.valueAt(i);
1912 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001913 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001914 if (DBG) {
1915 Log.d(TAG, "Terminating client-ID " + clientId
1916 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1917 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001918
1919 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001920 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001921 continue;
1922 }
1923
1924 if (request instanceof AdvertiserClientRequest) {
1925 mAdvertiser.removeService(globalId);
1926 continue;
1927 }
1928
1929 if (!(request instanceof LegacyClientRequest)) {
1930 throw new IllegalStateException("Unknown request type: " + request.getClass());
1931 }
1932
1933 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001934 case NsdManager.DISCOVER_SERVICES:
1935 stopServiceDiscovery(globalId);
1936 break;
1937 case NsdManager.RESOLVE_SERVICE:
1938 stopResolveService(globalId);
1939 break;
1940 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001941 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001942 break;
1943 default:
1944 break;
1945 }
1946 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001947 mClientRequests.clear();
1948 }
1949
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001950 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1951 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1952 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001953 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001954 for (int i = 0; i < mClientRequests.size(); i++) {
1955 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1956 return mClientRequests.keyAt(i);
1957 }
Christopher Lane74411222014-04-25 18:39:07 -07001958 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001959 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001960 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001961
Paul Hub2e67d32023-04-18 05:50:14 +00001962 private void log(String message) {
1963 mClientLogs.log(message);
1964 }
1965
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001966 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1967 try {
1968 mCb.onDiscoverServicesStarted(listenerKey, info);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1971 }
1972 }
1973
1974 void onDiscoverServicesFailed(int listenerKey, int error) {
1975 try {
1976 mCb.onDiscoverServicesFailed(listenerKey, error);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1979 }
1980 }
1981
1982 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1983 try {
1984 mCb.onServiceFound(listenerKey, info);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onServiceFound(", e);
1987 }
1988 }
1989
1990 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1991 try {
1992 mCb.onServiceLost(listenerKey, info);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onServiceLost(", e);
1995 }
1996 }
1997
1998 void onStopDiscoveryFailed(int listenerKey, int error) {
1999 try {
2000 mCb.onStopDiscoveryFailed(listenerKey, error);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2003 }
2004 }
2005
2006 void onStopDiscoverySucceeded(int listenerKey) {
2007 try {
2008 mCb.onStopDiscoverySucceeded(listenerKey);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2011 }
2012 }
2013
2014 void onRegisterServiceFailed(int listenerKey, int error) {
2015 try {
2016 mCb.onRegisterServiceFailed(listenerKey, error);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2019 }
2020 }
2021
2022 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2023 try {
2024 mCb.onRegisterServiceSucceeded(listenerKey, info);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2027 }
2028 }
2029
2030 void onUnregisterServiceFailed(int listenerKey, int error) {
2031 try {
2032 mCb.onUnregisterServiceFailed(listenerKey, error);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2035 }
2036 }
2037
2038 void onUnregisterServiceSucceeded(int listenerKey) {
2039 try {
2040 mCb.onUnregisterServiceSucceeded(listenerKey);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2043 }
2044 }
2045
2046 void onResolveServiceFailed(int listenerKey, int error) {
2047 try {
2048 mCb.onResolveServiceFailed(listenerKey, error);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2051 }
2052 }
2053
2054 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2055 try {
2056 mCb.onResolveServiceSucceeded(listenerKey, info);
2057 } catch (RemoteException e) {
2058 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2059 }
2060 }
Paul Hub58deb72022-12-26 09:24:42 +00002061
2062 void onStopResolutionFailed(int listenerKey, int error) {
2063 try {
2064 mCb.onStopResolutionFailed(listenerKey, error);
2065 } catch (RemoteException e) {
2066 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2067 }
2068 }
2069
2070 void onStopResolutionSucceeded(int listenerKey) {
2071 try {
2072 mCb.onStopResolutionSucceeded(listenerKey);
2073 } catch (RemoteException e) {
2074 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2075 }
2076 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002077
2078 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2079 try {
2080 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2081 } catch (RemoteException e) {
2082 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2083 }
2084 }
2085
2086 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2087 try {
2088 mCb.onServiceUpdated(listenerKey, info);
2089 } catch (RemoteException e) {
2090 Log.e(TAG, "Error calling onServiceUpdated", e);
2091 }
2092 }
2093
2094 void onServiceUpdatedLost(int listenerKey) {
2095 try {
2096 mCb.onServiceUpdatedLost(listenerKey);
2097 } catch (RemoteException e) {
2098 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2099 }
2100 }
2101
2102 void onServiceInfoCallbackUnregistered(int listenerKey) {
2103 try {
2104 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2105 } catch (RemoteException e) {
2106 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2107 }
2108 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002109 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002110}