blob: c93fcf663b8b74c800cc0651cd364acb2b85f908 [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;
20import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080021import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
paulhu2b9ed952022-02-10 21:58:32 +080022
Paul Hu23fa2022023-01-13 22:57:24 +080023import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080024import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080025import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070026import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090027import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090028import android.net.INetd;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090029import android.net.LinkProperties;
30import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080031import android.net.mdns.aidl.DiscoveryInfo;
32import android.net.mdns.aidl.GetAddressInfo;
33import android.net.mdns.aidl.IMDnsEventListener;
34import android.net.mdns.aidl.RegistrationInfo;
35import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070036import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090037import android.net.nsd.INsdManagerCallback;
38import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080039import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070040import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080041import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090042import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080043import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090044import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080045import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070046import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090047import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070048import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080049import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090050import android.util.Log;
51import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070052import android.util.SparseArray;
Hugo Benichid2552ae2017-04-11 14:42:47 +090053import android.util.SparseIntArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054
paulhua262cc12019-08-12 16:25:11 +080055import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080056import com.android.internal.util.State;
57import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080058import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080059import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080060import com.android.server.connectivity.mdns.ExecutorProvider;
61import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
62import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080063import com.android.server.connectivity.mdns.MdnsSearchOptions;
64import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
65import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080066import com.android.server.connectivity.mdns.MdnsSocketClientBase;
67import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080068
Irfan Sheriff77ec5582012-03-22 17:01:39 -070069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070071import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090072import java.net.NetworkInterface;
73import java.net.SocketException;
74import java.net.UnknownHostException;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070075import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080076import java.util.List;
77import java.util.regex.Matcher;
78import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070079
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080/**
81 * Network Service Discovery Service handles remote service discovery operation requests by
82 * implementing the INsdManager interface.
83 *
84 * @hide
85 */
86public class NsdService extends INsdManager.Stub {
87 private static final String TAG = "NsdService";
88 private static final String MDNS_TAG = "mDnsConnector";
Paul Hu4bd98ef2023-01-12 13:42:07 +080089 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +080090 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -070091
paulhu2b9ed952022-02-10 21:58:32 +080092 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +000093 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090094 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070095
Hugo Benichi32be63d2017-04-05 14:06:11 +090096 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +090097 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +080098 private final MDnsManager mMDnsManager;
99 private final MDnsEventCallback mMDnsEventCallback;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800100 @Nullable
101 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
102 @Nullable
103 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
104 @Nullable
105 private final MdnsSocketProvider mMdnsSocketProvider;
Paul Hu23fa2022023-01-13 22:57:24 +0800106 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800107 // state machine thread. If change this outside state machine, it will need to introduce
108 // synchronization.
109 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800110 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700111
112 /**
113 * Clients receiving asynchronous messages
114 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900115 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700117 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900118 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700119
Luke Huang05298582021-06-13 16:52:05 +0000120 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700121
Hugo Benichi32be63d2017-04-05 14:06:11 +0900122 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700123 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800124 // The count of the connected legacy clients.
125 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700126
Paul Hu23fa2022023-01-13 22:57:24 +0800127 private static class MdnsListener implements MdnsServiceBrowserListener {
128 protected final int mClientId;
129 protected final int mTransactionId;
130 @NonNull
131 protected final NsdServiceInfo mReqServiceInfo;
132 @NonNull
133 protected final String mListenedServiceType;
134
135 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
136 @NonNull String listenedServiceType) {
137 mClientId = clientId;
138 mTransactionId = transactionId;
139 mReqServiceInfo = reqServiceInfo;
140 mListenedServiceType = listenedServiceType;
141 }
142
143 @NonNull
144 public String getListenedServiceType() {
145 return mListenedServiceType;
146 }
147
148 @Override
149 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
150
151 @Override
152 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
153
154 @Override
155 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
156
157 @Override
158 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
159
160 @Override
161 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
162
163 @Override
164 public void onSearchStoppedWithError(int error) { }
165
166 @Override
167 public void onSearchFailedToStart() { }
168
169 @Override
170 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
171
172 @Override
173 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
174 }
175
176 private class DiscoveryListener extends MdnsListener {
177
178 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
179 @NonNull String listenServiceType) {
180 super(clientId, transactionId, reqServiceInfo, listenServiceType);
181 }
182
183 @Override
184 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
185 // TODO: implement service name discovered callback.
186 }
187
188 @Override
189 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
190 // TODO: implement service name removed callback.
191 }
192 }
193
Irfan Sheriff75006652012-04-17 23:15:29 -0700194 private class NsdStateMachine extends StateMachine {
195
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700196 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700197 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700198
199 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700200 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900201 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700202 }
203
Luke Huang92860f92021-06-23 06:29:30 +0000204 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800205 if (mIsDaemonStarted) {
206 if (DBG) Log.d(TAG, "Daemon is already started.");
207 return;
208 }
209 mMDnsManager.registerEventListener(mMDnsEventCallback);
210 mMDnsManager.startDaemon();
211 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000212 maybeScheduleStop();
213 }
214
paulhu2b9ed952022-02-10 21:58:32 +0800215 private void maybeStopDaemon() {
216 if (!mIsDaemonStarted) {
217 if (DBG) Log.d(TAG, "Daemon has not been started.");
218 return;
219 }
220 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
221 mMDnsManager.stopDaemon();
222 mIsDaemonStarted = false;
223 }
224
Luke Huang92860f92021-06-23 06:29:30 +0000225 private boolean isAnyRequestActive() {
226 return mIdToClientInfoMap.size() != 0;
227 }
228
229 private void scheduleStop() {
230 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
231 }
232 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800233 // The native daemon should stay alive and can't be cleanup
234 // if any legacy client connected.
235 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000236 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000237 }
238 }
239
Luke Huang92860f92021-06-23 06:29:30 +0000240 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000241 this.removeMessages(NsdManager.DAEMON_CLEANUP);
242 }
243
Paul Hu23fa2022023-01-13 22:57:24 +0800244 private void maybeStartMonitoringSockets() {
245 if (mIsMonitoringSocketsStarted) {
246 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
247 return;
248 }
249
250 mMdnsSocketProvider.startMonitoringSockets();
251 mIsMonitoringSocketsStarted = true;
252 }
253
254 private void maybeStopMonitoringSockets() {
255 if (!mIsMonitoringSocketsStarted) {
256 if (DBG) Log.d(TAG, "Socket monitoring has not been started.");
257 return;
258 }
259 mMdnsSocketProvider.stopMonitoringSockets();
260 mIsMonitoringSocketsStarted = false;
261 }
262
263 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
264 if (!isAnyRequestActive()) {
265 maybeStopMonitoringSockets();
266 }
267 }
268
Hugo Benichi803a2f02017-04-24 11:35:06 +0900269 NsdStateMachine(String name, Handler handler) {
270 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700271 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700272 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800273 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900274 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700275 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700276 }
277
278 class DefaultState extends State {
279 @Override
280 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900281 final ClientInfo cInfo;
282 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700283 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900284 case NsdManager.REGISTER_CLIENT:
285 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
286 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
287 final INsdManagerCallback cb = arg.second;
288 try {
289 cb.asBinder().linkToDeath(arg.first, 0);
290 cInfo = new ClientInfo(cb);
291 mClients.put(arg.first, cInfo);
292 } catch (RemoteException e) {
293 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700294 }
295 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900296 case NsdManager.UNREGISTER_CLIENT:
297 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
298 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800299 if (cInfo != null) {
Paul Hu23fa2022023-01-13 22:57:24 +0800300 if (mMdnsDiscoveryManager != null) {
301 cInfo.unregisterAllListeners();
302 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800303 cInfo.expungeAllRequests();
Luke Huangf7277ed2021-07-12 21:15:10 +0800304 if (cInfo.isLegacy()) {
305 mLegacyClientCount -= 1;
306 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800307 }
Paul Hu23fa2022023-01-13 22:57:24 +0800308 if (mMdnsDiscoveryManager != null) {
309 maybeStopMonitoringSocketsIfNoActiveRequest();
310 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800311 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700312 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700313 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900314 cInfo = getClientInfoForReply(msg);
315 if (cInfo != null) {
316 cInfo.onDiscoverServicesFailed(
317 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
318 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700319 break;
320 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900321 cInfo = getClientInfoForReply(msg);
322 if (cInfo != null) {
323 cInfo.onStopDiscoveryFailed(
324 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
325 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700326 break;
327 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900328 cInfo = getClientInfoForReply(msg);
329 if (cInfo != null) {
330 cInfo.onRegisterServiceFailed(
331 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
332 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700333 break;
334 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900335 cInfo = getClientInfoForReply(msg);
336 if (cInfo != null) {
337 cInfo.onUnregisterServiceFailed(
338 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
339 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700340 break;
341 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900342 cInfo = getClientInfoForReply(msg);
343 if (cInfo != null) {
344 cInfo.onResolveServiceFailed(
345 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
346 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700347 break;
Luke Huang05298582021-06-13 16:52:05 +0000348 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800349 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000350 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800351 // This event should be only sent by the legacy (target SDK < S) clients.
352 // Mark the sending client as legacy.
353 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900354 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800355 if (cInfo != null) {
356 cancelStop();
357 cInfo.setLegacy();
358 mLegacyClientCount += 1;
359 maybeStartDaemon();
360 }
361 break;
Paul Hu23fa2022023-01-13 22:57:24 +0800362 case NsdManager.MDNS_MONITORING_SOCKETS_CLEANUP:
363 maybeStopMonitoringSockets();
364 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700365 default:
paulhub2225702021-11-17 09:35:33 +0800366 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700367 return NOT_HANDLED;
368 }
369 return HANDLED;
370 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900371
372 private ClientInfo getClientInfoForReply(Message msg) {
373 final ListenerArgs args = (ListenerArgs) msg.obj;
374 return mClients.get(args.connector);
375 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700376 }
377
Irfan Sheriff75006652012-04-17 23:15:29 -0700378 class EnabledState extends State {
379 @Override
380 public void enter() {
381 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700382 }
383
384 @Override
385 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000386 // TODO: it is incorrect to stop the daemon without expunging all requests
387 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000388 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700389 }
390
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700391 private boolean requestLimitReached(ClientInfo clientInfo) {
392 if (clientInfo.mClientIds.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800393 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700394 return true;
395 }
396 return false;
397 }
398
Dave Plattfeff2af2014-03-07 14:48:22 -0800399 private void storeRequestMap(int clientId, int globalId, ClientInfo clientInfo, int what) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700400 clientInfo.mClientIds.put(clientId, globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -0800401 clientInfo.mClientRequests.put(clientId, what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700402 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000403 // Remove the cleanup event because here comes a new request.
404 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700405 }
406
407 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900408 clientInfo.mClientIds.delete(clientId);
409 clientInfo.mClientRequests.delete(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700410 mIdToClientInfoMap.remove(globalId);
Luke Huang05298582021-06-13 16:52:05 +0000411 maybeScheduleStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700412 }
413
Paul Hu23fa2022023-01-13 22:57:24 +0800414 private void storeListenerMap(int clientId, int transactionId, MdnsListener listener,
415 ClientInfo clientInfo) {
416 clientInfo.mClientIds.put(clientId, transactionId);
417 clientInfo.mListeners.put(clientId, listener);
418 mIdToClientInfoMap.put(transactionId, clientInfo);
419 removeMessages(NsdManager.MDNS_MONITORING_SOCKETS_CLEANUP);
420 }
421
422 private void removeListenerMap(int clientId, int transactionId, ClientInfo clientInfo) {
423 clientInfo.mClientIds.delete(clientId);
424 clientInfo.mListeners.delete(clientId);
425 mIdToClientInfoMap.remove(transactionId);
426 maybeStopMonitoringSocketsIfNoActiveRequest();
427 }
428
429 /**
430 * Check the given service type is valid and construct it to a service type
431 * which can use for discovery / resolution service.
432 *
433 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
434 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
435 * underscore; they are alphanumerical characters or dashes or underscore, except the
436 * last one that is just alphanumerical. The last label must be _tcp or _udp.
437 *
438 * @param serviceType the request service type for discovery / resolution service
439 * @return constructed service type or null if the given service type is invalid.
440 */
441 @Nullable
442 private String constructServiceType(String serviceType) {
443 if (TextUtils.isEmpty(serviceType)) return null;
444
445 final Pattern serviceTypePattern = Pattern.compile(
446 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
447 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
448 final Matcher matcher = serviceTypePattern.matcher(serviceType);
449 if (!matcher.matches()) return null;
450 return matcher.group(1) == null
451 ? serviceType + ".local"
452 : matcher.group(1) + "._sub" + matcher.group(2) + ".local";
453 }
454
Irfan Sheriff75006652012-04-17 23:15:29 -0700455 @Override
456 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900457 final ClientInfo clientInfo;
458 final int id;
459 final int clientId = msg.arg2;
460 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700461 switch (msg.what) {
Irfan Sheriff75006652012-04-17 23:15:29 -0700462 case NsdManager.DISCOVER_SERVICES:
paulhub2225702021-11-17 09:35:33 +0800463 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900464 args = (ListenerArgs) msg.obj;
465 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000466 // If the binder death notification for a INsdManagerCallback was received
467 // before any calls are received by NsdService, the clientInfo would be
468 // cleared and cause NPE. Add a null check here to prevent this corner case.
469 if (clientInfo == null) {
470 Log.e(TAG, "Unknown connector in discovery");
471 break;
472 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700473
474 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900475 clientInfo.onDiscoverServicesFailed(
476 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700477 break;
478 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700479
Paul Hu23fa2022023-01-13 22:57:24 +0800480 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700481 id = getUniqueId();
Paul Hu23fa2022023-01-13 22:57:24 +0800482 if (mMdnsDiscoveryManager != null) {
483 final String serviceType = constructServiceType(info.getServiceType());
484 if (serviceType == null) {
485 clientInfo.onDiscoverServicesFailed(clientId,
486 NsdManager.FAILURE_INTERNAL_ERROR);
487 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700488 }
Paul Hu23fa2022023-01-13 22:57:24 +0800489
490 maybeStartMonitoringSockets();
491 final MdnsListener listener =
492 new DiscoveryListener(clientId, id, info, serviceType);
493 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
494 .setNetwork(info.getNetwork())
495 .setIsPassiveMode(true)
496 .build();
497 mMdnsDiscoveryManager.registerListener(serviceType, listener, options);
498 storeListenerMap(clientId, id, listener, clientInfo);
499 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700500 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800501 maybeStartDaemon();
502 if (discoverServices(id, info)) {
503 if (DBG) {
504 Log.d(TAG, "Discover " + msg.arg2 + " " + id
505 + info.getServiceType());
506 }
507 storeRequestMap(clientId, id, clientInfo, msg.what);
508 clientInfo.onDiscoverServicesStarted(clientId, info);
509 } else {
510 stopServiceDiscovery(id);
511 clientInfo.onDiscoverServicesFailed(clientId,
512 NsdManager.FAILURE_INTERNAL_ERROR);
513 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700514 }
515 break;
516 case NsdManager.STOP_DISCOVERY:
paulhub2225702021-11-17 09:35:33 +0800517 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900518 args = (ListenerArgs) msg.obj;
519 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000520 // If the binder death notification for a INsdManagerCallback was received
521 // before any calls are received by NsdService, the clientInfo would be
522 // cleared and cause NPE. Add a null check here to prevent this corner case.
523 if (clientInfo == null) {
524 Log.e(TAG, "Unknown connector in stop discovery");
525 break;
526 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700527
528 try {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900529 id = clientInfo.mClientIds.get(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700530 } catch (NullPointerException e) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900531 clientInfo.onStopDiscoveryFailed(
532 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700533 break;
534 }
Paul Hu23fa2022023-01-13 22:57:24 +0800535 if (mMdnsDiscoveryManager != null) {
536 final MdnsListener listener = clientInfo.mListeners.get(clientId);
537 if (listener == null) {
538 clientInfo.onStopDiscoveryFailed(
539 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
540 break;
541 }
542 mMdnsDiscoveryManager.unregisterListener(
543 listener.getListenedServiceType(), listener);
544 removeListenerMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900545 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700546 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800547 removeRequestMap(clientId, id, clientInfo);
548 if (stopServiceDiscovery(id)) {
549 clientInfo.onStopDiscoverySucceeded(clientId);
550 } else {
551 clientInfo.onStopDiscoveryFailed(
552 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
553 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700554 }
555 break;
556 case NsdManager.REGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800557 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900558 args = (ListenerArgs) msg.obj;
559 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000560 // If the binder death notification for a INsdManagerCallback was received
561 // before any calls are received by NsdService, the clientInfo would be
562 // cleared and cause NPE. Add a null check here to prevent this corner case.
563 if (clientInfo == null) {
564 Log.e(TAG, "Unknown connector in registration");
565 break;
566 }
567
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700568 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900569 clientInfo.onRegisterServiceFailed(
570 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700571 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700572 }
573
Luke Huang05298582021-06-13 16:52:05 +0000574 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700575 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900576 if (registerService(id, args.serviceInfo)) {
paulhub2225702021-11-17 09:35:33 +0800577 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900578 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700579 // Return success after mDns reports success
Irfan Sheriff75006652012-04-17 23:15:29 -0700580 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700581 unregisterService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900582 clientInfo.onRegisterServiceFailed(
583 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700584 }
585 break;
586 case NsdManager.UNREGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800587 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900588 args = (ListenerArgs) msg.obj;
589 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000590 // If the binder death notification for a INsdManagerCallback was received
591 // before any calls are received by NsdService, the clientInfo would be
592 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900593 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800594 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700595 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700596 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900597 id = clientInfo.mClientIds.get(clientId);
598 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700599 if (unregisterService(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900600 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700601 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 clientInfo.onUnregisterServiceFailed(
603 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700604 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 break;
606 case NsdManager.RESOLVE_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800607 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900608 args = (ListenerArgs) msg.obj;
609 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000610 // If the binder death notification for a INsdManagerCallback was received
611 // before any calls are received by NsdService, the clientInfo would be
612 // cleared and cause NPE. Add a null check here to prevent this corner case.
613 if (clientInfo == null) {
614 Log.e(TAG, "Unknown connector in resolution");
615 break;
616 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617
618 if (clientInfo.mResolvedService != null) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900619 clientInfo.onResolveServiceFailed(
620 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
Irfan Sheriff75006652012-04-17 23:15:29 -0700621 break;
622 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700623
Luke Huang05298582021-06-13 16:52:05 +0000624 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700625 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900626 if (resolveService(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700627 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900628 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900630 clientInfo.onResolveServiceFailed(
631 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700632 }
633 break;
paulhu2b9ed952022-02-10 21:58:32 +0800634 case MDNS_SERVICE_EVENT:
635 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900636 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700637 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700638 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700639 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900640 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700641 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900642 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700643 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700644
paulhu2b9ed952022-02-10 21:58:32 +0800645 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700646 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700647 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
648 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800649 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900650 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700651 }
652
653 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700654 int clientId = clientInfo.getClientId(id);
655 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700656 // This can happen because of race conditions. For example,
657 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
658 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800659 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
660 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900661 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700662 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900663 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800664 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900665 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700666 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800667 case IMDnsEventListener.SERVICE_FOUND: {
668 final DiscoveryInfo info = (DiscoveryInfo) obj;
669 final String name = info.serviceName;
670 final String type = info.registrationType;
671 servInfo = new NsdServiceInfo(name, type);
672 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900673 if (foundNetId == 0L) {
674 // Ignore services that do not have a Network: they are not usable
675 // by apps, as they would need privileged permissions to use
676 // interfaces that do not have an associated Network.
677 break;
678 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900679 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900680 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700681 break;
paulhu2b9ed952022-02-10 21:58:32 +0800682 }
683 case IMDnsEventListener.SERVICE_LOST: {
684 final DiscoveryInfo info = (DiscoveryInfo) obj;
685 final String name = info.serviceName;
686 final String type = info.registrationType;
687 final int lostNetId = info.netId;
688 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900689 // The network could be set to null (netId 0) if it was torn down when the
690 // service is lost
691 // TODO: avoid returning null in that case, possibly by remembering
692 // found services on the same interface index and their network at the time
693 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900694 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700695 break;
paulhu2b9ed952022-02-10 21:58:32 +0800696 }
697 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900698 clientInfo.onDiscoverServicesFailed(
699 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700700 break;
paulhu2b9ed952022-02-10 21:58:32 +0800701 case IMDnsEventListener.SERVICE_REGISTERED: {
702 final RegistrationInfo info = (RegistrationInfo) obj;
703 final String name = info.serviceName;
704 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900705 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700706 break;
paulhu2b9ed952022-02-10 21:58:32 +0800707 }
708 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900709 clientInfo.onRegisterServiceFailed(
710 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700711 break;
paulhu2b9ed952022-02-10 21:58:32 +0800712 case IMDnsEventListener.SERVICE_RESOLVED: {
713 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700714 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800715 final String fullName = info.serviceFullName;
716 while (index < fullName.length() && fullName.charAt(index) != '.') {
717 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700718 ++index;
719 }
720 ++index;
721 }
paulhu2b9ed952022-02-10 21:58:32 +0800722 if (index >= fullName.length()) {
723 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700724 break;
725 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900726
paulhube186602022-04-12 07:18:23 +0000727 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800728 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700729 String type = rest.replace(".local.", "");
730
731 clientInfo.mResolvedService.setServiceName(name);
732 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800733 clientInfo.mResolvedService.setPort(info.port);
734 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900735 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700736
737 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800738 removeRequestMap(clientId, id, clientInfo);
739
paulhu2b9ed952022-02-10 21:58:32 +0800740 final int id2 = getUniqueId();
741 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800742 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800743 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900744 clientInfo.onResolveServiceFailed(
745 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700746 clientInfo.mResolvedService = null;
747 }
748 break;
paulhu2b9ed952022-02-10 21:58:32 +0800749 }
750 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700751 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700752 stopResolveService(id);
753 removeRequestMap(clientId, id, clientInfo);
754 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900755 clientInfo.onResolveServiceFailed(
756 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700757 break;
paulhu2b9ed952022-02-10 21:58:32 +0800758 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700759 /* NNN resolveId errorCode */
760 stopGetAddrInfo(id);
761 removeRequestMap(clientId, id, clientInfo);
762 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900763 clientInfo.onResolveServiceFailed(
764 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700765 break;
paulhu2b9ed952022-02-10 21:58:32 +0800766 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900767 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800768 final GetAddressInfo info = (GetAddressInfo) obj;
769 final String address = info.address;
770 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900771 InetAddress serviceHost = null;
772 try {
paulhu2b9ed952022-02-10 21:58:32 +0800773 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900774 } catch (UnknownHostException e) {
775 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
776 }
777
778 // If the resolved service is on an interface without a network, consider it
779 // as a failure: it would not be usable by apps as they would need
780 // privileged permissions.
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900781 if (netId != NETID_UNSET && serviceHost != null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900782 clientInfo.mResolvedService.setHost(serviceHost);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900783 setServiceNetworkForCallback(clientInfo.mResolvedService,
784 netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900785 clientInfo.onResolveServiceSucceeded(
786 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900787 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900788 clientInfo.onResolveServiceFailed(
789 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700790 }
791 stopGetAddrInfo(id);
792 removeRequestMap(clientId, id, clientInfo);
793 clientInfo.mResolvedService = null;
794 break;
paulhu2b9ed952022-02-10 21:58:32 +0800795 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700796 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900797 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700798 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900799 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700800 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700801 }
802 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700803
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900804 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
805 switch (netId) {
806 case NETID_UNSET:
807 info.setNetwork(null);
808 break;
809 case INetd.LOCAL_NET_ID:
810 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
811 // visible / usable for apps, so do not return it. Store the interface
812 // index instead, so at least if the client tries to resolve the service
813 // with that NsdServiceInfo, it will be done on the same interface.
814 // If they recreate the NsdServiceInfo themselves, resolution would be
815 // done on all interfaces as before T, which should also work.
816 info.setNetwork(null);
817 info.setInterfaceIndex(ifaceIdx);
818 break;
819 default:
820 info.setNetwork(new Network(netId));
821 }
822 }
823
paulhube186602022-04-12 07:18:23 +0000824 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
825 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
826 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
827 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
828 private String unescape(String s) {
829 StringBuilder sb = new StringBuilder(s.length());
830 for (int i = 0; i < s.length(); ++i) {
831 char c = s.charAt(i);
832 if (c == '\\') {
833 if (++i >= s.length()) {
834 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
835 break;
836 }
837 c = s.charAt(i);
838 if (c != '.' && c != '\\') {
839 if (i + 2 >= s.length()) {
840 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
841 break;
842 }
843 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
844 + (s.charAt(i + 2) - '0'));
845 i += 2;
846 }
847 }
848 sb.append(c);
849 }
850 return sb.toString();
851 }
852
Hugo Benichi803a2f02017-04-24 11:35:06 +0900853 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +0800854 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +0800855 this(ctx, handler, cleanupDelayMs, new Dependencies());
856 }
857
858 @VisibleForTesting
859 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +0000860 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900861 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900862 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700863 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +0800864 mMDnsManager = ctx.getSystemService(MDnsManager.class);
865 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Paul Hu4bd98ef2023-01-12 13:42:07 +0800866 if (deps.isMdnsDiscoveryManagerEnabled(ctx)) {
867 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
868 mMdnsSocketClient =
869 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
870 mMdnsDiscoveryManager =
871 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
872 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
873 } else {
874 mMdnsSocketProvider = null;
875 mMdnsSocketClient = null;
876 mMdnsDiscoveryManager = null;
877 }
878 }
879
880 /**
881 * Dependencies of NsdService, for injection in tests.
882 */
883 @VisibleForTesting
884 public static class Dependencies {
885 /**
886 * Check whether or not MdnsDiscoveryManager feature is enabled.
887 *
888 * @param context The global context information about an app environment.
889 * @return true if MdnsDiscoveryManager feature is enabled.
890 */
891 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
892 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
893 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
894 }
895
896 /**
897 * @see MdnsDiscoveryManager
898 */
899 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
900 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
901 return new MdnsDiscoveryManager(executorProvider, socketClient);
902 }
903
904 /**
905 * @see MdnsSocketProvider
906 */
907 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
908 return new MdnsSocketProvider(context, looper);
909 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700910 }
911
paulhu1b35e822022-04-08 14:48:41 +0800912 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900913 HandlerThread thread = new HandlerThread(TAG);
914 thread.start();
915 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +0800916 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700917 return service;
918 }
919
paulhu2b9ed952022-02-10 21:58:32 +0800920 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
921 private final StateMachine mStateMachine;
922
923 MDnsEventCallback(StateMachine sm) {
924 mStateMachine = sm;
925 }
926
927 @Override
928 public void onServiceRegistrationStatus(final RegistrationInfo status) {
929 mStateMachine.sendMessage(
930 MDNS_SERVICE_EVENT, status.result, status.id, status);
931 }
932
933 @Override
934 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
935 mStateMachine.sendMessage(
936 MDNS_SERVICE_EVENT, status.result, status.id, status);
937 }
938
939 @Override
940 public void onServiceResolutionStatus(final ResolutionInfo status) {
941 mStateMachine.sendMessage(
942 MDNS_SERVICE_EVENT, status.result, status.id, status);
943 }
944
945 @Override
946 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
947 mStateMachine.sendMessage(
948 MDNS_SERVICE_EVENT, status.result, status.id, status);
949 }
950
951 @Override
952 public int getInterfaceVersion() throws RemoteException {
953 return this.VERSION;
954 }
955
956 @Override
957 public String getInterfaceHash() throws RemoteException {
958 return this.HASH;
959 }
960 }
961
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900962 @Override
963 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900965 final INsdServiceConnector connector = new NsdServiceConnector();
966 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
967 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
968 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -0700969 }
970
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900971 private static class ListenerArgs {
972 public final NsdServiceConnector connector;
973 public final NsdServiceInfo serviceInfo;
974 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
975 this.connector = connector;
976 this.serviceInfo = serviceInfo;
977 }
978 }
979
980 private class NsdServiceConnector extends INsdServiceConnector.Stub
981 implements IBinder.DeathRecipient {
982 @Override
983 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
984 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
985 NsdManager.REGISTER_SERVICE, 0, listenerKey,
986 new ListenerArgs(this, serviceInfo)));
987 }
988
989 @Override
990 public void unregisterService(int listenerKey) {
991 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
992 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
993 new ListenerArgs(this, null)));
994 }
995
996 @Override
997 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
998 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
999 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1000 new ListenerArgs(this, serviceInfo)));
1001 }
1002
1003 @Override
1004 public void stopDiscovery(int listenerKey) {
1005 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1006 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1007 }
1008
1009 @Override
1010 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1011 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1012 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1013 new ListenerArgs(this, serviceInfo)));
1014 }
1015
1016 @Override
1017 public void startDaemon() {
1018 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1019 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1020 }
1021
1022 @Override
1023 public void binderDied() {
1024 mNsdStateMachine.sendMessage(
1025 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1026 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001027 }
1028
Hugo Benichi912db992017-04-24 16:41:03 +09001029 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001030 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001031 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001032 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1033 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001034 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001035 }
1036
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001037 private int getUniqueId() {
1038 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1039 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001040 }
1041
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001042 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001043 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001044 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001045 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001046 String name = service.getServiceName();
1047 String type = service.getServiceType();
1048 int port = service.getPort();
1049 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001050 final int registerInterface = getNetworkInterfaceIndex(service);
1051 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001052 Log.e(TAG, "Interface to register service on not found");
1053 return false;
1054 }
1055 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001056 }
1057
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001058 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001059 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001060 }
1061
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001062 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001063 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001064 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1065 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001066 Log.e(TAG, "Interface to discover service on not found");
1067 return false;
1068 }
paulhu2b9ed952022-02-10 21:58:32 +08001069 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001070 }
1071
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001072 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001073 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001074 }
1075
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001076 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001077 final String name = service.getServiceName();
1078 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001079 final int resolveInterface = getNetworkInterfaceIndex(service);
1080 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001081 Log.e(TAG, "Interface to resolve service on not found");
1082 return false;
1083 }
paulhu2b9ed952022-02-10 21:58:32 +08001084 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001085 }
1086
1087 /**
1088 * Guess the interface to use to resolve or discover a service on a specific network.
1089 *
1090 * This is an imperfect guess, as for example the network may be gone or not yet fully
1091 * registered. This is fine as failing is correct if the network is gone, and a client
1092 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1093 * this is to support the legacy mdnsresponder implementation, which historically resolved
1094 * services on an unspecified network.
1095 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001096 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1097 final Network network = serviceInfo.getNetwork();
1098 if (network == null) {
1099 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1100 // provided by NsdService from discovery results, and the service was found on an
1101 // interface that has no app-usable Network).
1102 if (serviceInfo.getInterfaceIndex() != 0) {
1103 return serviceInfo.getInterfaceIndex();
1104 }
1105 return IFACE_IDX_ANY;
1106 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001107
1108 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1109 if (cm == null) {
1110 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1111 return IFACE_IDX_ANY;
1112 }
1113 final LinkProperties lp = cm.getLinkProperties(network);
1114 if (lp == null) return IFACE_IDX_ANY;
1115
1116 // Only resolve on non-stacked interfaces
1117 final NetworkInterface iface;
1118 try {
1119 iface = NetworkInterface.getByName(lp.getInterfaceName());
1120 } catch (SocketException e) {
1121 Log.e(TAG, "Error querying interface", e);
1122 return IFACE_IDX_ANY;
1123 }
1124
1125 if (iface == null) {
1126 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1127 return IFACE_IDX_ANY;
1128 }
1129
1130 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001131 }
1132
1133 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001134 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001135 }
1136
paulhu2b9ed952022-02-10 21:58:32 +08001137 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1138 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001139 }
1140
1141 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001142 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001143 }
1144
1145 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001146 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001147 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001148
Irfan Sheriff75006652012-04-17 23:15:29 -07001149 for (ClientInfo client : mClients.values()) {
1150 pw.println("Client Info");
1151 pw.println(client);
1152 }
1153
1154 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001155 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001156
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001157 /* Information tracked per client */
1158 private class ClientInfo {
1159
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001160 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001161 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001162 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001163 private NsdServiceInfo mResolvedService;
1164
1165 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001166 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001167
Dave Plattfeff2af2014-03-07 14:48:22 -08001168 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001169 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -08001170
Paul Hu23fa2022023-01-13 22:57:24 +08001171 /* A map from client id to the MdnsListener */
1172 private final SparseArray<MdnsListener> mListeners = new SparseArray<>();
1173
Luke Huangf7277ed2021-07-12 21:15:10 +08001174 // The target SDK of this client < Build.VERSION_CODES.S
1175 private boolean mIsLegacy = false;
1176
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001177 private ClientInfo(INsdManagerCallback cb) {
1178 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001179 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001180 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001181
1182 @Override
1183 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001184 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001185 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +08001186 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001187 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001188 int clientID = mClientIds.keyAt(i);
1189 sb.append("clientId ").append(clientID).
1190 append(" mDnsId ").append(mClientIds.valueAt(i)).
1191 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001192 }
1193 return sb.toString();
1194 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001195
Luke Huangf7277ed2021-07-12 21:15:10 +08001196 private boolean isLegacy() {
1197 return mIsLegacy;
1198 }
1199
1200 private void setLegacy() {
1201 mIsLegacy = true;
1202 }
1203
Dave Plattfeff2af2014-03-07 14:48:22 -08001204 // Remove any pending requests from the global map when we get rid of a client,
1205 // and send cancellations to the daemon.
1206 private void expungeAllRequests() {
1207 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +09001208 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -08001209 for (i = 0; i < mClientIds.size(); i++) {
1210 clientId = mClientIds.keyAt(i);
1211 globalId = mClientIds.valueAt(i);
1212 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001213 if (DBG) {
1214 Log.d(TAG, "Terminating client-ID " + clientId
1215 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1216 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001217 switch (mClientRequests.get(clientId)) {
1218 case NsdManager.DISCOVER_SERVICES:
1219 stopServiceDiscovery(globalId);
1220 break;
1221 case NsdManager.RESOLVE_SERVICE:
1222 stopResolveService(globalId);
1223 break;
1224 case NsdManager.REGISTER_SERVICE:
1225 unregisterService(globalId);
1226 break;
1227 default:
1228 break;
1229 }
1230 }
1231 mClientIds.clear();
1232 mClientRequests.clear();
1233 }
1234
Paul Hu23fa2022023-01-13 22:57:24 +08001235 void unregisterAllListeners() {
1236 for (int i = 0; i < mListeners.size(); i++) {
1237 final MdnsListener listener = mListeners.valueAt(i);
1238 mMdnsDiscoveryManager.unregisterListener(
1239 listener.getListenedServiceType(), listener);
1240 }
1241 mListeners.clear();
1242 }
1243
Christopher Lane74411222014-04-25 18:39:07 -07001244 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
1245 // return the corresponding listener id. mDnsClient id is also called a global id.
1246 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001247 int idx = mClientIds.indexOfValue(globalId);
1248 if (idx < 0) {
1249 return idx;
Christopher Lane74411222014-04-25 18:39:07 -07001250 }
Hugo Benichid2552ae2017-04-11 14:42:47 +09001251 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -07001252 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001253
1254 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1255 try {
1256 mCb.onDiscoverServicesStarted(listenerKey, info);
1257 } catch (RemoteException e) {
1258 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1259 }
1260 }
1261
1262 void onDiscoverServicesFailed(int listenerKey, int error) {
1263 try {
1264 mCb.onDiscoverServicesFailed(listenerKey, error);
1265 } catch (RemoteException e) {
1266 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1267 }
1268 }
1269
1270 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1271 try {
1272 mCb.onServiceFound(listenerKey, info);
1273 } catch (RemoteException e) {
1274 Log.e(TAG, "Error calling onServiceFound(", e);
1275 }
1276 }
1277
1278 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1279 try {
1280 mCb.onServiceLost(listenerKey, info);
1281 } catch (RemoteException e) {
1282 Log.e(TAG, "Error calling onServiceLost(", e);
1283 }
1284 }
1285
1286 void onStopDiscoveryFailed(int listenerKey, int error) {
1287 try {
1288 mCb.onStopDiscoveryFailed(listenerKey, error);
1289 } catch (RemoteException e) {
1290 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1291 }
1292 }
1293
1294 void onStopDiscoverySucceeded(int listenerKey) {
1295 try {
1296 mCb.onStopDiscoverySucceeded(listenerKey);
1297 } catch (RemoteException e) {
1298 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1299 }
1300 }
1301
1302 void onRegisterServiceFailed(int listenerKey, int error) {
1303 try {
1304 mCb.onRegisterServiceFailed(listenerKey, error);
1305 } catch (RemoteException e) {
1306 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1307 }
1308 }
1309
1310 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1311 try {
1312 mCb.onRegisterServiceSucceeded(listenerKey, info);
1313 } catch (RemoteException e) {
1314 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1315 }
1316 }
1317
1318 void onUnregisterServiceFailed(int listenerKey, int error) {
1319 try {
1320 mCb.onUnregisterServiceFailed(listenerKey, error);
1321 } catch (RemoteException e) {
1322 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1323 }
1324 }
1325
1326 void onUnregisterServiceSucceeded(int listenerKey) {
1327 try {
1328 mCb.onUnregisterServiceSucceeded(listenerKey);
1329 } catch (RemoteException e) {
1330 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1331 }
1332 }
1333
1334 void onResolveServiceFailed(int listenerKey, int error) {
1335 try {
1336 mCb.onResolveServiceFailed(listenerKey, error);
1337 } catch (RemoteException e) {
1338 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1339 }
1340 }
1341
1342 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1343 try {
1344 mCb.onResolveServiceSucceeded(listenerKey, info);
1345 } catch (RemoteException e) {
1346 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1347 }
1348 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001349 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001350}