blob: 36c3cd48e94e4fdfbe4c0e2f25ecf431457de18f [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
paulhu2b9ed952022-02-10 21:58:32 +080023
Paul Hu23fa2022023-01-13 22:57:24 +080024import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080025import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080026import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070027import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090028import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090029import android.net.INetd;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090030import android.net.LinkProperties;
31import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080032import android.net.mdns.aidl.DiscoveryInfo;
33import android.net.mdns.aidl.GetAddressInfo;
34import android.net.mdns.aidl.IMDnsEventListener;
35import android.net.mdns.aidl.RegistrationInfo;
36import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070037import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090038import android.net.nsd.INsdManagerCallback;
39import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080040import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070041import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080042import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090043import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080044import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090045import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080046import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070047import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090048import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070049import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080050import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090051import android.util.Log;
52import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070053import android.util.SparseArray;
Hugo Benichid2552ae2017-04-11 14:42:47 +090054import android.util.SparseIntArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070055
paulhua262cc12019-08-12 16:25:11 +080056import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.util.State;
58import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080059import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080060import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import com.android.server.connectivity.mdns.ExecutorProvider;
62import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
63import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080064import com.android.server.connectivity.mdns.MdnsSearchOptions;
65import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
66import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080067import com.android.server.connectivity.mdns.MdnsSocketClientBase;
68import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080069
Irfan Sheriff77ec5582012-03-22 17:01:39 -070070import java.io.FileDescriptor;
71import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070072import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090073import java.net.NetworkInterface;
74import java.net.SocketException;
75import java.net.UnknownHostException;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070076import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080077import java.util.List;
78import java.util.regex.Matcher;
79import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080
Irfan Sheriff77ec5582012-03-22 17:01:39 -070081/**
82 * Network Service Discovery Service handles remote service discovery operation requests by
83 * implementing the INsdManager interface.
84 *
85 * @hide
86 */
87public class NsdService extends INsdManager.Stub {
88 private static final String TAG = "NsdService";
89 private static final String MDNS_TAG = "mDnsConnector";
Paul Hu4bd98ef2023-01-12 13:42:07 +080090 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +080091 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -070092
paulhu2b9ed952022-02-10 21:58:32 +080093 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +000094 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090095 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070096
Hugo Benichi32be63d2017-04-05 14:06:11 +090097 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +090098 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +080099 private final MDnsManager mMDnsManager;
100 private final MDnsEventCallback mMDnsEventCallback;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800101 @Nullable
102 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
103 @Nullable
104 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
105 @Nullable
106 private final MdnsSocketProvider mMdnsSocketProvider;
Paul Hu23fa2022023-01-13 22:57:24 +0800107 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800108 // state machine thread. If change this outside state machine, it will need to introduce
109 // synchronization.
110 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800111 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700112
113 /**
114 * Clients receiving asynchronous messages
115 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900116 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700117
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700118 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900119 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700120
Luke Huang05298582021-06-13 16:52:05 +0000121 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700122
Hugo Benichi32be63d2017-04-05 14:06:11 +0900123 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700124 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800125 // The count of the connected legacy clients.
126 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700127
Paul Hu23fa2022023-01-13 22:57:24 +0800128 private static class MdnsListener implements MdnsServiceBrowserListener {
129 protected final int mClientId;
130 protected final int mTransactionId;
131 @NonNull
132 protected final NsdServiceInfo mReqServiceInfo;
133 @NonNull
134 protected final String mListenedServiceType;
135
136 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
137 @NonNull String listenedServiceType) {
138 mClientId = clientId;
139 mTransactionId = transactionId;
140 mReqServiceInfo = reqServiceInfo;
141 mListenedServiceType = listenedServiceType;
142 }
143
144 @NonNull
145 public String getListenedServiceType() {
146 return mListenedServiceType;
147 }
148
149 @Override
150 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
151
152 @Override
153 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
154
155 @Override
156 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
157
158 @Override
159 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
160
161 @Override
162 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
163
164 @Override
165 public void onSearchStoppedWithError(int error) { }
166
167 @Override
168 public void onSearchFailedToStart() { }
169
170 @Override
171 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
172
173 @Override
174 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
175 }
176
177 private class DiscoveryListener extends MdnsListener {
178
179 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
180 @NonNull String listenServiceType) {
181 super(clientId, transactionId, reqServiceInfo, listenServiceType);
182 }
183
184 @Override
185 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800186 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
187 NsdManager.SERVICE_FOUND,
188 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800189 }
190
191 @Override
192 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800193 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
194 NsdManager.SERVICE_LOST,
195 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800196 }
197 }
198
Paul Hu019621e2023-01-13 23:26:49 +0800199 /**
200 * Data class of mdns service callback information.
201 */
202 private static class MdnsEvent {
203 final int mClientId;
204 @NonNull
205 final String mRequestedServiceType;
206 @NonNull
207 final MdnsServiceInfo mMdnsServiceInfo;
208
209 MdnsEvent(int clientId, @NonNull String requestedServiceType,
210 @NonNull MdnsServiceInfo mdnsServiceInfo) {
211 mClientId = clientId;
212 mRequestedServiceType = requestedServiceType;
213 mMdnsServiceInfo = mdnsServiceInfo;
214 }
215 }
216
Irfan Sheriff75006652012-04-17 23:15:29 -0700217 private class NsdStateMachine extends StateMachine {
218
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700219 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700220 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700221
222 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700223 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900224 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700225 }
226
Luke Huang92860f92021-06-23 06:29:30 +0000227 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800228 if (mIsDaemonStarted) {
229 if (DBG) Log.d(TAG, "Daemon is already started.");
230 return;
231 }
232 mMDnsManager.registerEventListener(mMDnsEventCallback);
233 mMDnsManager.startDaemon();
234 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000235 maybeScheduleStop();
236 }
237
paulhu2b9ed952022-02-10 21:58:32 +0800238 private void maybeStopDaemon() {
239 if (!mIsDaemonStarted) {
240 if (DBG) Log.d(TAG, "Daemon has not been started.");
241 return;
242 }
243 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
244 mMDnsManager.stopDaemon();
245 mIsDaemonStarted = false;
246 }
247
Luke Huang92860f92021-06-23 06:29:30 +0000248 private boolean isAnyRequestActive() {
249 return mIdToClientInfoMap.size() != 0;
250 }
251
252 private void scheduleStop() {
253 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
254 }
255 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800256 // The native daemon should stay alive and can't be cleanup
257 // if any legacy client connected.
258 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000259 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000260 }
261 }
262
Luke Huang92860f92021-06-23 06:29:30 +0000263 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000264 this.removeMessages(NsdManager.DAEMON_CLEANUP);
265 }
266
Paul Hu23fa2022023-01-13 22:57:24 +0800267 private void maybeStartMonitoringSockets() {
268 if (mIsMonitoringSocketsStarted) {
269 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
270 return;
271 }
272
273 mMdnsSocketProvider.startMonitoringSockets();
274 mIsMonitoringSocketsStarted = true;
275 }
276
277 private void maybeStopMonitoringSockets() {
278 if (!mIsMonitoringSocketsStarted) {
279 if (DBG) Log.d(TAG, "Socket monitoring has not been started.");
280 return;
281 }
282 mMdnsSocketProvider.stopMonitoringSockets();
283 mIsMonitoringSocketsStarted = false;
284 }
285
286 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
287 if (!isAnyRequestActive()) {
288 maybeStopMonitoringSockets();
289 }
290 }
291
Hugo Benichi803a2f02017-04-24 11:35:06 +0900292 NsdStateMachine(String name, Handler handler) {
293 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700294 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700295 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800296 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900297 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700298 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700299 }
300
301 class DefaultState extends State {
302 @Override
303 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900304 final ClientInfo cInfo;
305 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700306 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900307 case NsdManager.REGISTER_CLIENT:
308 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
309 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
310 final INsdManagerCallback cb = arg.second;
311 try {
312 cb.asBinder().linkToDeath(arg.first, 0);
313 cInfo = new ClientInfo(cb);
314 mClients.put(arg.first, cInfo);
315 } catch (RemoteException e) {
316 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700317 }
318 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900319 case NsdManager.UNREGISTER_CLIENT:
320 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
321 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800322 if (cInfo != null) {
Paul Hu23fa2022023-01-13 22:57:24 +0800323 if (mMdnsDiscoveryManager != null) {
324 cInfo.unregisterAllListeners();
325 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800326 cInfo.expungeAllRequests();
Luke Huangf7277ed2021-07-12 21:15:10 +0800327 if (cInfo.isLegacy()) {
328 mLegacyClientCount -= 1;
329 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800330 }
Paul Hu23fa2022023-01-13 22:57:24 +0800331 if (mMdnsDiscoveryManager != null) {
332 maybeStopMonitoringSocketsIfNoActiveRequest();
333 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800334 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700335 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700336 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900337 cInfo = getClientInfoForReply(msg);
338 if (cInfo != null) {
339 cInfo.onDiscoverServicesFailed(
340 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
341 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700342 break;
343 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900344 cInfo = getClientInfoForReply(msg);
345 if (cInfo != null) {
346 cInfo.onStopDiscoveryFailed(
347 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
348 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700349 break;
350 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900351 cInfo = getClientInfoForReply(msg);
352 if (cInfo != null) {
353 cInfo.onRegisterServiceFailed(
354 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
355 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700356 break;
357 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900358 cInfo = getClientInfoForReply(msg);
359 if (cInfo != null) {
360 cInfo.onUnregisterServiceFailed(
361 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
362 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700363 break;
364 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900365 cInfo = getClientInfoForReply(msg);
366 if (cInfo != null) {
367 cInfo.onResolveServiceFailed(
368 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
369 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700370 break;
Luke Huang05298582021-06-13 16:52:05 +0000371 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800372 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000373 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800374 // This event should be only sent by the legacy (target SDK < S) clients.
375 // Mark the sending client as legacy.
376 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900377 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800378 if (cInfo != null) {
379 cancelStop();
380 cInfo.setLegacy();
381 mLegacyClientCount += 1;
382 maybeStartDaemon();
383 }
384 break;
Paul Hu23fa2022023-01-13 22:57:24 +0800385 case NsdManager.MDNS_MONITORING_SOCKETS_CLEANUP:
386 maybeStopMonitoringSockets();
387 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700388 default:
paulhub2225702021-11-17 09:35:33 +0800389 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 return NOT_HANDLED;
391 }
392 return HANDLED;
393 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900394
395 private ClientInfo getClientInfoForReply(Message msg) {
396 final ListenerArgs args = (ListenerArgs) msg.obj;
397 return mClients.get(args.connector);
398 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700399 }
400
Irfan Sheriff75006652012-04-17 23:15:29 -0700401 class EnabledState extends State {
402 @Override
403 public void enter() {
404 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700405 }
406
407 @Override
408 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000409 // TODO: it is incorrect to stop the daemon without expunging all requests
410 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000411 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700412 }
413
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700414 private boolean requestLimitReached(ClientInfo clientInfo) {
415 if (clientInfo.mClientIds.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800416 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700417 return true;
418 }
419 return false;
420 }
421
Dave Plattfeff2af2014-03-07 14:48:22 -0800422 private void storeRequestMap(int clientId, int globalId, ClientInfo clientInfo, int what) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700423 clientInfo.mClientIds.put(clientId, globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -0800424 clientInfo.mClientRequests.put(clientId, what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700425 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000426 // Remove the cleanup event because here comes a new request.
427 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700428 }
429
430 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900431 clientInfo.mClientIds.delete(clientId);
432 clientInfo.mClientRequests.delete(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700433 mIdToClientInfoMap.remove(globalId);
Luke Huang05298582021-06-13 16:52:05 +0000434 maybeScheduleStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700435 }
436
Paul Hu23fa2022023-01-13 22:57:24 +0800437 private void storeListenerMap(int clientId, int transactionId, MdnsListener listener,
438 ClientInfo clientInfo) {
439 clientInfo.mClientIds.put(clientId, transactionId);
440 clientInfo.mListeners.put(clientId, listener);
441 mIdToClientInfoMap.put(transactionId, clientInfo);
442 removeMessages(NsdManager.MDNS_MONITORING_SOCKETS_CLEANUP);
443 }
444
445 private void removeListenerMap(int clientId, int transactionId, ClientInfo clientInfo) {
446 clientInfo.mClientIds.delete(clientId);
447 clientInfo.mListeners.delete(clientId);
448 mIdToClientInfoMap.remove(transactionId);
449 maybeStopMonitoringSocketsIfNoActiveRequest();
450 }
451
452 /**
453 * Check the given service type is valid and construct it to a service type
454 * which can use for discovery / resolution service.
455 *
456 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
457 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
458 * underscore; they are alphanumerical characters or dashes or underscore, except the
459 * last one that is just alphanumerical. The last label must be _tcp or _udp.
460 *
461 * @param serviceType the request service type for discovery / resolution service
462 * @return constructed service type or null if the given service type is invalid.
463 */
464 @Nullable
465 private String constructServiceType(String serviceType) {
466 if (TextUtils.isEmpty(serviceType)) return null;
467
468 final Pattern serviceTypePattern = Pattern.compile(
469 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
470 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
471 final Matcher matcher = serviceTypePattern.matcher(serviceType);
472 if (!matcher.matches()) return null;
473 return matcher.group(1) == null
474 ? serviceType + ".local"
475 : matcher.group(1) + "._sub" + matcher.group(2) + ".local";
476 }
477
Irfan Sheriff75006652012-04-17 23:15:29 -0700478 @Override
479 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900480 final ClientInfo clientInfo;
481 final int id;
482 final int clientId = msg.arg2;
483 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700484 switch (msg.what) {
Irfan Sheriff75006652012-04-17 23:15:29 -0700485 case NsdManager.DISCOVER_SERVICES:
paulhub2225702021-11-17 09:35:33 +0800486 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900487 args = (ListenerArgs) msg.obj;
488 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000489 // If the binder death notification for a INsdManagerCallback was received
490 // before any calls are received by NsdService, the clientInfo would be
491 // cleared and cause NPE. Add a null check here to prevent this corner case.
492 if (clientInfo == null) {
493 Log.e(TAG, "Unknown connector in discovery");
494 break;
495 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700496
497 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900498 clientInfo.onDiscoverServicesFailed(
499 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700500 break;
501 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700502
Paul Hu23fa2022023-01-13 22:57:24 +0800503 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700504 id = getUniqueId();
Paul Hu23fa2022023-01-13 22:57:24 +0800505 if (mMdnsDiscoveryManager != null) {
506 final String serviceType = constructServiceType(info.getServiceType());
507 if (serviceType == null) {
508 clientInfo.onDiscoverServicesFailed(clientId,
509 NsdManager.FAILURE_INTERNAL_ERROR);
510 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700511 }
Paul Hu23fa2022023-01-13 22:57:24 +0800512
513 maybeStartMonitoringSockets();
514 final MdnsListener listener =
515 new DiscoveryListener(clientId, id, info, serviceType);
516 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
517 .setNetwork(info.getNetwork())
518 .setIsPassiveMode(true)
519 .build();
520 mMdnsDiscoveryManager.registerListener(serviceType, listener, options);
521 storeListenerMap(clientId, id, listener, clientInfo);
522 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700523 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800524 maybeStartDaemon();
525 if (discoverServices(id, info)) {
526 if (DBG) {
527 Log.d(TAG, "Discover " + msg.arg2 + " " + id
528 + info.getServiceType());
529 }
530 storeRequestMap(clientId, id, clientInfo, msg.what);
531 clientInfo.onDiscoverServicesStarted(clientId, info);
532 } else {
533 stopServiceDiscovery(id);
534 clientInfo.onDiscoverServicesFailed(clientId,
535 NsdManager.FAILURE_INTERNAL_ERROR);
536 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700537 }
538 break;
539 case NsdManager.STOP_DISCOVERY:
paulhub2225702021-11-17 09:35:33 +0800540 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900541 args = (ListenerArgs) msg.obj;
542 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000543 // If the binder death notification for a INsdManagerCallback was received
544 // before any calls are received by NsdService, the clientInfo would be
545 // cleared and cause NPE. Add a null check here to prevent this corner case.
546 if (clientInfo == null) {
547 Log.e(TAG, "Unknown connector in stop discovery");
548 break;
549 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700550
551 try {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900552 id = clientInfo.mClientIds.get(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700553 } catch (NullPointerException e) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900554 clientInfo.onStopDiscoveryFailed(
555 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700556 break;
557 }
Paul Hu23fa2022023-01-13 22:57:24 +0800558 if (mMdnsDiscoveryManager != null) {
559 final MdnsListener listener = clientInfo.mListeners.get(clientId);
560 if (listener == null) {
561 clientInfo.onStopDiscoveryFailed(
562 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
563 break;
564 }
565 mMdnsDiscoveryManager.unregisterListener(
566 listener.getListenedServiceType(), listener);
567 removeListenerMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900568 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700569 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800570 removeRequestMap(clientId, id, clientInfo);
571 if (stopServiceDiscovery(id)) {
572 clientInfo.onStopDiscoverySucceeded(clientId);
573 } else {
574 clientInfo.onStopDiscoveryFailed(
575 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
576 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700577 }
578 break;
579 case NsdManager.REGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800580 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900581 args = (ListenerArgs) msg.obj;
582 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000583 // If the binder death notification for a INsdManagerCallback was received
584 // before any calls are received by NsdService, the clientInfo would be
585 // cleared and cause NPE. Add a null check here to prevent this corner case.
586 if (clientInfo == null) {
587 Log.e(TAG, "Unknown connector in registration");
588 break;
589 }
590
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700591 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900592 clientInfo.onRegisterServiceFailed(
593 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700594 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700595 }
596
Luke Huang05298582021-06-13 16:52:05 +0000597 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700598 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900599 if (registerService(id, args.serviceInfo)) {
paulhub2225702021-11-17 09:35:33 +0800600 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900601 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700602 // Return success after mDns reports success
Irfan Sheriff75006652012-04-17 23:15:29 -0700603 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700604 unregisterService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900605 clientInfo.onRegisterServiceFailed(
606 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700607 }
608 break;
609 case NsdManager.UNREGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800610 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900611 args = (ListenerArgs) msg.obj;
612 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000613 // If the binder death notification for a INsdManagerCallback was received
614 // before any calls are received by NsdService, the clientInfo would be
615 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900616 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800617 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700618 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700619 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 id = clientInfo.mClientIds.get(clientId);
621 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700622 if (unregisterService(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900623 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700624 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900625 clientInfo.onUnregisterServiceFailed(
626 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700627 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700628 break;
629 case NsdManager.RESOLVE_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800630 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900631 args = (ListenerArgs) msg.obj;
632 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000633 // If the binder death notification for a INsdManagerCallback was received
634 // before any calls are received by NsdService, the clientInfo would be
635 // cleared and cause NPE. Add a null check here to prevent this corner case.
636 if (clientInfo == null) {
637 Log.e(TAG, "Unknown connector in resolution");
638 break;
639 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700640
641 if (clientInfo.mResolvedService != null) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900642 clientInfo.onResolveServiceFailed(
643 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 break;
645 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700646
Luke Huang05298582021-06-13 16:52:05 +0000647 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700648 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900649 if (resolveService(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700650 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900651 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700652 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900653 clientInfo.onResolveServiceFailed(
654 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700655 }
656 break;
paulhu2b9ed952022-02-10 21:58:32 +0800657 case MDNS_SERVICE_EVENT:
658 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900659 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700660 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700661 break;
Paul Hu019621e2023-01-13 23:26:49 +0800662 case MDNS_DISCOVERY_MANAGER_EVENT:
663 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
664 return NOT_HANDLED;
665 }
666 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900668 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900670 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700671 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700672
paulhu2b9ed952022-02-10 21:58:32 +0800673 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700674 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700675 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
676 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800677 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900678 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700679 }
680
681 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700682 int clientId = clientInfo.getClientId(id);
683 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700684 // This can happen because of race conditions. For example,
685 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
686 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800687 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
688 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900689 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700690 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900691 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800692 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900693 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700694 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800695 case IMDnsEventListener.SERVICE_FOUND: {
696 final DiscoveryInfo info = (DiscoveryInfo) obj;
697 final String name = info.serviceName;
698 final String type = info.registrationType;
699 servInfo = new NsdServiceInfo(name, type);
700 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900701 if (foundNetId == 0L) {
702 // Ignore services that do not have a Network: they are not usable
703 // by apps, as they would need privileged permissions to use
704 // interfaces that do not have an associated Network.
705 break;
706 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900707 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900708 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700709 break;
paulhu2b9ed952022-02-10 21:58:32 +0800710 }
711 case IMDnsEventListener.SERVICE_LOST: {
712 final DiscoveryInfo info = (DiscoveryInfo) obj;
713 final String name = info.serviceName;
714 final String type = info.registrationType;
715 final int lostNetId = info.netId;
716 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900717 // The network could be set to null (netId 0) if it was torn down when the
718 // service is lost
719 // TODO: avoid returning null in that case, possibly by remembering
720 // found services on the same interface index and their network at the time
721 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900722 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700723 break;
paulhu2b9ed952022-02-10 21:58:32 +0800724 }
725 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900726 clientInfo.onDiscoverServicesFailed(
727 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700728 break;
paulhu2b9ed952022-02-10 21:58:32 +0800729 case IMDnsEventListener.SERVICE_REGISTERED: {
730 final RegistrationInfo info = (RegistrationInfo) obj;
731 final String name = info.serviceName;
732 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900733 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700734 break;
paulhu2b9ed952022-02-10 21:58:32 +0800735 }
736 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900737 clientInfo.onRegisterServiceFailed(
738 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700739 break;
paulhu2b9ed952022-02-10 21:58:32 +0800740 case IMDnsEventListener.SERVICE_RESOLVED: {
741 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700742 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800743 final String fullName = info.serviceFullName;
744 while (index < fullName.length() && fullName.charAt(index) != '.') {
745 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700746 ++index;
747 }
748 ++index;
749 }
paulhu2b9ed952022-02-10 21:58:32 +0800750 if (index >= fullName.length()) {
751 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700752 break;
753 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900754
paulhube186602022-04-12 07:18:23 +0000755 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800756 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700757 String type = rest.replace(".local.", "");
758
759 clientInfo.mResolvedService.setServiceName(name);
760 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800761 clientInfo.mResolvedService.setPort(info.port);
762 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900763 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700764
765 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800766 removeRequestMap(clientId, id, clientInfo);
767
paulhu2b9ed952022-02-10 21:58:32 +0800768 final int id2 = getUniqueId();
769 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800770 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800771 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900772 clientInfo.onResolveServiceFailed(
773 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700774 clientInfo.mResolvedService = null;
775 }
776 break;
paulhu2b9ed952022-02-10 21:58:32 +0800777 }
778 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700779 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700780 stopResolveService(id);
781 removeRequestMap(clientId, id, clientInfo);
782 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900783 clientInfo.onResolveServiceFailed(
784 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700785 break;
paulhu2b9ed952022-02-10 21:58:32 +0800786 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700787 /* NNN resolveId errorCode */
788 stopGetAddrInfo(id);
789 removeRequestMap(clientId, id, clientInfo);
790 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900791 clientInfo.onResolveServiceFailed(
792 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700793 break;
paulhu2b9ed952022-02-10 21:58:32 +0800794 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900795 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800796 final GetAddressInfo info = (GetAddressInfo) obj;
797 final String address = info.address;
798 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900799 InetAddress serviceHost = null;
800 try {
paulhu2b9ed952022-02-10 21:58:32 +0800801 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900802 } catch (UnknownHostException e) {
803 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
804 }
805
806 // If the resolved service is on an interface without a network, consider it
807 // as a failure: it would not be usable by apps as they would need
808 // privileged permissions.
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900809 if (netId != NETID_UNSET && serviceHost != null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900810 clientInfo.mResolvedService.setHost(serviceHost);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900811 setServiceNetworkForCallback(clientInfo.mResolvedService,
812 netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900813 clientInfo.onResolveServiceSucceeded(
814 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900815 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900816 clientInfo.onResolveServiceFailed(
817 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700818 }
819 stopGetAddrInfo(id);
820 removeRequestMap(clientId, id, clientInfo);
821 clientInfo.mResolvedService = null;
822 break;
paulhu2b9ed952022-02-10 21:58:32 +0800823 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700824 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900825 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700826 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900827 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700828 }
Paul Hu019621e2023-01-13 23:26:49 +0800829
830 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
831 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
832 final String serviceType = event.mRequestedServiceType;
833 final String serviceName = serviceInfo.getServiceInstanceName();
834 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
835 final Network network = serviceInfo.getNetwork();
836 setServiceNetworkForCallback(
837 servInfo,
838 network == null ? NETID_UNSET : network.netId,
839 serviceInfo.getInterfaceIndex());
840 return servInfo;
841 }
842
843 private boolean handleMdnsDiscoveryManagerEvent(
844 int transactionId, int code, Object obj) {
845 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
846 if (clientInfo == null) {
847 Log.e(TAG, String.format(
848 "id %d for %d has no client mapping", transactionId, code));
849 return false;
850 }
851
852 final MdnsEvent event = (MdnsEvent) obj;
853 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +0800854 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +0800855 if (DBG) {
856 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
857 NsdManager.nameOf(code), transactionId));
858 }
859 switch (code) {
860 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +0800861 clientInfo.onServiceFound(clientId, info);
862 break;
863 case NsdManager.SERVICE_LOST:
864 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +0800865 break;
866 default:
867 return false;
868 }
869 return true;
870 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700871 }
872 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700873
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900874 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
875 switch (netId) {
876 case NETID_UNSET:
877 info.setNetwork(null);
878 break;
879 case INetd.LOCAL_NET_ID:
880 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
881 // visible / usable for apps, so do not return it. Store the interface
882 // index instead, so at least if the client tries to resolve the service
883 // with that NsdServiceInfo, it will be done on the same interface.
884 // If they recreate the NsdServiceInfo themselves, resolution would be
885 // done on all interfaces as before T, which should also work.
886 info.setNetwork(null);
887 info.setInterfaceIndex(ifaceIdx);
888 break;
889 default:
890 info.setNetwork(new Network(netId));
891 }
892 }
893
paulhube186602022-04-12 07:18:23 +0000894 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
895 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
896 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
897 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
898 private String unescape(String s) {
899 StringBuilder sb = new StringBuilder(s.length());
900 for (int i = 0; i < s.length(); ++i) {
901 char c = s.charAt(i);
902 if (c == '\\') {
903 if (++i >= s.length()) {
904 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
905 break;
906 }
907 c = s.charAt(i);
908 if (c != '.' && c != '\\') {
909 if (i + 2 >= s.length()) {
910 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
911 break;
912 }
913 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
914 + (s.charAt(i + 2) - '0'));
915 i += 2;
916 }
917 }
918 sb.append(c);
919 }
920 return sb.toString();
921 }
922
Hugo Benichi803a2f02017-04-24 11:35:06 +0900923 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +0800924 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +0800925 this(ctx, handler, cleanupDelayMs, new Dependencies());
926 }
927
928 @VisibleForTesting
929 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +0000930 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900931 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900932 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700933 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +0800934 mMDnsManager = ctx.getSystemService(MDnsManager.class);
935 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Paul Hu4bd98ef2023-01-12 13:42:07 +0800936 if (deps.isMdnsDiscoveryManagerEnabled(ctx)) {
937 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
938 mMdnsSocketClient =
939 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
940 mMdnsDiscoveryManager =
941 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
942 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
943 } else {
944 mMdnsSocketProvider = null;
945 mMdnsSocketClient = null;
946 mMdnsDiscoveryManager = null;
947 }
948 }
949
950 /**
951 * Dependencies of NsdService, for injection in tests.
952 */
953 @VisibleForTesting
954 public static class Dependencies {
955 /**
956 * Check whether or not MdnsDiscoveryManager feature is enabled.
957 *
958 * @param context The global context information about an app environment.
959 * @return true if MdnsDiscoveryManager feature is enabled.
960 */
961 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
962 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
963 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
964 }
965
966 /**
967 * @see MdnsDiscoveryManager
968 */
969 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
970 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
971 return new MdnsDiscoveryManager(executorProvider, socketClient);
972 }
973
974 /**
975 * @see MdnsSocketProvider
976 */
977 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
978 return new MdnsSocketProvider(context, looper);
979 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700980 }
981
paulhu1b35e822022-04-08 14:48:41 +0800982 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900983 HandlerThread thread = new HandlerThread(TAG);
984 thread.start();
985 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +0800986 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700987 return service;
988 }
989
paulhu2b9ed952022-02-10 21:58:32 +0800990 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
991 private final StateMachine mStateMachine;
992
993 MDnsEventCallback(StateMachine sm) {
994 mStateMachine = sm;
995 }
996
997 @Override
998 public void onServiceRegistrationStatus(final RegistrationInfo status) {
999 mStateMachine.sendMessage(
1000 MDNS_SERVICE_EVENT, status.result, status.id, status);
1001 }
1002
1003 @Override
1004 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1005 mStateMachine.sendMessage(
1006 MDNS_SERVICE_EVENT, status.result, status.id, status);
1007 }
1008
1009 @Override
1010 public void onServiceResolutionStatus(final ResolutionInfo status) {
1011 mStateMachine.sendMessage(
1012 MDNS_SERVICE_EVENT, status.result, status.id, status);
1013 }
1014
1015 @Override
1016 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1017 mStateMachine.sendMessage(
1018 MDNS_SERVICE_EVENT, status.result, status.id, status);
1019 }
1020
1021 @Override
1022 public int getInterfaceVersion() throws RemoteException {
1023 return this.VERSION;
1024 }
1025
1026 @Override
1027 public String getInterfaceHash() throws RemoteException {
1028 return this.HASH;
1029 }
1030 }
1031
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001032 @Override
1033 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001035 final INsdServiceConnector connector = new NsdServiceConnector();
1036 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1037 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1038 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001039 }
1040
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001041 private static class ListenerArgs {
1042 public final NsdServiceConnector connector;
1043 public final NsdServiceInfo serviceInfo;
1044 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1045 this.connector = connector;
1046 this.serviceInfo = serviceInfo;
1047 }
1048 }
1049
1050 private class NsdServiceConnector extends INsdServiceConnector.Stub
1051 implements IBinder.DeathRecipient {
1052 @Override
1053 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1054 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1055 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1056 new ListenerArgs(this, serviceInfo)));
1057 }
1058
1059 @Override
1060 public void unregisterService(int listenerKey) {
1061 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1062 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1063 new ListenerArgs(this, null)));
1064 }
1065
1066 @Override
1067 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1068 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1069 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1070 new ListenerArgs(this, serviceInfo)));
1071 }
1072
1073 @Override
1074 public void stopDiscovery(int listenerKey) {
1075 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1076 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1077 }
1078
1079 @Override
1080 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1081 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1082 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1083 new ListenerArgs(this, serviceInfo)));
1084 }
1085
1086 @Override
1087 public void startDaemon() {
1088 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1089 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1090 }
1091
1092 @Override
1093 public void binderDied() {
1094 mNsdStateMachine.sendMessage(
1095 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1096 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001097 }
1098
Hugo Benichi912db992017-04-24 16:41:03 +09001099 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001100 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001101 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001102 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1103 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001104 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001105 }
1106
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001107 private int getUniqueId() {
1108 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1109 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001110 }
1111
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001112 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001113 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001114 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001115 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001116 String name = service.getServiceName();
1117 String type = service.getServiceType();
1118 int port = service.getPort();
1119 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001120 final int registerInterface = getNetworkInterfaceIndex(service);
1121 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001122 Log.e(TAG, "Interface to register service on not found");
1123 return false;
1124 }
1125 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001126 }
1127
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001128 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001129 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001130 }
1131
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001132 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001133 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001134 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1135 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001136 Log.e(TAG, "Interface to discover service on not found");
1137 return false;
1138 }
paulhu2b9ed952022-02-10 21:58:32 +08001139 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001140 }
1141
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001142 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001143 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001144 }
1145
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001146 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001147 final String name = service.getServiceName();
1148 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001149 final int resolveInterface = getNetworkInterfaceIndex(service);
1150 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001151 Log.e(TAG, "Interface to resolve service on not found");
1152 return false;
1153 }
paulhu2b9ed952022-02-10 21:58:32 +08001154 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001155 }
1156
1157 /**
1158 * Guess the interface to use to resolve or discover a service on a specific network.
1159 *
1160 * This is an imperfect guess, as for example the network may be gone or not yet fully
1161 * registered. This is fine as failing is correct if the network is gone, and a client
1162 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1163 * this is to support the legacy mdnsresponder implementation, which historically resolved
1164 * services on an unspecified network.
1165 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001166 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1167 final Network network = serviceInfo.getNetwork();
1168 if (network == null) {
1169 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1170 // provided by NsdService from discovery results, and the service was found on an
1171 // interface that has no app-usable Network).
1172 if (serviceInfo.getInterfaceIndex() != 0) {
1173 return serviceInfo.getInterfaceIndex();
1174 }
1175 return IFACE_IDX_ANY;
1176 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001177
1178 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1179 if (cm == null) {
1180 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1181 return IFACE_IDX_ANY;
1182 }
1183 final LinkProperties lp = cm.getLinkProperties(network);
1184 if (lp == null) return IFACE_IDX_ANY;
1185
1186 // Only resolve on non-stacked interfaces
1187 final NetworkInterface iface;
1188 try {
1189 iface = NetworkInterface.getByName(lp.getInterfaceName());
1190 } catch (SocketException e) {
1191 Log.e(TAG, "Error querying interface", e);
1192 return IFACE_IDX_ANY;
1193 }
1194
1195 if (iface == null) {
1196 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1197 return IFACE_IDX_ANY;
1198 }
1199
1200 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001201 }
1202
1203 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001204 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001205 }
1206
paulhu2b9ed952022-02-10 21:58:32 +08001207 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1208 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001209 }
1210
1211 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001212 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001213 }
1214
1215 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001216 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001217 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001218
Irfan Sheriff75006652012-04-17 23:15:29 -07001219 for (ClientInfo client : mClients.values()) {
1220 pw.println("Client Info");
1221 pw.println(client);
1222 }
1223
1224 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001225 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001226
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001227 /* Information tracked per client */
1228 private class ClientInfo {
1229
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001230 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001231 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001232 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001233 private NsdServiceInfo mResolvedService;
1234
1235 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001236 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001237
Dave Plattfeff2af2014-03-07 14:48:22 -08001238 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +09001239 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -08001240
Paul Hu23fa2022023-01-13 22:57:24 +08001241 /* A map from client id to the MdnsListener */
1242 private final SparseArray<MdnsListener> mListeners = new SparseArray<>();
1243
Luke Huangf7277ed2021-07-12 21:15:10 +08001244 // The target SDK of this client < Build.VERSION_CODES.S
1245 private boolean mIsLegacy = false;
1246
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001247 private ClientInfo(INsdManagerCallback cb) {
1248 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001249 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001250 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001251
1252 @Override
1253 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001254 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001255 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +08001256 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001257 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001258 int clientID = mClientIds.keyAt(i);
1259 sb.append("clientId ").append(clientID).
1260 append(" mDnsId ").append(mClientIds.valueAt(i)).
1261 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001262 }
1263 return sb.toString();
1264 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001265
Luke Huangf7277ed2021-07-12 21:15:10 +08001266 private boolean isLegacy() {
1267 return mIsLegacy;
1268 }
1269
1270 private void setLegacy() {
1271 mIsLegacy = true;
1272 }
1273
Dave Plattfeff2af2014-03-07 14:48:22 -08001274 // Remove any pending requests from the global map when we get rid of a client,
1275 // and send cancellations to the daemon.
1276 private void expungeAllRequests() {
1277 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +09001278 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -08001279 for (i = 0; i < mClientIds.size(); i++) {
1280 clientId = mClientIds.keyAt(i);
1281 globalId = mClientIds.valueAt(i);
1282 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001283 if (DBG) {
1284 Log.d(TAG, "Terminating client-ID " + clientId
1285 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1286 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001287 switch (mClientRequests.get(clientId)) {
1288 case NsdManager.DISCOVER_SERVICES:
1289 stopServiceDiscovery(globalId);
1290 break;
1291 case NsdManager.RESOLVE_SERVICE:
1292 stopResolveService(globalId);
1293 break;
1294 case NsdManager.REGISTER_SERVICE:
1295 unregisterService(globalId);
1296 break;
1297 default:
1298 break;
1299 }
1300 }
1301 mClientIds.clear();
1302 mClientRequests.clear();
1303 }
1304
Paul Hu23fa2022023-01-13 22:57:24 +08001305 void unregisterAllListeners() {
1306 for (int i = 0; i < mListeners.size(); i++) {
1307 final MdnsListener listener = mListeners.valueAt(i);
1308 mMdnsDiscoveryManager.unregisterListener(
1309 listener.getListenedServiceType(), listener);
1310 }
1311 mListeners.clear();
1312 }
1313
Christopher Lane74411222014-04-25 18:39:07 -07001314 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
1315 // return the corresponding listener id. mDnsClient id is also called a global id.
1316 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001317 int idx = mClientIds.indexOfValue(globalId);
1318 if (idx < 0) {
1319 return idx;
Christopher Lane74411222014-04-25 18:39:07 -07001320 }
Hugo Benichid2552ae2017-04-11 14:42:47 +09001321 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -07001322 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001323
1324 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1325 try {
1326 mCb.onDiscoverServicesStarted(listenerKey, info);
1327 } catch (RemoteException e) {
1328 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1329 }
1330 }
1331
1332 void onDiscoverServicesFailed(int listenerKey, int error) {
1333 try {
1334 mCb.onDiscoverServicesFailed(listenerKey, error);
1335 } catch (RemoteException e) {
1336 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1337 }
1338 }
1339
1340 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1341 try {
1342 mCb.onServiceFound(listenerKey, info);
1343 } catch (RemoteException e) {
1344 Log.e(TAG, "Error calling onServiceFound(", e);
1345 }
1346 }
1347
1348 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1349 try {
1350 mCb.onServiceLost(listenerKey, info);
1351 } catch (RemoteException e) {
1352 Log.e(TAG, "Error calling onServiceLost(", e);
1353 }
1354 }
1355
1356 void onStopDiscoveryFailed(int listenerKey, int error) {
1357 try {
1358 mCb.onStopDiscoveryFailed(listenerKey, error);
1359 } catch (RemoteException e) {
1360 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1361 }
1362 }
1363
1364 void onStopDiscoverySucceeded(int listenerKey) {
1365 try {
1366 mCb.onStopDiscoverySucceeded(listenerKey);
1367 } catch (RemoteException e) {
1368 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1369 }
1370 }
1371
1372 void onRegisterServiceFailed(int listenerKey, int error) {
1373 try {
1374 mCb.onRegisterServiceFailed(listenerKey, error);
1375 } catch (RemoteException e) {
1376 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1377 }
1378 }
1379
1380 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1381 try {
1382 mCb.onRegisterServiceSucceeded(listenerKey, info);
1383 } catch (RemoteException e) {
1384 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1385 }
1386 }
1387
1388 void onUnregisterServiceFailed(int listenerKey, int error) {
1389 try {
1390 mCb.onUnregisterServiceFailed(listenerKey, error);
1391 } catch (RemoteException e) {
1392 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1393 }
1394 }
1395
1396 void onUnregisterServiceSucceeded(int listenerKey) {
1397 try {
1398 mCb.onUnregisterServiceSucceeded(listenerKey);
1399 } catch (RemoteException e) {
1400 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1401 }
1402 }
1403
1404 void onResolveServiceFailed(int listenerKey, int error) {
1405 try {
1406 mCb.onResolveServiceFailed(listenerKey, error);
1407 } catch (RemoteException e) {
1408 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1409 }
1410 }
1411
1412 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1413 try {
1414 mCb.onResolveServiceSucceeded(listenerKey, info);
1415 } catch (RemoteException e) {
1416 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1417 }
1418 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001419 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001420}