blob: 37c2c33efac1a3756a8154b38e14493032cbe750 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Paul Hu23fa2022023-01-13 22:57:24 +080025import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080026import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080027import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070028import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090029import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090030import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080031import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090032import android.net.LinkProperties;
33import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080034import android.net.mdns.aidl.DiscoveryInfo;
35import android.net.mdns.aidl.GetAddressInfo;
36import android.net.mdns.aidl.IMDnsEventListener;
37import android.net.mdns.aidl.RegistrationInfo;
38import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070039import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090040import android.net.nsd.INsdManagerCallback;
41import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080042import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070043import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080044import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090045import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080046import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090047import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080048import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070049import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090050import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070051import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080052import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.util.Log;
54import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070055import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070056
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.util.State;
59import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080060import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080061import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080062import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090063import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080064import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
65import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080066import com.android.server.connectivity.mdns.MdnsSearchOptions;
67import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
68import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.MdnsSocketClientBase;
70import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080071
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070074import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090075import java.net.NetworkInterface;
76import java.net.SocketException;
77import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090078import java.nio.ByteBuffer;
79import java.nio.CharBuffer;
80import java.nio.charset.Charset;
81import java.nio.charset.CharsetEncoder;
82import java.nio.charset.StandardCharsets;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070083import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080084import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080085import java.util.Map;
Paul Hu18aeccc2022-12-27 08:48:48 +000086import java.util.Objects;
Paul Hu23fa2022023-01-13 22:57:24 +080087import java.util.regex.Matcher;
88import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089
Irfan Sheriff77ec5582012-03-22 17:01:39 -070090/**
91 * Network Service Discovery Service handles remote service discovery operation requests by
92 * implementing the INsdManager interface.
93 *
94 * @hide
95 */
96public class NsdService extends INsdManager.Stub {
97 private static final String TAG = "NsdService";
98 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090099 /**
100 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
101 * implementation.
102 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800103 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800104 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900105 // Max label length as per RFC 1034/1035
106 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700107
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900108 /**
109 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
110 * implementation.
111 */
112 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
113
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900114 /**
115 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
116 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
117 *
118 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
119 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
120 *
121 * In which case the flags:
122 * "mdns_discovery_manager_allowlist_mytype_version",
123 * "mdns_advertiser_allowlist_mytype_version",
124 * "mdns_discovery_manager_allowlist_othertype_version",
125 * "mdns_advertiser_allowlist_othertype_version"
126 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
127 * be read with
128 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
129 *
130 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
131 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
132 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
133 */
134 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
135
136 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
137 "mdns_discovery_manager_allowlist_";
138 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
139 "mdns_advertiser_allowlist_";
140 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
141
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900142 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000143 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900144 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700145
Hugo Benichi32be63d2017-04-05 14:06:11 +0900146 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800148 private final MDnsManager mMDnsManager;
149 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900150 @NonNull
151 private final Dependencies mDeps;
152 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800153 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900154 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800155 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900156 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800157 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900158 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900159 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800160 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800161 // state machine thread. If change this outside state machine, it will need to introduce
162 // synchronization.
163 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800164 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700165
166 /**
167 * Clients receiving asynchronous messages
168 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900169 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700170
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700171 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900172 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700173
Luke Huang05298582021-06-13 16:52:05 +0000174 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700175
Hugo Benichi32be63d2017-04-05 14:06:11 +0900176 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700177 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800178 // The count of the connected legacy clients.
179 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700180
Paul Hu23fa2022023-01-13 22:57:24 +0800181 private static class MdnsListener implements MdnsServiceBrowserListener {
182 protected final int mClientId;
183 protected final int mTransactionId;
184 @NonNull
185 protected final NsdServiceInfo mReqServiceInfo;
186 @NonNull
187 protected final String mListenedServiceType;
188
189 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
190 @NonNull String listenedServiceType) {
191 mClientId = clientId;
192 mTransactionId = transactionId;
193 mReqServiceInfo = reqServiceInfo;
194 mListenedServiceType = listenedServiceType;
195 }
196
197 @NonNull
198 public String getListenedServiceType() {
199 return mListenedServiceType;
200 }
201
202 @Override
203 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
204
205 @Override
206 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
207
208 @Override
209 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
210
211 @Override
212 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
213
214 @Override
215 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
216
217 @Override
218 public void onSearchStoppedWithError(int error) { }
219
220 @Override
221 public void onSearchFailedToStart() { }
222
223 @Override
224 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
225
226 @Override
227 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
228 }
229
230 private class DiscoveryListener extends MdnsListener {
231
232 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
233 @NonNull String listenServiceType) {
234 super(clientId, transactionId, reqServiceInfo, listenServiceType);
235 }
236
237 @Override
238 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800239 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
240 NsdManager.SERVICE_FOUND,
241 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800242 }
243
244 @Override
245 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800246 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
247 NsdManager.SERVICE_LOST,
248 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800249 }
250 }
251
Paul Hu75069ed2023-01-14 00:31:09 +0800252 private class ResolutionListener extends MdnsListener {
253
254 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
255 @NonNull String listenServiceType) {
256 super(clientId, transactionId, reqServiceInfo, listenServiceType);
257 }
258
259 @Override
260 public void onServiceFound(MdnsServiceInfo serviceInfo) {
261 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
262 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
263 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
264 }
265 }
266
Paul Hu019621e2023-01-13 23:26:49 +0800267 /**
268 * Data class of mdns service callback information.
269 */
270 private static class MdnsEvent {
271 final int mClientId;
272 @NonNull
273 final String mRequestedServiceType;
274 @NonNull
275 final MdnsServiceInfo mMdnsServiceInfo;
276
277 MdnsEvent(int clientId, @NonNull String requestedServiceType,
278 @NonNull MdnsServiceInfo mdnsServiceInfo) {
279 mClientId = clientId;
280 mRequestedServiceType = requestedServiceType;
281 mMdnsServiceInfo = mdnsServiceInfo;
282 }
283 }
284
Irfan Sheriff75006652012-04-17 23:15:29 -0700285 private class NsdStateMachine extends StateMachine {
286
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700287 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700288 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700289
290 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700291 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900292 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700293 }
294
Luke Huang92860f92021-06-23 06:29:30 +0000295 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800296 if (mIsDaemonStarted) {
297 if (DBG) Log.d(TAG, "Daemon is already started.");
298 return;
299 }
300 mMDnsManager.registerEventListener(mMDnsEventCallback);
301 mMDnsManager.startDaemon();
302 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000303 maybeScheduleStop();
304 }
305
paulhu2b9ed952022-02-10 21:58:32 +0800306 private void maybeStopDaemon() {
307 if (!mIsDaemonStarted) {
308 if (DBG) Log.d(TAG, "Daemon has not been started.");
309 return;
310 }
311 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
312 mMDnsManager.stopDaemon();
313 mIsDaemonStarted = false;
314 }
315
Luke Huang92860f92021-06-23 06:29:30 +0000316 private boolean isAnyRequestActive() {
317 return mIdToClientInfoMap.size() != 0;
318 }
319
320 private void scheduleStop() {
321 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
322 }
323 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800324 // The native daemon should stay alive and can't be cleanup
325 // if any legacy client connected.
326 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000327 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000328 }
329 }
330
Luke Huang92860f92021-06-23 06:29:30 +0000331 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000332 this.removeMessages(NsdManager.DAEMON_CLEANUP);
333 }
334
Paul Hu23fa2022023-01-13 22:57:24 +0800335 private void maybeStartMonitoringSockets() {
336 if (mIsMonitoringSocketsStarted) {
337 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
338 return;
339 }
340
341 mMdnsSocketProvider.startMonitoringSockets();
342 mIsMonitoringSocketsStarted = true;
343 }
344
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900345 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
346 if (!mIsMonitoringSocketsStarted) return;
347 if (isAnyRequestActive()) return;
348
Paul Hu58f20602023-02-18 11:41:07 +0800349 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800350 mIsMonitoringSocketsStarted = false;
351 }
352
Hugo Benichi803a2f02017-04-24 11:35:06 +0900353 NsdStateMachine(String name, Handler handler) {
354 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700355 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700356 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800357 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900358 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700359 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700360 }
361
362 class DefaultState extends State {
363 @Override
364 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900365 final ClientInfo cInfo;
366 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700367 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900368 case NsdManager.REGISTER_CLIENT:
369 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
370 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
371 final INsdManagerCallback cb = arg.second;
372 try {
373 cb.asBinder().linkToDeath(arg.first, 0);
374 cInfo = new ClientInfo(cb);
375 mClients.put(arg.first, cInfo);
376 } catch (RemoteException e) {
377 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700378 }
379 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900380 case NsdManager.UNREGISTER_CLIENT:
381 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
382 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800383 if (cInfo != null) {
384 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900385 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800386 mLegacyClientCount -= 1;
387 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800388 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900389 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800390 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700391 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700392 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900393 cInfo = getClientInfoForReply(msg);
394 if (cInfo != null) {
395 cInfo.onDiscoverServicesFailed(
396 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
397 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700398 break;
399 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900400 cInfo = getClientInfoForReply(msg);
401 if (cInfo != null) {
402 cInfo.onStopDiscoveryFailed(
403 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
404 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700405 break;
406 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900407 cInfo = getClientInfoForReply(msg);
408 if (cInfo != null) {
409 cInfo.onRegisterServiceFailed(
410 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
411 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700412 break;
413 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900414 cInfo = getClientInfoForReply(msg);
415 if (cInfo != null) {
416 cInfo.onUnregisterServiceFailed(
417 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
418 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700419 break;
420 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900421 cInfo = getClientInfoForReply(msg);
422 if (cInfo != null) {
423 cInfo.onResolveServiceFailed(
424 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
425 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 break;
Paul Hub58deb72022-12-26 09:24:42 +0000427 case NsdManager.STOP_RESOLUTION:
428 cInfo = getClientInfoForReply(msg);
429 if (cInfo != null) {
430 cInfo.onStopResolutionFailed(
431 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
432 }
433 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000434 case NsdManager.REGISTER_SERVICE_CALLBACK:
435 cInfo = getClientInfoForReply(msg);
436 if (cInfo != null) {
437 cInfo.onServiceInfoCallbackRegistrationFailed(
438 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
439 }
440 break;
Luke Huang05298582021-06-13 16:52:05 +0000441 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800442 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000443 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800444 // This event should be only sent by the legacy (target SDK < S) clients.
445 // Mark the sending client as legacy.
446 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900447 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800448 if (cInfo != null) {
449 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900450 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800451 mLegacyClientCount += 1;
452 maybeStartDaemon();
453 }
454 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700455 default:
paulhub2225702021-11-17 09:35:33 +0800456 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700457 return NOT_HANDLED;
458 }
459 return HANDLED;
460 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900461
462 private ClientInfo getClientInfoForReply(Message msg) {
463 final ListenerArgs args = (ListenerArgs) msg.obj;
464 return mClients.get(args.connector);
465 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700466 }
467
Irfan Sheriff75006652012-04-17 23:15:29 -0700468 class EnabledState extends State {
469 @Override
470 public void enter() {
471 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700472 }
473
474 @Override
475 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000476 // TODO: it is incorrect to stop the daemon without expunging all requests
477 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000478 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700479 }
480
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700481 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900482 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800483 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700484 return true;
485 }
486 return false;
487 }
488
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900489 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
490 int what) {
491 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700492 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000493 // Remove the cleanup event because here comes a new request.
494 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700495 }
496
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900497 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800498 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900499 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
500 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800501 }
502
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900503 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
504 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
505 if (existing == null) return;
506 clientInfo.mClientRequests.remove(clientId);
507 mIdToClientInfoMap.remove(globalId);
508
509 if (existing instanceof LegacyClientRequest) {
510 maybeScheduleStop();
511 } else {
512 maybeStopMonitoringSocketsIfNoActiveRequest();
513 }
514 }
515
516 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
517 MdnsListener listener, ClientInfo clientInfo) {
518 clientInfo.mClientRequests.put(clientId,
519 new DiscoveryManagerRequest(globalId, listener));
520 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800521 }
522
Paul Hu18aeccc2022-12-27 08:48:48 +0000523 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
524 clientInfo.mRegisteredService = null;
525 clientInfo.mClientIdForServiceUpdates = 0;
526 }
527
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900528
529 /**
530 * Truncate a service name to up to 63 UTF-8 bytes.
531 *
532 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
533 * names used in registerService follows historical behavior (see mdnsresponder
534 * handle_regservice_request).
535 */
536 @NonNull
537 private String truncateServiceName(@NonNull String originalName) {
538 // UTF-8 is at most 4 bytes per character; return early in the common case where
539 // the name can't possibly be over the limit given its string length.
540 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
541
542 final Charset utf8 = StandardCharsets.UTF_8;
543 final CharsetEncoder encoder = utf8.newEncoder();
544 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
545 // encode will write as many characters as possible to the out buffer, and just
546 // return an overflow code if there were too many characters (no need to check the
547 // return code here, this method truncates the name on purpose).
548 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
549 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800550 }
551
Paul Hue4f5f252023-02-16 21:13:47 +0800552 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
553 ClientInfo clientInfo) {
554 clientInfo.unregisterMdnsListenerFromRequest(request);
555 removeRequestMap(clientId, id, clientInfo);
556 }
557
Irfan Sheriff75006652012-04-17 23:15:29 -0700558 @Override
559 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900560 final ClientInfo clientInfo;
561 final int id;
562 final int clientId = msg.arg2;
563 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700564 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800565 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800566 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900567 args = (ListenerArgs) msg.obj;
568 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000569 // If the binder death notification for a INsdManagerCallback was received
570 // before any calls are received by NsdService, the clientInfo would be
571 // cleared and cause NPE. Add a null check here to prevent this corner case.
572 if (clientInfo == null) {
573 Log.e(TAG, "Unknown connector in discovery");
574 break;
575 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700576
577 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900578 clientInfo.onDiscoverServicesFailed(
579 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700580 break;
581 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700582
Paul Hu23fa2022023-01-13 22:57:24 +0800583 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700584 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900585 final String serviceType = constructServiceType(info.getServiceType());
586 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)
587 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800588 if (serviceType == null) {
589 clientInfo.onDiscoverServicesFailed(clientId,
590 NsdManager.FAILURE_INTERNAL_ERROR);
591 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700592 }
Paul Hu23fa2022023-01-13 22:57:24 +0800593
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900594 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800595 maybeStartMonitoringSockets();
596 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900597 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800598 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
599 .setNetwork(info.getNetwork())
600 .setIsPassiveMode(true)
601 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900602 mMdnsDiscoveryManager.registerListener(
603 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900604 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800605 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700606 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800607 maybeStartDaemon();
608 if (discoverServices(id, info)) {
609 if (DBG) {
610 Log.d(TAG, "Discover " + msg.arg2 + " " + id
611 + info.getServiceType());
612 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900613 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800614 clientInfo.onDiscoverServicesStarted(clientId, info);
615 } else {
616 stopServiceDiscovery(id);
617 clientInfo.onDiscoverServicesFailed(clientId,
618 NsdManager.FAILURE_INTERNAL_ERROR);
619 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700620 }
621 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800622 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900623 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800624 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900625 args = (ListenerArgs) msg.obj;
626 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000627 // If the binder death notification for a INsdManagerCallback was received
628 // before any calls are received by NsdService, the clientInfo would be
629 // cleared and cause NPE. Add a null check here to prevent this corner case.
630 if (clientInfo == null) {
631 Log.e(TAG, "Unknown connector in stop discovery");
632 break;
633 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700634
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900635 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
636 if (request == null) {
637 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700638 break;
639 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900640 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900641 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
642 // point, so this needs to check the type of the original request to
643 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900644 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800645 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900646 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700647 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800648 removeRequestMap(clientId, id, clientInfo);
649 if (stopServiceDiscovery(id)) {
650 clientInfo.onStopDiscoverySucceeded(clientId);
651 } else {
652 clientInfo.onStopDiscoveryFailed(
653 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
654 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700655 }
656 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900657 }
658 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800659 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900660 args = (ListenerArgs) msg.obj;
661 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000662 // If the binder death notification for a INsdManagerCallback was received
663 // before any calls are received by NsdService, the clientInfo would be
664 // cleared and cause NPE. Add a null check here to prevent this corner case.
665 if (clientInfo == null) {
666 Log.e(TAG, "Unknown connector in registration");
667 break;
668 }
669
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700670 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900671 clientInfo.onRegisterServiceFailed(
672 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700673 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700674 }
675
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700676 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900677 final NsdServiceInfo serviceInfo = args.serviceInfo;
678 final String serviceType = serviceInfo.getServiceType();
679 final String registerServiceType = constructServiceType(serviceType);
680 if (mDeps.isMdnsAdvertiserEnabled(mContext)
681 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900682 if (registerServiceType == null) {
683 Log.e(TAG, "Invalid service type: " + serviceType);
684 clientInfo.onRegisterServiceFailed(clientId,
685 NsdManager.FAILURE_INTERNAL_ERROR);
686 break;
687 }
688 serviceInfo.setServiceType(registerServiceType);
689 serviceInfo.setServiceName(truncateServiceName(
690 serviceInfo.getServiceName()));
691
692 maybeStartMonitoringSockets();
693 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900694 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700695 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900696 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900697 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900698 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900699 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900700 // Return success after mDns reports success
701 } else {
702 unregisterService(id);
703 clientInfo.onRegisterServiceFailed(
704 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
705 }
706
Irfan Sheriff75006652012-04-17 23:15:29 -0700707 }
708 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900709 }
710 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800711 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900712 args = (ListenerArgs) msg.obj;
713 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000714 // If the binder death notification for a INsdManagerCallback was received
715 // before any calls are received by NsdService, the clientInfo would be
716 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900717 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800718 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700719 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700720 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900721 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
722 if (request == null) {
723 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
724 break;
725 }
726 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900727 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900728
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900729 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
730 // so this needs to check the type of the original request to unregister
731 // instead of looking at the flag value.
732 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900733 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900734 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700735 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900736 if (unregisterService(id)) {
737 clientInfo.onUnregisterServiceSucceeded(clientId);
738 } else {
739 clientInfo.onUnregisterServiceFailed(
740 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
741 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700742 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700743 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900744 }
Paul Hu75069ed2023-01-14 00:31:09 +0800745 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800746 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900747 args = (ListenerArgs) msg.obj;
748 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000749 // If the binder death notification for a INsdManagerCallback was received
750 // before any calls are received by NsdService, the clientInfo would be
751 // cleared and cause NPE. Add a null check here to prevent this corner case.
752 if (clientInfo == null) {
753 Log.e(TAG, "Unknown connector in resolution");
754 break;
755 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700756
Paul Hu75069ed2023-01-14 00:31:09 +0800757 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700758 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900759 final String serviceType = constructServiceType(info.getServiceType());
760 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)
761 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800762 if (serviceType == null) {
763 clientInfo.onResolveServiceFailed(clientId,
764 NsdManager.FAILURE_INTERNAL_ERROR);
765 break;
766 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900767 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800768
769 maybeStartMonitoringSockets();
770 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900771 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800772 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
773 .setNetwork(info.getNetwork())
774 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900775 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800776 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900777 mMdnsDiscoveryManager.registerListener(
778 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900779 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700780 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800781 if (clientInfo.mResolvedService != null) {
782 clientInfo.onResolveServiceFailed(
783 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
784 break;
785 }
786
787 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900788 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800789 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900790 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800791 } else {
792 clientInfo.onResolveServiceFailed(
793 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
794 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700795 }
796 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800797 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900798 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000799 if (DBG) Log.d(TAG, "Stop service resolution");
800 args = (ListenerArgs) msg.obj;
801 clientInfo = mClients.get(args.connector);
802 // If the binder death notification for a INsdManagerCallback was received
803 // before any calls are received by NsdService, the clientInfo would be
804 // cleared and cause NPE. Add a null check here to prevent this corner case.
805 if (clientInfo == null) {
806 Log.e(TAG, "Unknown connector in stop resolution");
807 break;
808 }
809
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900810 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
811 if (request == null) {
812 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
813 break;
814 }
815 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800816 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
817 // point, so this needs to check the type of the original request to
818 // unregister instead of looking at the flag value.
819 if (request instanceof DiscoveryManagerRequest) {
820 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000821 clientInfo.onStopResolutionSucceeded(clientId);
822 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800823 removeRequestMap(clientId, id, clientInfo);
824 if (stopResolveService(id)) {
825 clientInfo.onStopResolutionSucceeded(clientId);
826 } else {
827 clientInfo.onStopResolutionFailed(
828 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
829 }
830 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000831 }
Paul Hub58deb72022-12-26 09:24:42 +0000832 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900833 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000834 case NsdManager.REGISTER_SERVICE_CALLBACK:
835 if (DBG) Log.d(TAG, "Register a service callback");
836 args = (ListenerArgs) msg.obj;
837 clientInfo = mClients.get(args.connector);
838 // If the binder death notification for a INsdManagerCallback was received
839 // before any calls are received by NsdService, the clientInfo would be
840 // cleared and cause NPE. Add a null check here to prevent this corner case.
841 if (clientInfo == null) {
842 Log.e(TAG, "Unknown connector in callback registration");
843 break;
844 }
845
846 if (clientInfo.mRegisteredService != null) {
847 clientInfo.onServiceInfoCallbackRegistrationFailed(
848 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
849 break;
850 }
851
852 maybeStartDaemon();
853 id = getUniqueId();
854 if (resolveService(id, args.serviceInfo)) {
855 clientInfo.mRegisteredService = new NsdServiceInfo();
856 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900857 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000858 } else {
859 clientInfo.onServiceInfoCallbackRegistrationFailed(
860 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
861 }
862 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900863 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000864 if (DBG) Log.d(TAG, "Unregister a service callback");
865 args = (ListenerArgs) msg.obj;
866 clientInfo = mClients.get(args.connector);
867 // If the binder death notification for a INsdManagerCallback was received
868 // before any calls are received by NsdService, the clientInfo would be
869 // cleared and cause NPE. Add a null check here to prevent this corner case.
870 if (clientInfo == null) {
871 Log.e(TAG, "Unknown connector in callback unregistration");
872 break;
873 }
874
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900875 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
876 if (request == null) {
877 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
878 break;
879 }
880 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000881 removeRequestMap(clientId, id, clientInfo);
882 if (stopResolveService(id)) {
883 clientInfo.onServiceInfoCallbackUnregistered(clientId);
884 } else {
885 Log.e(TAG, "Failed to unregister service info callback");
886 }
887 clearRegisteredServiceInfo(clientInfo);
888 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900889 }
paulhu2b9ed952022-02-10 21:58:32 +0800890 case MDNS_SERVICE_EVENT:
891 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900892 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700893 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700894 break;
Paul Hu019621e2023-01-13 23:26:49 +0800895 case MDNS_DISCOVERY_MANAGER_EVENT:
896 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
897 return NOT_HANDLED;
898 }
899 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700900 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900901 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700902 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900903 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700904 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700905
Paul Hu18aeccc2022-12-27 08:48:48 +0000906 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
907 ClientInfo clientInfo, int error) {
908 if (isListenedToUpdates) {
909 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
910 clearRegisteredServiceInfo(clientInfo);
911 } else {
912 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
913 // for backwards compatibility.
914 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
915 clientInfo.mResolvedService = null;
916 }
917 }
918
paulhu2b9ed952022-02-10 21:58:32 +0800919 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700920 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700921 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
922 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800923 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900924 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700925 }
926
927 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700928 int clientId = clientInfo.getClientId(id);
929 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700930 // This can happen because of race conditions. For example,
931 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
932 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800933 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
934 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900935 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700936 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900937 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800938 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900939 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700940 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800941 case IMDnsEventListener.SERVICE_FOUND: {
942 final DiscoveryInfo info = (DiscoveryInfo) obj;
943 final String name = info.serviceName;
944 final String type = info.registrationType;
945 servInfo = new NsdServiceInfo(name, type);
946 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900947 if (foundNetId == 0L) {
948 // Ignore services that do not have a Network: they are not usable
949 // by apps, as they would need privileged permissions to use
950 // interfaces that do not have an associated Network.
951 break;
952 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900953 if (foundNetId == INetd.DUMMY_NET_ID) {
954 // Ignore services on the dummy0 interface: they are only seen when
955 // discovering locally advertised services, and are not reachable
956 // through that interface.
957 break;
958 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900959 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900960 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700961 break;
paulhu2b9ed952022-02-10 21:58:32 +0800962 }
963 case IMDnsEventListener.SERVICE_LOST: {
964 final DiscoveryInfo info = (DiscoveryInfo) obj;
965 final String name = info.serviceName;
966 final String type = info.registrationType;
967 final int lostNetId = info.netId;
968 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900969 // The network could be set to null (netId 0) if it was torn down when the
970 // service is lost
971 // TODO: avoid returning null in that case, possibly by remembering
972 // found services on the same interface index and their network at the time
973 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900974 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000975 // TODO: also support registered service lost when not discovering
976 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700977 break;
paulhu2b9ed952022-02-10 21:58:32 +0800978 }
979 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900980 clientInfo.onDiscoverServicesFailed(
981 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700982 break;
paulhu2b9ed952022-02-10 21:58:32 +0800983 case IMDnsEventListener.SERVICE_REGISTERED: {
984 final RegistrationInfo info = (RegistrationInfo) obj;
985 final String name = info.serviceName;
986 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900987 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700988 break;
paulhu2b9ed952022-02-10 21:58:32 +0800989 }
990 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900991 clientInfo.onRegisterServiceFailed(
992 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700993 break;
paulhu2b9ed952022-02-10 21:58:32 +0800994 case IMDnsEventListener.SERVICE_RESOLVED: {
995 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700996 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800997 final String fullName = info.serviceFullName;
998 while (index < fullName.length() && fullName.charAt(index) != '.') {
999 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001000 ++index;
1001 }
1002 ++index;
1003 }
paulhu2b9ed952022-02-10 21:58:32 +08001004 if (index >= fullName.length()) {
1005 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001006 break;
1007 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001008
paulhube186602022-04-12 07:18:23 +00001009 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001010 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001011 String type = rest.replace(".local.", "");
1012
Paul Hu18aeccc2022-12-27 08:48:48 +00001013 final boolean isListenedToUpdates =
1014 clientId == clientInfo.mClientIdForServiceUpdates;
1015 final NsdServiceInfo serviceInfo = isListenedToUpdates
1016 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1017
1018 serviceInfo.setServiceName(name);
1019 serviceInfo.setServiceType(type);
1020 serviceInfo.setPort(info.port);
1021 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001022 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001023
1024 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001025 removeRequestMap(clientId, id, clientInfo);
1026
paulhu2b9ed952022-02-10 21:58:32 +08001027 final int id2 = getUniqueId();
1028 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001029 storeLegacyRequestMap(clientId, id2, clientInfo,
1030 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001031 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001032 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1033 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001034 }
1035 break;
paulhu2b9ed952022-02-10 21:58:32 +08001036 }
1037 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001038 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001039 stopResolveService(id);
1040 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001041 notifyResolveFailedResult(
1042 clientId == clientInfo.mClientIdForServiceUpdates,
1043 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001044 break;
paulhu2b9ed952022-02-10 21:58:32 +08001045 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001046 /* NNN resolveId errorCode */
1047 stopGetAddrInfo(id);
1048 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001049 notifyResolveFailedResult(
1050 clientId == clientInfo.mClientIdForServiceUpdates,
1051 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001052 break;
paulhu2b9ed952022-02-10 21:58:32 +08001053 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001054 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001055 final GetAddressInfo info = (GetAddressInfo) obj;
1056 final String address = info.address;
1057 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001058 InetAddress serviceHost = null;
1059 try {
paulhu2b9ed952022-02-10 21:58:32 +08001060 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001061 } catch (UnknownHostException e) {
1062 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1063 }
1064
1065 // If the resolved service is on an interface without a network, consider it
1066 // as a failure: it would not be usable by apps as they would need
1067 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001068 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1069 if (netId != NETID_UNSET && serviceHost != null) {
1070 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1071 netId, info.interfaceIdx);
1072 final List<InetAddress> addresses =
1073 clientInfo.mRegisteredService.getHostAddresses();
1074 addresses.add(serviceHost);
1075 clientInfo.mRegisteredService.setHostAddresses(addresses);
1076 clientInfo.onServiceUpdated(
1077 clientId, clientInfo.mRegisteredService);
1078 } else {
1079 stopGetAddrInfo(id);
1080 removeRequestMap(clientId, id, clientInfo);
1081 clearRegisteredServiceInfo(clientInfo);
1082 clientInfo.onServiceInfoCallbackRegistrationFailed(
1083 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1084 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001085 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001086 if (netId != NETID_UNSET && serviceHost != null) {
1087 clientInfo.mResolvedService.setHost(serviceHost);
1088 setServiceNetworkForCallback(clientInfo.mResolvedService,
1089 netId, info.interfaceIdx);
1090 clientInfo.onResolveServiceSucceeded(
1091 clientId, clientInfo.mResolvedService);
1092 } else {
1093 clientInfo.onResolveServiceFailed(
1094 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1095 }
1096 stopGetAddrInfo(id);
1097 removeRequestMap(clientId, id, clientInfo);
1098 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001099 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001100 break;
paulhu2b9ed952022-02-10 21:58:32 +08001101 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001102 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001103 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001104 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001105 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001106 }
Paul Hu019621e2023-01-13 23:26:49 +08001107
1108 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1109 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1110 final String serviceType = event.mRequestedServiceType;
1111 final String serviceName = serviceInfo.getServiceInstanceName();
1112 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1113 final Network network = serviceInfo.getNetwork();
1114 setServiceNetworkForCallback(
1115 servInfo,
1116 network == null ? NETID_UNSET : network.netId,
1117 serviceInfo.getInterfaceIndex());
1118 return servInfo;
1119 }
1120
1121 private boolean handleMdnsDiscoveryManagerEvent(
1122 int transactionId, int code, Object obj) {
1123 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1124 if (clientInfo == null) {
1125 Log.e(TAG, String.format(
1126 "id %d for %d has no client mapping", transactionId, code));
1127 return false;
1128 }
1129
1130 final MdnsEvent event = (MdnsEvent) obj;
1131 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001132 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001133 if (DBG) {
1134 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1135 NsdManager.nameOf(code), transactionId));
1136 }
1137 switch (code) {
1138 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001139 clientInfo.onServiceFound(clientId, info);
1140 break;
1141 case NsdManager.SERVICE_LOST:
1142 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001143 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001144 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001145 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1146 if (request == null) {
1147 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1148 break;
1149 }
Paul Hu75069ed2023-01-14 00:31:09 +08001150 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1151 // Add '.' in front of the service type that aligns with historical behavior
1152 info.setServiceType("." + event.mRequestedServiceType);
1153 info.setPort(serviceInfo.getPort());
1154
1155 Map<String, String> attrs = serviceInfo.getAttributes();
1156 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1157 final String key = kv.getKey();
1158 try {
1159 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1160 } catch (IllegalArgumentException e) {
1161 Log.e(TAG, "Invalid attribute", e);
1162 }
1163 }
1164 try {
1165 if (serviceInfo.getIpv4Address() != null) {
1166 info.setHost(InetAddresses.parseNumericAddress(
1167 serviceInfo.getIpv4Address()));
1168 } else {
1169 info.setHost(InetAddresses.parseNumericAddress(
1170 serviceInfo.getIpv6Address()));
1171 }
1172 clientInfo.onResolveServiceSucceeded(clientId, info);
1173 } catch (IllegalArgumentException e) {
1174 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1175 clientInfo.onResolveServiceFailed(
1176 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1177 }
1178
1179 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001180 if (!(request instanceof DiscoveryManagerRequest)) {
1181 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1182 break;
1183 }
Paul Hue4f5f252023-02-16 21:13:47 +08001184 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001185 break;
1186 }
Paul Hu019621e2023-01-13 23:26:49 +08001187 default:
1188 return false;
1189 }
1190 return true;
1191 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001192 }
1193 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001194
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001195 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1196 switch (netId) {
1197 case NETID_UNSET:
1198 info.setNetwork(null);
1199 break;
1200 case INetd.LOCAL_NET_ID:
1201 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1202 // visible / usable for apps, so do not return it. Store the interface
1203 // index instead, so at least if the client tries to resolve the service
1204 // with that NsdServiceInfo, it will be done on the same interface.
1205 // If they recreate the NsdServiceInfo themselves, resolution would be
1206 // done on all interfaces as before T, which should also work.
1207 info.setNetwork(null);
1208 info.setInterfaceIndex(ifaceIdx);
1209 break;
1210 default:
1211 info.setNetwork(new Network(netId));
1212 }
1213 }
1214
paulhube186602022-04-12 07:18:23 +00001215 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1216 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1217 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1218 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1219 private String unescape(String s) {
1220 StringBuilder sb = new StringBuilder(s.length());
1221 for (int i = 0; i < s.length(); ++i) {
1222 char c = s.charAt(i);
1223 if (c == '\\') {
1224 if (++i >= s.length()) {
1225 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1226 break;
1227 }
1228 c = s.charAt(i);
1229 if (c != '.' && c != '\\') {
1230 if (i + 2 >= s.length()) {
1231 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1232 break;
1233 }
1234 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1235 + (s.charAt(i + 2) - '0'));
1236 i += 2;
1237 }
1238 }
1239 sb.append(c);
1240 }
1241 return sb.toString();
1242 }
1243
Paul Hu7445e3d2023-03-03 15:14:00 +08001244 /**
1245 * Check the given service type is valid and construct it to a service type
1246 * which can use for discovery / resolution service.
1247 *
1248 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1249 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1250 * underscore; they are alphanumerical characters or dashes or underscore, except the
1251 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1252 *
1253 * @param serviceType the request service type for discovery / resolution service
1254 * @return constructed service type or null if the given service type is invalid.
1255 */
1256 @Nullable
1257 public static String constructServiceType(String serviceType) {
1258 if (TextUtils.isEmpty(serviceType)) return null;
1259
1260 final Pattern serviceTypePattern = Pattern.compile(
1261 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1262 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1263 // Drop '.' at the end of service type that is compatible with old backend.
1264 + "\\.?$");
1265 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1266 if (!matcher.matches()) return null;
1267 return matcher.group(1) == null
1268 ? matcher.group(2)
1269 : matcher.group(1) + "_sub." + matcher.group(2);
1270 }
1271
Hugo Benichi803a2f02017-04-24 11:35:06 +09001272 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001273 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001274 this(ctx, handler, cleanupDelayMs, new Dependencies());
1275 }
1276
1277 @VisibleForTesting
1278 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001279 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001280 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001281 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001282 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001283 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1284 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001285 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001286
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001287 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1288 mMdnsSocketClient =
1289 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1290 mMdnsDiscoveryManager =
1291 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1292 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1293 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1294 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001295 }
1296
1297 /**
1298 * Dependencies of NsdService, for injection in tests.
1299 */
1300 @VisibleForTesting
1301 public static class Dependencies {
1302 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001303 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001304 *
1305 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001306 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001307 */
1308 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1309 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1310 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1311 }
1312
1313 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001314 * Check whether the MdnsAdvertiser feature is enabled.
1315 *
1316 * @param context The global context information about an app environment.
1317 * @return true if the MdnsAdvertiser feature is enabled.
1318 */
1319 public boolean isMdnsAdvertiserEnabled(Context context) {
1320 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1321 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1322 }
1323
1324 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001325 * Get the type allowlist flag value.
1326 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1327 */
1328 @Nullable
1329 public String getTypeAllowlistFlags() {
1330 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1331 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1332 }
1333
1334 /**
1335 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1336 */
1337 public boolean isFeatureEnabled(Context context, String feature) {
1338 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1339 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1340 }
1341
1342 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001343 * @see MdnsDiscoveryManager
1344 */
1345 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1346 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1347 return new MdnsDiscoveryManager(executorProvider, socketClient);
1348 }
1349
1350 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001351 * @see MdnsAdvertiser
1352 */
1353 public MdnsAdvertiser makeMdnsAdvertiser(
1354 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1355 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1356 return new MdnsAdvertiser(looper, socketProvider, cb);
1357 }
1358
1359 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001360 * @see MdnsSocketProvider
1361 */
1362 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1363 return new MdnsSocketProvider(context, looper);
1364 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001365 }
1366
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001367 /**
1368 * Return whether a type is allowlisted to use the Java backend.
1369 * @param type The service type
1370 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1371 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1372 */
1373 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1374 @NonNull String flagPrefix) {
1375 if (type == null) return false;
1376 final String typesConfig = mDeps.getTypeAllowlistFlags();
1377 if (TextUtils.isEmpty(typesConfig)) return false;
1378
1379 final String mappingPrefix = type + ":";
1380 String mappedFlag = null;
1381 for (String mapping : TextUtils.split(typesConfig, ",")) {
1382 if (mapping.startsWith(mappingPrefix)) {
1383 mappedFlag = mapping.substring(mappingPrefix.length());
1384 break;
1385 }
1386 }
1387
1388 if (mappedFlag == null) return false;
1389
1390 return mDeps.isFeatureEnabled(mContext,
1391 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1392 }
1393
1394 private boolean useDiscoveryManagerForType(@Nullable String type) {
1395 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1396 }
1397
1398 private boolean useAdvertiserForType(@Nullable String type) {
1399 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1400 }
1401
paulhu1b35e822022-04-08 14:48:41 +08001402 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001403 HandlerThread thread = new HandlerThread(TAG);
1404 thread.start();
1405 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001406 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001407 return service;
1408 }
1409
paulhu2b9ed952022-02-10 21:58:32 +08001410 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1411 private final StateMachine mStateMachine;
1412
1413 MDnsEventCallback(StateMachine sm) {
1414 mStateMachine = sm;
1415 }
1416
1417 @Override
1418 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1419 mStateMachine.sendMessage(
1420 MDNS_SERVICE_EVENT, status.result, status.id, status);
1421 }
1422
1423 @Override
1424 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1425 mStateMachine.sendMessage(
1426 MDNS_SERVICE_EVENT, status.result, status.id, status);
1427 }
1428
1429 @Override
1430 public void onServiceResolutionStatus(final ResolutionInfo status) {
1431 mStateMachine.sendMessage(
1432 MDNS_SERVICE_EVENT, status.result, status.id, status);
1433 }
1434
1435 @Override
1436 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1437 mStateMachine.sendMessage(
1438 MDNS_SERVICE_EVENT, status.result, status.id, status);
1439 }
1440
1441 @Override
1442 public int getInterfaceVersion() throws RemoteException {
1443 return this.VERSION;
1444 }
1445
1446 @Override
1447 public String getInterfaceHash() throws RemoteException {
1448 return this.HASH;
1449 }
1450 }
1451
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001452 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1453 @Override
1454 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1455 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1456 if (clientInfo == null) return;
1457
1458 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1459 if (clientId < 0) return;
1460
1461 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1462 // historical behavior.
1463 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1464 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1465 }
1466
1467 @Override
1468 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1469 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1470 if (clientInfo == null) return;
1471
1472 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1473 if (clientId < 0) return;
1474
1475 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1476 }
1477
1478 private ClientInfo getClientInfoOrLog(int serviceId) {
1479 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1480 if (clientInfo == null) {
1481 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1482 }
1483 return clientInfo;
1484 }
1485
1486 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1487 final int clientId = info.getClientId(serviceId);
1488 if (clientId < 0) {
1489 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1490 }
1491 return clientId;
1492 }
1493 }
1494
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001495 @Override
1496 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001497 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001498 final INsdServiceConnector connector = new NsdServiceConnector();
1499 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1500 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1501 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001502 }
1503
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001504 private static class ListenerArgs {
1505 public final NsdServiceConnector connector;
1506 public final NsdServiceInfo serviceInfo;
1507 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1508 this.connector = connector;
1509 this.serviceInfo = serviceInfo;
1510 }
1511 }
1512
1513 private class NsdServiceConnector extends INsdServiceConnector.Stub
1514 implements IBinder.DeathRecipient {
1515 @Override
1516 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1517 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1518 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1519 new ListenerArgs(this, serviceInfo)));
1520 }
1521
1522 @Override
1523 public void unregisterService(int listenerKey) {
1524 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1525 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1526 new ListenerArgs(this, null)));
1527 }
1528
1529 @Override
1530 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1531 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1532 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1533 new ListenerArgs(this, serviceInfo)));
1534 }
1535
1536 @Override
1537 public void stopDiscovery(int listenerKey) {
1538 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1539 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1540 }
1541
1542 @Override
1543 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1544 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1545 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1546 new ListenerArgs(this, serviceInfo)));
1547 }
1548
1549 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001550 public void stopResolution(int listenerKey) {
1551 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1552 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1553 }
1554
1555 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001556 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1557 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1558 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1559 new ListenerArgs(this, serviceInfo)));
1560 }
1561
1562 @Override
1563 public void unregisterServiceInfoCallback(int listenerKey) {
1564 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1565 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1566 new ListenerArgs(this, null)));
1567 }
1568
1569 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001570 public void startDaemon() {
1571 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1572 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1573 }
1574
1575 @Override
1576 public void binderDied() {
1577 mNsdStateMachine.sendMessage(
1578 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1579 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001580 }
1581
Hugo Benichi912db992017-04-24 16:41:03 +09001582 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001583 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001584 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001585 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1586 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001587 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001588 }
1589
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001590 private int getUniqueId() {
1591 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1592 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001593 }
1594
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001595 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001596 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001597 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001598 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001599 String name = service.getServiceName();
1600 String type = service.getServiceType();
1601 int port = service.getPort();
1602 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001603 final int registerInterface = getNetworkInterfaceIndex(service);
1604 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001605 Log.e(TAG, "Interface to register service on not found");
1606 return false;
1607 }
1608 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001609 }
1610
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001611 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001612 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001613 }
1614
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001615 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001616 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001617 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1618 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001619 Log.e(TAG, "Interface to discover service on not found");
1620 return false;
1621 }
paulhu2b9ed952022-02-10 21:58:32 +08001622 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001623 }
1624
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001625 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001626 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001627 }
1628
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001629 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001630 final String name = service.getServiceName();
1631 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001632 final int resolveInterface = getNetworkInterfaceIndex(service);
1633 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001634 Log.e(TAG, "Interface to resolve service on not found");
1635 return false;
1636 }
paulhu2b9ed952022-02-10 21:58:32 +08001637 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001638 }
1639
1640 /**
1641 * Guess the interface to use to resolve or discover a service on a specific network.
1642 *
1643 * This is an imperfect guess, as for example the network may be gone or not yet fully
1644 * registered. This is fine as failing is correct if the network is gone, and a client
1645 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1646 * this is to support the legacy mdnsresponder implementation, which historically resolved
1647 * services on an unspecified network.
1648 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001649 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1650 final Network network = serviceInfo.getNetwork();
1651 if (network == null) {
1652 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1653 // provided by NsdService from discovery results, and the service was found on an
1654 // interface that has no app-usable Network).
1655 if (serviceInfo.getInterfaceIndex() != 0) {
1656 return serviceInfo.getInterfaceIndex();
1657 }
1658 return IFACE_IDX_ANY;
1659 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001660
1661 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1662 if (cm == null) {
1663 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1664 return IFACE_IDX_ANY;
1665 }
1666 final LinkProperties lp = cm.getLinkProperties(network);
1667 if (lp == null) return IFACE_IDX_ANY;
1668
1669 // Only resolve on non-stacked interfaces
1670 final NetworkInterface iface;
1671 try {
1672 iface = NetworkInterface.getByName(lp.getInterfaceName());
1673 } catch (SocketException e) {
1674 Log.e(TAG, "Error querying interface", e);
1675 return IFACE_IDX_ANY;
1676 }
1677
1678 if (iface == null) {
1679 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1680 return IFACE_IDX_ANY;
1681 }
1682
1683 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001684 }
1685
1686 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001687 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001688 }
1689
paulhu2b9ed952022-02-10 21:58:32 +08001690 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1691 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001692 }
1693
1694 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001695 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001696 }
1697
1698 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001699 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001700 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001701
Irfan Sheriff75006652012-04-17 23:15:29 -07001702 for (ClientInfo client : mClients.values()) {
1703 pw.println("Client Info");
1704 pw.println(client);
1705 }
1706
1707 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001708 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001709
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001710 private abstract static class ClientRequest {
1711 private final int mGlobalId;
1712
1713 private ClientRequest(int globalId) {
1714 mGlobalId = globalId;
1715 }
1716 }
1717
1718 private static class LegacyClientRequest extends ClientRequest {
1719 private final int mRequestCode;
1720
1721 private LegacyClientRequest(int globalId, int requestCode) {
1722 super(globalId);
1723 mRequestCode = requestCode;
1724 }
1725 }
1726
1727 private static class AdvertiserClientRequest extends ClientRequest {
1728 private AdvertiserClientRequest(int globalId) {
1729 super(globalId);
1730 }
1731 }
1732
1733 private static class DiscoveryManagerRequest extends ClientRequest {
1734 @NonNull
1735 private final MdnsListener mListener;
1736
1737 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1738 super(globalId);
1739 mListener = listener;
1740 }
1741 }
1742
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001743 /* Information tracked per client */
1744 private class ClientInfo {
1745
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001746 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001747 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001748 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001749 private NsdServiceInfo mResolvedService;
1750
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001751 /* A map from client-side ID (listenerKey) to the request */
1752 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001753
Luke Huangf7277ed2021-07-12 21:15:10 +08001754 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001755 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001756
Paul Hu18aeccc2022-12-27 08:48:48 +00001757 /*** The service that is registered to listen to its updates */
1758 private NsdServiceInfo mRegisteredService;
1759 /*** The client id that listen to updates */
1760 private int mClientIdForServiceUpdates;
1761
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001762 private ClientInfo(INsdManagerCallback cb) {
1763 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001764 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001765 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001766
1767 @Override
1768 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001769 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001770 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001771 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1772 for (int i = 0; i < mClientRequests.size(); i++) {
1773 int clientID = mClientRequests.keyAt(i);
1774 sb.append("clientId ")
1775 .append(clientID)
1776 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1777 .append(" type ").append(
1778 mClientRequests.valueAt(i).getClass().getSimpleName())
1779 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001780 }
1781 return sb.toString();
1782 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001783
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001784 private boolean isPreSClient() {
1785 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001786 }
1787
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001788 private void setPreSClient() {
1789 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001790 }
1791
Paul Hue4f5f252023-02-16 21:13:47 +08001792 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1793 final MdnsListener listener =
1794 ((DiscoveryManagerRequest) request).mListener;
1795 mMdnsDiscoveryManager.unregisterListener(
1796 listener.getListenedServiceType(), listener);
1797 }
1798
Dave Plattfeff2af2014-03-07 14:48:22 -08001799 // Remove any pending requests from the global map when we get rid of a client,
1800 // and send cancellations to the daemon.
1801 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001802 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001803 for (int i = 0; i < mClientRequests.size(); i++) {
1804 final int clientId = mClientRequests.keyAt(i);
1805 final ClientRequest request = mClientRequests.valueAt(i);
1806 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001807 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001808 if (DBG) {
1809 Log.d(TAG, "Terminating client-ID " + clientId
1810 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1811 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001812
1813 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001814 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001815 continue;
1816 }
1817
1818 if (request instanceof AdvertiserClientRequest) {
1819 mAdvertiser.removeService(globalId);
1820 continue;
1821 }
1822
1823 if (!(request instanceof LegacyClientRequest)) {
1824 throw new IllegalStateException("Unknown request type: " + request.getClass());
1825 }
1826
1827 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001828 case NsdManager.DISCOVER_SERVICES:
1829 stopServiceDiscovery(globalId);
1830 break;
1831 case NsdManager.RESOLVE_SERVICE:
1832 stopResolveService(globalId);
1833 break;
1834 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001835 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001836 break;
1837 default:
1838 break;
1839 }
1840 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001841 mClientRequests.clear();
1842 }
1843
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001844 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1845 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1846 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001847 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001848 for (int i = 0; i < mClientRequests.size(); i++) {
1849 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1850 return mClientRequests.keyAt(i);
1851 }
Christopher Lane74411222014-04-25 18:39:07 -07001852 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001853 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001854 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001855
Paul Hu18aeccc2022-12-27 08:48:48 +00001856 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1857 if (mRegisteredService == null) return;
1858 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1859 // Resolved services have a leading dot appended at the beginning of their type, but in
1860 // discovered info it's at the end
1861 if (!Objects.equals(
1862 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1863 return;
1864 }
1865 onServiceUpdatedLost(mClientIdForServiceUpdates);
1866 }
1867
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001868 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1869 try {
1870 mCb.onDiscoverServicesStarted(listenerKey, info);
1871 } catch (RemoteException e) {
1872 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1873 }
1874 }
1875
1876 void onDiscoverServicesFailed(int listenerKey, int error) {
1877 try {
1878 mCb.onDiscoverServicesFailed(listenerKey, error);
1879 } catch (RemoteException e) {
1880 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1881 }
1882 }
1883
1884 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1885 try {
1886 mCb.onServiceFound(listenerKey, info);
1887 } catch (RemoteException e) {
1888 Log.e(TAG, "Error calling onServiceFound(", e);
1889 }
1890 }
1891
1892 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1893 try {
1894 mCb.onServiceLost(listenerKey, info);
1895 } catch (RemoteException e) {
1896 Log.e(TAG, "Error calling onServiceLost(", e);
1897 }
1898 }
1899
1900 void onStopDiscoveryFailed(int listenerKey, int error) {
1901 try {
1902 mCb.onStopDiscoveryFailed(listenerKey, error);
1903 } catch (RemoteException e) {
1904 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1905 }
1906 }
1907
1908 void onStopDiscoverySucceeded(int listenerKey) {
1909 try {
1910 mCb.onStopDiscoverySucceeded(listenerKey);
1911 } catch (RemoteException e) {
1912 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1913 }
1914 }
1915
1916 void onRegisterServiceFailed(int listenerKey, int error) {
1917 try {
1918 mCb.onRegisterServiceFailed(listenerKey, error);
1919 } catch (RemoteException e) {
1920 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1921 }
1922 }
1923
1924 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1925 try {
1926 mCb.onRegisterServiceSucceeded(listenerKey, info);
1927 } catch (RemoteException e) {
1928 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1929 }
1930 }
1931
1932 void onUnregisterServiceFailed(int listenerKey, int error) {
1933 try {
1934 mCb.onUnregisterServiceFailed(listenerKey, error);
1935 } catch (RemoteException e) {
1936 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1937 }
1938 }
1939
1940 void onUnregisterServiceSucceeded(int listenerKey) {
1941 try {
1942 mCb.onUnregisterServiceSucceeded(listenerKey);
1943 } catch (RemoteException e) {
1944 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1945 }
1946 }
1947
1948 void onResolveServiceFailed(int listenerKey, int error) {
1949 try {
1950 mCb.onResolveServiceFailed(listenerKey, error);
1951 } catch (RemoteException e) {
1952 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1953 }
1954 }
1955
1956 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1957 try {
1958 mCb.onResolveServiceSucceeded(listenerKey, info);
1959 } catch (RemoteException e) {
1960 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1961 }
1962 }
Paul Hub58deb72022-12-26 09:24:42 +00001963
1964 void onStopResolutionFailed(int listenerKey, int error) {
1965 try {
1966 mCb.onStopResolutionFailed(listenerKey, error);
1967 } catch (RemoteException e) {
1968 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1969 }
1970 }
1971
1972 void onStopResolutionSucceeded(int listenerKey) {
1973 try {
1974 mCb.onStopResolutionSucceeded(listenerKey);
1975 } catch (RemoteException e) {
1976 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1977 }
1978 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001979
1980 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1981 try {
1982 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1983 } catch (RemoteException e) {
1984 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1985 }
1986 }
1987
1988 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1989 try {
1990 mCb.onServiceUpdated(listenerKey, info);
1991 } catch (RemoteException e) {
1992 Log.e(TAG, "Error calling onServiceUpdated", e);
1993 }
1994 }
1995
1996 void onServiceUpdatedLost(int listenerKey) {
1997 try {
1998 mCb.onServiceUpdatedLost(listenerKey);
1999 } catch (RemoteException e) {
2000 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2001 }
2002 }
2003
2004 void onServiceInfoCallbackUnregistered(int listenerKey) {
2005 try {
2006 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2007 } catch (RemoteException e) {
2008 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2009 }
2010 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002011 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002012}