blob: b5a10e29c4529db3514a431813e59b885534f3c7 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
20import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080021import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
paulhu2b9ed952022-02-10 21:58:32 +080022
Paul Hu4bd98ef2023-01-12 13:42:07 +080023import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080024import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070025import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090026import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090027import android.net.INetd;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090028import android.net.LinkProperties;
29import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080030import android.net.mdns.aidl.DiscoveryInfo;
31import android.net.mdns.aidl.GetAddressInfo;
32import android.net.mdns.aidl.IMDnsEventListener;
33import android.net.mdns.aidl.RegistrationInfo;
34import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070035import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090036import android.net.nsd.INsdManagerCallback;
37import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080038import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070039import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080040import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090041import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080042import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090043import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080044import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070047import android.os.UserHandle;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090048import android.util.Log;
49import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070050import android.util.SparseArray;
Hugo Benichid2552ae2017-04-11 14:42:47 +090051import android.util.SparseIntArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052
paulhua262cc12019-08-12 16:25:11 +080053import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080054import com.android.internal.util.State;
55import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080056import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080057import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080058import com.android.server.connectivity.mdns.ExecutorProvider;
59import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
60import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
61import com.android.server.connectivity.mdns.MdnsSocketClientBase;
62import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080063
Irfan Sheriff77ec5582012-03-22 17:01:39 -070064import java.io.FileDescriptor;
65import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070066import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090067import java.net.NetworkInterface;
68import java.net.SocketException;
69import java.net.UnknownHostException;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070070import java.util.HashMap;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070071
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072/**
73 * Network Service Discovery Service handles remote service discovery operation requests by
74 * implementing the INsdManager interface.
75 *
76 * @hide
77 */
78public class NsdService extends INsdManager.Stub {
79 private static final String TAG = "NsdService";
80 private static final String MDNS_TAG = "mDnsConnector";
Paul Hu4bd98ef2023-01-12 13:42:07 +080081 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Irfan Sheriff77ec5582012-03-22 17:01:39 -070082
paulhu2b9ed952022-02-10 21:58:32 +080083 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +000084 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090085 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070086
Hugo Benichi32be63d2017-04-05 14:06:11 +090087 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +090088 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +080089 private final MDnsManager mMDnsManager;
90 private final MDnsEventCallback mMDnsEventCallback;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091 @Nullable
92 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
93 @Nullable
94 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
95 @Nullable
96 private final MdnsSocketProvider mMdnsSocketProvider;
paulhu2b9ed952022-02-10 21:58:32 +080097 // WARNING : Accessing this value in any thread is not safe, it must only be changed in the
98 // state machine thread. If change this outside state machine, it will need to introduce
99 // synchronization.
100 private boolean mIsDaemonStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700101
102 /**
103 * Clients receiving asynchronous messages
104 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900105 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700106
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700107 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900108 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700109
Luke Huang05298582021-06-13 16:52:05 +0000110 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700111
Hugo Benichi32be63d2017-04-05 14:06:11 +0900112 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700113 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800114 // The count of the connected legacy clients.
115 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700116
Irfan Sheriff75006652012-04-17 23:15:29 -0700117 private class NsdStateMachine extends StateMachine {
118
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700119 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700120 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700121
122 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700123 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900124 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700125 }
126
Luke Huang92860f92021-06-23 06:29:30 +0000127 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800128 if (mIsDaemonStarted) {
129 if (DBG) Log.d(TAG, "Daemon is already started.");
130 return;
131 }
132 mMDnsManager.registerEventListener(mMDnsEventCallback);
133 mMDnsManager.startDaemon();
134 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000135 maybeScheduleStop();
136 }
137
paulhu2b9ed952022-02-10 21:58:32 +0800138 private void maybeStopDaemon() {
139 if (!mIsDaemonStarted) {
140 if (DBG) Log.d(TAG, "Daemon has not been started.");
141 return;
142 }
143 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
144 mMDnsManager.stopDaemon();
145 mIsDaemonStarted = false;
146 }
147
Luke Huang92860f92021-06-23 06:29:30 +0000148 private boolean isAnyRequestActive() {
149 return mIdToClientInfoMap.size() != 0;
150 }
151
152 private void scheduleStop() {
153 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
154 }
155 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800156 // The native daemon should stay alive and can't be cleanup
157 // if any legacy client connected.
158 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000159 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000160 }
161 }
162
Luke Huang92860f92021-06-23 06:29:30 +0000163 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000164 this.removeMessages(NsdManager.DAEMON_CLEANUP);
165 }
166
Hugo Benichi803a2f02017-04-24 11:35:06 +0900167 NsdStateMachine(String name, Handler handler) {
168 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700169 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700170 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800171 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900172 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700173 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700174 }
175
176 class DefaultState extends State {
177 @Override
178 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900179 final ClientInfo cInfo;
180 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700181 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900182 case NsdManager.REGISTER_CLIENT:
183 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
184 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
185 final INsdManagerCallback cb = arg.second;
186 try {
187 cb.asBinder().linkToDeath(arg.first, 0);
188 cInfo = new ClientInfo(cb);
189 mClients.put(arg.first, cInfo);
190 } catch (RemoteException e) {
191 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700192 }
193 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900194 case NsdManager.UNREGISTER_CLIENT:
195 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
196 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800197 if (cInfo != null) {
198 cInfo.expungeAllRequests();
Luke Huangf7277ed2021-07-12 21:15:10 +0800199 if (cInfo.isLegacy()) {
200 mLegacyClientCount -= 1;
201 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800202 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800203 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700204 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700205 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900206 cInfo = getClientInfoForReply(msg);
207 if (cInfo != null) {
208 cInfo.onDiscoverServicesFailed(
209 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
210 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700211 break;
212 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900213 cInfo = getClientInfoForReply(msg);
214 if (cInfo != null) {
215 cInfo.onStopDiscoveryFailed(
216 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
217 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700218 break;
219 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900220 cInfo = getClientInfoForReply(msg);
221 if (cInfo != null) {
222 cInfo.onRegisterServiceFailed(
223 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
224 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700225 break;
226 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900227 cInfo = getClientInfoForReply(msg);
228 if (cInfo != null) {
229 cInfo.onUnregisterServiceFailed(
230 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
231 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700232 break;
233 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900234 cInfo = getClientInfoForReply(msg);
235 if (cInfo != null) {
236 cInfo.onResolveServiceFailed(
237 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
238 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700239 break;
Luke Huang05298582021-06-13 16:52:05 +0000240 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800241 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000242 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800243 // This event should be only sent by the legacy (target SDK < S) clients.
244 // Mark the sending client as legacy.
245 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900246 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800247 if (cInfo != null) {
248 cancelStop();
249 cInfo.setLegacy();
250 mLegacyClientCount += 1;
251 maybeStartDaemon();
252 }
253 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700254 default:
paulhub2225702021-11-17 09:35:33 +0800255 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700256 return NOT_HANDLED;
257 }
258 return HANDLED;
259 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900260
261 private ClientInfo getClientInfoForReply(Message msg) {
262 final ListenerArgs args = (ListenerArgs) msg.obj;
263 return mClients.get(args.connector);
264 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700265 }
266
Irfan Sheriff75006652012-04-17 23:15:29 -0700267 class EnabledState extends State {
268 @Override
269 public void enter() {
270 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700271 }
272
273 @Override
274 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000275 // TODO: it is incorrect to stop the daemon without expunging all requests
276 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000277 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700278 }
279
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700280 private boolean requestLimitReached(ClientInfo clientInfo) {
281 if (clientInfo.mClientIds.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800282 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700283 return true;
284 }
285 return false;
286 }
287
Dave Plattfeff2af2014-03-07 14:48:22 -0800288 private void storeRequestMap(int clientId, int globalId, ClientInfo clientInfo, int what) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700289 clientInfo.mClientIds.put(clientId, globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -0800290 clientInfo.mClientRequests.put(clientId, what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700291 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000292 // Remove the cleanup event because here comes a new request.
293 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700294 }
295
296 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900297 clientInfo.mClientIds.delete(clientId);
298 clientInfo.mClientRequests.delete(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700299 mIdToClientInfoMap.remove(globalId);
Luke Huang05298582021-06-13 16:52:05 +0000300 maybeScheduleStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700301 }
302
Irfan Sheriff75006652012-04-17 23:15:29 -0700303 @Override
304 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900305 final ClientInfo clientInfo;
306 final int id;
307 final int clientId = msg.arg2;
308 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700309 switch (msg.what) {
Irfan Sheriff75006652012-04-17 23:15:29 -0700310 case NsdManager.DISCOVER_SERVICES:
paulhub2225702021-11-17 09:35:33 +0800311 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900312 args = (ListenerArgs) msg.obj;
313 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000314 // If the binder death notification for a INsdManagerCallback was received
315 // before any calls are received by NsdService, the clientInfo would be
316 // cleared and cause NPE. Add a null check here to prevent this corner case.
317 if (clientInfo == null) {
318 Log.e(TAG, "Unknown connector in discovery");
319 break;
320 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700321
322 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900323 clientInfo.onDiscoverServicesFailed(
324 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700325 break;
326 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700327
Luke Huang05298582021-06-13 16:52:05 +0000328 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700329 id = getUniqueId();
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900330 if (discoverServices(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700331 if (DBG) {
paulhub2225702021-11-17 09:35:33 +0800332 Log.d(TAG, "Discover " + msg.arg2 + " " + id
333 + args.serviceInfo.getServiceType());
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700334 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900335 storeRequestMap(clientId, id, clientInfo, msg.what);
336 clientInfo.onDiscoverServicesStarted(clientId, args.serviceInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700337 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700338 stopServiceDiscovery(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900339 clientInfo.onDiscoverServicesFailed(clientId,
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700340 NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700341 }
342 break;
343 case NsdManager.STOP_DISCOVERY:
paulhub2225702021-11-17 09:35:33 +0800344 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900345 args = (ListenerArgs) msg.obj;
346 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000347 // If the binder death notification for a INsdManagerCallback was received
348 // before any calls are received by NsdService, the clientInfo would be
349 // cleared and cause NPE. Add a null check here to prevent this corner case.
350 if (clientInfo == null) {
351 Log.e(TAG, "Unknown connector in stop discovery");
352 break;
353 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700354
355 try {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900356 id = clientInfo.mClientIds.get(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700357 } catch (NullPointerException e) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900358 clientInfo.onStopDiscoveryFailed(
359 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700360 break;
361 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900362 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700363 if (stopServiceDiscovery(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900364 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700365 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900366 clientInfo.onStopDiscoveryFailed(
367 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700368 }
369 break;
370 case NsdManager.REGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800371 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900372 args = (ListenerArgs) msg.obj;
373 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000374 // If the binder death notification for a INsdManagerCallback was received
375 // before any calls are received by NsdService, the clientInfo would be
376 // cleared and cause NPE. Add a null check here to prevent this corner case.
377 if (clientInfo == null) {
378 Log.e(TAG, "Unknown connector in registration");
379 break;
380 }
381
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700382 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900383 clientInfo.onRegisterServiceFailed(
384 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700385 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700386 }
387
Luke Huang05298582021-06-13 16:52:05 +0000388 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700389 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900390 if (registerService(id, args.serviceInfo)) {
paulhub2225702021-11-17 09:35:33 +0800391 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900392 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700393 // Return success after mDns reports success
Irfan Sheriff75006652012-04-17 23:15:29 -0700394 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700395 unregisterService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900396 clientInfo.onRegisterServiceFailed(
397 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700398 }
399 break;
400 case NsdManager.UNREGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800401 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900402 args = (ListenerArgs) msg.obj;
403 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000404 // If the binder death notification for a INsdManagerCallback was received
405 // before any calls are received by NsdService, the clientInfo would be
406 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900407 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800408 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700409 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700410 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900411 id = clientInfo.mClientIds.get(clientId);
412 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700413 if (unregisterService(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900414 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700415 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900416 clientInfo.onUnregisterServiceFailed(
417 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700418 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700419 break;
420 case NsdManager.RESOLVE_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800421 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900422 args = (ListenerArgs) msg.obj;
423 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000424 // If the binder death notification for a INsdManagerCallback was received
425 // before any calls are received by NsdService, the clientInfo would be
426 // cleared and cause NPE. Add a null check here to prevent this corner case.
427 if (clientInfo == null) {
428 Log.e(TAG, "Unknown connector in resolution");
429 break;
430 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700431
432 if (clientInfo.mResolvedService != null) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900433 clientInfo.onResolveServiceFailed(
434 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
Irfan Sheriff75006652012-04-17 23:15:29 -0700435 break;
436 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700437
Luke Huang05298582021-06-13 16:52:05 +0000438 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700439 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900440 if (resolveService(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700441 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900442 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700443 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900444 clientInfo.onResolveServiceFailed(
445 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 }
447 break;
paulhu2b9ed952022-02-10 21:58:32 +0800448 case MDNS_SERVICE_EVENT:
449 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900450 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700451 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700452 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900454 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700455 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900456 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700457 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700458
paulhu2b9ed952022-02-10 21:58:32 +0800459 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700460 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700461 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
462 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800463 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900464 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700465 }
466
467 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700468 int clientId = clientInfo.getClientId(id);
469 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700470 // This can happen because of race conditions. For example,
471 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
472 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800473 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
474 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900475 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700476 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900477 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800478 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900479 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700480 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800481 case IMDnsEventListener.SERVICE_FOUND: {
482 final DiscoveryInfo info = (DiscoveryInfo) obj;
483 final String name = info.serviceName;
484 final String type = info.registrationType;
485 servInfo = new NsdServiceInfo(name, type);
486 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900487 if (foundNetId == 0L) {
488 // Ignore services that do not have a Network: they are not usable
489 // by apps, as they would need privileged permissions to use
490 // interfaces that do not have an associated Network.
491 break;
492 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900493 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900494 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700495 break;
paulhu2b9ed952022-02-10 21:58:32 +0800496 }
497 case IMDnsEventListener.SERVICE_LOST: {
498 final DiscoveryInfo info = (DiscoveryInfo) obj;
499 final String name = info.serviceName;
500 final String type = info.registrationType;
501 final int lostNetId = info.netId;
502 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900503 // The network could be set to null (netId 0) if it was torn down when the
504 // service is lost
505 // TODO: avoid returning null in that case, possibly by remembering
506 // found services on the same interface index and their network at the time
507 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900508 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700509 break;
paulhu2b9ed952022-02-10 21:58:32 +0800510 }
511 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900512 clientInfo.onDiscoverServicesFailed(
513 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700514 break;
paulhu2b9ed952022-02-10 21:58:32 +0800515 case IMDnsEventListener.SERVICE_REGISTERED: {
516 final RegistrationInfo info = (RegistrationInfo) obj;
517 final String name = info.serviceName;
518 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900519 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700520 break;
paulhu2b9ed952022-02-10 21:58:32 +0800521 }
522 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900523 clientInfo.onRegisterServiceFailed(
524 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700525 break;
paulhu2b9ed952022-02-10 21:58:32 +0800526 case IMDnsEventListener.SERVICE_RESOLVED: {
527 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700528 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800529 final String fullName = info.serviceFullName;
530 while (index < fullName.length() && fullName.charAt(index) != '.') {
531 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700532 ++index;
533 }
534 ++index;
535 }
paulhu2b9ed952022-02-10 21:58:32 +0800536 if (index >= fullName.length()) {
537 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700538 break;
539 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900540
paulhube186602022-04-12 07:18:23 +0000541 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800542 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700543 String type = rest.replace(".local.", "");
544
545 clientInfo.mResolvedService.setServiceName(name);
546 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800547 clientInfo.mResolvedService.setPort(info.port);
548 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900549 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700550
551 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800552 removeRequestMap(clientId, id, clientInfo);
553
paulhu2b9ed952022-02-10 21:58:32 +0800554 final int id2 = getUniqueId();
555 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800556 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800557 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900558 clientInfo.onResolveServiceFailed(
559 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700560 clientInfo.mResolvedService = null;
561 }
562 break;
paulhu2b9ed952022-02-10 21:58:32 +0800563 }
564 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700565 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700566 stopResolveService(id);
567 removeRequestMap(clientId, id, clientInfo);
568 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900569 clientInfo.onResolveServiceFailed(
570 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700571 break;
paulhu2b9ed952022-02-10 21:58:32 +0800572 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700573 /* NNN resolveId errorCode */
574 stopGetAddrInfo(id);
575 removeRequestMap(clientId, id, clientInfo);
576 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900577 clientInfo.onResolveServiceFailed(
578 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700579 break;
paulhu2b9ed952022-02-10 21:58:32 +0800580 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900581 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800582 final GetAddressInfo info = (GetAddressInfo) obj;
583 final String address = info.address;
584 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900585 InetAddress serviceHost = null;
586 try {
paulhu2b9ed952022-02-10 21:58:32 +0800587 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900588 } catch (UnknownHostException e) {
589 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
590 }
591
592 // If the resolved service is on an interface without a network, consider it
593 // as a failure: it would not be usable by apps as they would need
594 // privileged permissions.
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900595 if (netId != NETID_UNSET && serviceHost != null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900596 clientInfo.mResolvedService.setHost(serviceHost);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900597 setServiceNetworkForCallback(clientInfo.mResolvedService,
598 netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900599 clientInfo.onResolveServiceSucceeded(
600 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900601 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 clientInfo.onResolveServiceFailed(
603 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700604 }
605 stopGetAddrInfo(id);
606 removeRequestMap(clientId, id, clientInfo);
607 clientInfo.mResolvedService = null;
608 break;
paulhu2b9ed952022-02-10 21:58:32 +0800609 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700610 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900611 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700612 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900613 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700614 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 }
616 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700617
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900618 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
619 switch (netId) {
620 case NETID_UNSET:
621 info.setNetwork(null);
622 break;
623 case INetd.LOCAL_NET_ID:
624 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
625 // visible / usable for apps, so do not return it. Store the interface
626 // index instead, so at least if the client tries to resolve the service
627 // with that NsdServiceInfo, it will be done on the same interface.
628 // If they recreate the NsdServiceInfo themselves, resolution would be
629 // done on all interfaces as before T, which should also work.
630 info.setNetwork(null);
631 info.setInterfaceIndex(ifaceIdx);
632 break;
633 default:
634 info.setNetwork(new Network(netId));
635 }
636 }
637
paulhube186602022-04-12 07:18:23 +0000638 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
639 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
640 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
641 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
642 private String unescape(String s) {
643 StringBuilder sb = new StringBuilder(s.length());
644 for (int i = 0; i < s.length(); ++i) {
645 char c = s.charAt(i);
646 if (c == '\\') {
647 if (++i >= s.length()) {
648 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
649 break;
650 }
651 c = s.charAt(i);
652 if (c != '.' && c != '\\') {
653 if (i + 2 >= s.length()) {
654 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
655 break;
656 }
657 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
658 + (s.charAt(i + 2) - '0'));
659 i += 2;
660 }
661 }
662 sb.append(c);
663 }
664 return sb.toString();
665 }
666
Hugo Benichi803a2f02017-04-24 11:35:06 +0900667 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +0800668 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +0800669 this(ctx, handler, cleanupDelayMs, new Dependencies());
670 }
671
672 @VisibleForTesting
673 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +0000674 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900675 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900676 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700677 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +0800678 mMDnsManager = ctx.getSystemService(MDnsManager.class);
679 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Paul Hu4bd98ef2023-01-12 13:42:07 +0800680 if (deps.isMdnsDiscoveryManagerEnabled(ctx)) {
681 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
682 mMdnsSocketClient =
683 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
684 mMdnsDiscoveryManager =
685 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
686 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
687 } else {
688 mMdnsSocketProvider = null;
689 mMdnsSocketClient = null;
690 mMdnsDiscoveryManager = null;
691 }
692 }
693
694 /**
695 * Dependencies of NsdService, for injection in tests.
696 */
697 @VisibleForTesting
698 public static class Dependencies {
699 /**
700 * Check whether or not MdnsDiscoveryManager feature is enabled.
701 *
702 * @param context The global context information about an app environment.
703 * @return true if MdnsDiscoveryManager feature is enabled.
704 */
705 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
706 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
707 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
708 }
709
710 /**
711 * @see MdnsDiscoveryManager
712 */
713 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
714 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
715 return new MdnsDiscoveryManager(executorProvider, socketClient);
716 }
717
718 /**
719 * @see MdnsSocketProvider
720 */
721 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
722 return new MdnsSocketProvider(context, looper);
723 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700724 }
725
paulhu1b35e822022-04-08 14:48:41 +0800726 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900727 HandlerThread thread = new HandlerThread(TAG);
728 thread.start();
729 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +0800730 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700731 return service;
732 }
733
paulhu2b9ed952022-02-10 21:58:32 +0800734 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
735 private final StateMachine mStateMachine;
736
737 MDnsEventCallback(StateMachine sm) {
738 mStateMachine = sm;
739 }
740
741 @Override
742 public void onServiceRegistrationStatus(final RegistrationInfo status) {
743 mStateMachine.sendMessage(
744 MDNS_SERVICE_EVENT, status.result, status.id, status);
745 }
746
747 @Override
748 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
749 mStateMachine.sendMessage(
750 MDNS_SERVICE_EVENT, status.result, status.id, status);
751 }
752
753 @Override
754 public void onServiceResolutionStatus(final ResolutionInfo status) {
755 mStateMachine.sendMessage(
756 MDNS_SERVICE_EVENT, status.result, status.id, status);
757 }
758
759 @Override
760 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
761 mStateMachine.sendMessage(
762 MDNS_SERVICE_EVENT, status.result, status.id, status);
763 }
764
765 @Override
766 public int getInterfaceVersion() throws RemoteException {
767 return this.VERSION;
768 }
769
770 @Override
771 public String getInterfaceHash() throws RemoteException {
772 return this.HASH;
773 }
774 }
775
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900776 @Override
777 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900778 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900779 final INsdServiceConnector connector = new NsdServiceConnector();
780 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
781 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
782 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -0700783 }
784
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900785 private static class ListenerArgs {
786 public final NsdServiceConnector connector;
787 public final NsdServiceInfo serviceInfo;
788 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
789 this.connector = connector;
790 this.serviceInfo = serviceInfo;
791 }
792 }
793
794 private class NsdServiceConnector extends INsdServiceConnector.Stub
795 implements IBinder.DeathRecipient {
796 @Override
797 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
798 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
799 NsdManager.REGISTER_SERVICE, 0, listenerKey,
800 new ListenerArgs(this, serviceInfo)));
801 }
802
803 @Override
804 public void unregisterService(int listenerKey) {
805 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
806 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
807 new ListenerArgs(this, null)));
808 }
809
810 @Override
811 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
812 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
813 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
814 new ListenerArgs(this, serviceInfo)));
815 }
816
817 @Override
818 public void stopDiscovery(int listenerKey) {
819 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
820 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
821 }
822
823 @Override
824 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
825 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
826 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
827 new ListenerArgs(this, serviceInfo)));
828 }
829
830 @Override
831 public void startDaemon() {
832 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
833 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
834 }
835
836 @Override
837 public void binderDied() {
838 mNsdStateMachine.sendMessage(
839 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
840 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700841 }
842
Hugo Benichi912db992017-04-24 16:41:03 +0900843 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -0700844 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -0700845 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +0900846 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
847 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -0700848 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -0700849 }
850
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700851 private int getUniqueId() {
852 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
853 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700854 }
855
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700856 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +0900857 if (DBG) {
paulhub2225702021-11-17 09:35:33 +0800858 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700859 }
Hugo Benichi6d706442017-04-24 16:19:58 +0900860 String name = service.getServiceName();
861 String type = service.getServiceType();
862 int port = service.getPort();
863 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900864 final int registerInterface = getNetworkInterfaceIndex(service);
865 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +0800866 Log.e(TAG, "Interface to register service on not found");
867 return false;
868 }
869 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700870 }
871
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700872 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +0800873 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700874 }
875
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900876 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +0800877 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900878 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
879 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900880 Log.e(TAG, "Interface to discover service on not found");
881 return false;
882 }
paulhu2b9ed952022-02-10 21:58:32 +0800883 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700884 }
885
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700886 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +0800887 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700888 }
889
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700890 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900891 final String name = service.getServiceName();
892 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900893 final int resolveInterface = getNetworkInterfaceIndex(service);
894 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900895 Log.e(TAG, "Interface to resolve service on not found");
896 return false;
897 }
paulhu2b9ed952022-02-10 21:58:32 +0800898 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900899 }
900
901 /**
902 * Guess the interface to use to resolve or discover a service on a specific network.
903 *
904 * This is an imperfect guess, as for example the network may be gone or not yet fully
905 * registered. This is fine as failing is correct if the network is gone, and a client
906 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
907 * this is to support the legacy mdnsresponder implementation, which historically resolved
908 * services on an unspecified network.
909 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900910 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
911 final Network network = serviceInfo.getNetwork();
912 if (network == null) {
913 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
914 // provided by NsdService from discovery results, and the service was found on an
915 // interface that has no app-usable Network).
916 if (serviceInfo.getInterfaceIndex() != 0) {
917 return serviceInfo.getInterfaceIndex();
918 }
919 return IFACE_IDX_ANY;
920 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900921
922 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
923 if (cm == null) {
924 Log.wtf(TAG, "No ConnectivityManager for resolveService");
925 return IFACE_IDX_ANY;
926 }
927 final LinkProperties lp = cm.getLinkProperties(network);
928 if (lp == null) return IFACE_IDX_ANY;
929
930 // Only resolve on non-stacked interfaces
931 final NetworkInterface iface;
932 try {
933 iface = NetworkInterface.getByName(lp.getInterfaceName());
934 } catch (SocketException e) {
935 Log.e(TAG, "Error querying interface", e);
936 return IFACE_IDX_ANY;
937 }
938
939 if (iface == null) {
940 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
941 return IFACE_IDX_ANY;
942 }
943
944 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700945 }
946
947 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +0800948 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700949 }
950
paulhu2b9ed952022-02-10 21:58:32 +0800951 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
952 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700953 }
954
955 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +0800956 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700957 }
958
959 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -0700960 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +0800961 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700962
Irfan Sheriff75006652012-04-17 23:15:29 -0700963 for (ClientInfo client : mClients.values()) {
964 pw.println("Client Info");
965 pw.println(client);
966 }
967
968 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700969 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700970
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700971 /* Information tracked per client */
972 private class ClientInfo {
973
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700974 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900975 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700976 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700977 private NsdServiceInfo mResolvedService;
978
979 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +0900980 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700981
Dave Plattfeff2af2014-03-07 14:48:22 -0800982 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +0900983 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -0800984
Luke Huangf7277ed2021-07-12 21:15:10 +0800985 // The target SDK of this client < Build.VERSION_CODES.S
986 private boolean mIsLegacy = false;
987
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900988 private ClientInfo(INsdManagerCallback cb) {
989 mCb = cb;
paulhub2225702021-11-17 09:35:33 +0800990 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700991 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700992
993 @Override
994 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -0600995 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -0700996 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +0800997 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700998 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800999 int clientID = mClientIds.keyAt(i);
1000 sb.append("clientId ").append(clientID).
1001 append(" mDnsId ").append(mClientIds.valueAt(i)).
1002 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001003 }
1004 return sb.toString();
1005 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001006
Luke Huangf7277ed2021-07-12 21:15:10 +08001007 private boolean isLegacy() {
1008 return mIsLegacy;
1009 }
1010
1011 private void setLegacy() {
1012 mIsLegacy = true;
1013 }
1014
Dave Plattfeff2af2014-03-07 14:48:22 -08001015 // Remove any pending requests from the global map when we get rid of a client,
1016 // and send cancellations to the daemon.
1017 private void expungeAllRequests() {
1018 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +09001019 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -08001020 for (i = 0; i < mClientIds.size(); i++) {
1021 clientId = mClientIds.keyAt(i);
1022 globalId = mClientIds.valueAt(i);
1023 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001024 if (DBG) {
1025 Log.d(TAG, "Terminating client-ID " + clientId
1026 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1027 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001028 switch (mClientRequests.get(clientId)) {
1029 case NsdManager.DISCOVER_SERVICES:
1030 stopServiceDiscovery(globalId);
1031 break;
1032 case NsdManager.RESOLVE_SERVICE:
1033 stopResolveService(globalId);
1034 break;
1035 case NsdManager.REGISTER_SERVICE:
1036 unregisterService(globalId);
1037 break;
1038 default:
1039 break;
1040 }
1041 }
1042 mClientIds.clear();
1043 mClientRequests.clear();
1044 }
1045
Christopher Lane74411222014-04-25 18:39:07 -07001046 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
1047 // return the corresponding listener id. mDnsClient id is also called a global id.
1048 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001049 int idx = mClientIds.indexOfValue(globalId);
1050 if (idx < 0) {
1051 return idx;
Christopher Lane74411222014-04-25 18:39:07 -07001052 }
Hugo Benichid2552ae2017-04-11 14:42:47 +09001053 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -07001054 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001055
1056 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1057 try {
1058 mCb.onDiscoverServicesStarted(listenerKey, info);
1059 } catch (RemoteException e) {
1060 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1061 }
1062 }
1063
1064 void onDiscoverServicesFailed(int listenerKey, int error) {
1065 try {
1066 mCb.onDiscoverServicesFailed(listenerKey, error);
1067 } catch (RemoteException e) {
1068 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1069 }
1070 }
1071
1072 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1073 try {
1074 mCb.onServiceFound(listenerKey, info);
1075 } catch (RemoteException e) {
1076 Log.e(TAG, "Error calling onServiceFound(", e);
1077 }
1078 }
1079
1080 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1081 try {
1082 mCb.onServiceLost(listenerKey, info);
1083 } catch (RemoteException e) {
1084 Log.e(TAG, "Error calling onServiceLost(", e);
1085 }
1086 }
1087
1088 void onStopDiscoveryFailed(int listenerKey, int error) {
1089 try {
1090 mCb.onStopDiscoveryFailed(listenerKey, error);
1091 } catch (RemoteException e) {
1092 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1093 }
1094 }
1095
1096 void onStopDiscoverySucceeded(int listenerKey) {
1097 try {
1098 mCb.onStopDiscoverySucceeded(listenerKey);
1099 } catch (RemoteException e) {
1100 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1101 }
1102 }
1103
1104 void onRegisterServiceFailed(int listenerKey, int error) {
1105 try {
1106 mCb.onRegisterServiceFailed(listenerKey, error);
1107 } catch (RemoteException e) {
1108 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1109 }
1110 }
1111
1112 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1113 try {
1114 mCb.onRegisterServiceSucceeded(listenerKey, info);
1115 } catch (RemoteException e) {
1116 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1117 }
1118 }
1119
1120 void onUnregisterServiceFailed(int listenerKey, int error) {
1121 try {
1122 mCb.onUnregisterServiceFailed(listenerKey, error);
1123 } catch (RemoteException e) {
1124 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1125 }
1126 }
1127
1128 void onUnregisterServiceSucceeded(int listenerKey) {
1129 try {
1130 mCb.onUnregisterServiceSucceeded(listenerKey);
1131 } catch (RemoteException e) {
1132 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1133 }
1134 }
1135
1136 void onResolveServiceFailed(int listenerKey, int error) {
1137 try {
1138 mCb.onResolveServiceFailed(listenerKey, error);
1139 } catch (RemoteException e) {
1140 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1141 }
1142 }
1143
1144 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1145 try {
1146 mCb.onResolveServiceSucceeded(listenerKey, info);
1147 } catch (RemoteException e) {
1148 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1149 }
1150 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001151 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001152}