blob: 4086e4ec9baefcdac4d88a7fa11c4952a96393d2 [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;
21
paulhua262cc12019-08-12 16:25:11 +080022import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070023import android.content.Intent;
paulhub2225702021-11-17 09:35:33 +080024import android.content.pm.PackageManager;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090025import android.net.ConnectivityManager;
26import android.net.LinkProperties;
27import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080028import android.net.mdns.aidl.DiscoveryInfo;
29import android.net.mdns.aidl.GetAddressInfo;
30import android.net.mdns.aidl.IMDnsEventListener;
31import android.net.mdns.aidl.RegistrationInfo;
32import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070033import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090034import android.net.nsd.INsdManagerCallback;
35import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080036import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070037import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080038import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090039import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080040import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090041import android.os.IBinder;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090043import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070044import android.os.UserHandle;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090045import android.util.Log;
46import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070047import android.util.SparseArray;
Hugo Benichid2552ae2017-04-11 14:42:47 +090048import android.util.SparseIntArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070049
paulhua262cc12019-08-12 16:25:11 +080050import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080051import com.android.internal.util.State;
52import com.android.internal.util.StateMachine;
53
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054import java.io.FileDescriptor;
55import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070056import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090057import java.net.NetworkInterface;
58import java.net.SocketException;
59import java.net.UnknownHostException;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070060import java.util.HashMap;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070061
Irfan Sheriff77ec5582012-03-22 17:01:39 -070062/**
63 * Network Service Discovery Service handles remote service discovery operation requests by
64 * implementing the INsdManager interface.
65 *
66 * @hide
67 */
68public class NsdService extends INsdManager.Stub {
69 private static final String TAG = "NsdService";
70 private static final String MDNS_TAG = "mDnsConnector";
71
paulhu2b9ed952022-02-10 21:58:32 +080072 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +000073 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090074 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070075
Hugo Benichi32be63d2017-04-05 14:06:11 +090076 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +090077 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +080078 private final MDnsManager mMDnsManager;
79 private final MDnsEventCallback mMDnsEventCallback;
80 // WARNING : Accessing this value in any thread is not safe, it must only be changed in the
81 // state machine thread. If change this outside state machine, it will need to introduce
82 // synchronization.
83 private boolean mIsDaemonStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070084
85 /**
86 * Clients receiving asynchronous messages
87 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090088 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070090 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +090091 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070092
Luke Huang05298582021-06-13 16:52:05 +000093 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094
Hugo Benichi32be63d2017-04-05 14:06:11 +090095 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070096 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +080097 // The count of the connected legacy clients.
98 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070099
Irfan Sheriff75006652012-04-17 23:15:29 -0700100 private class NsdStateMachine extends StateMachine {
101
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700102 private final DefaultState mDefaultState = new DefaultState();
103 private final DisabledState mDisabledState = new DisabledState();
104 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700105
106 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700107 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900108 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700109 }
110
Luke Huang92860f92021-06-23 06:29:30 +0000111 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800112 if (mIsDaemonStarted) {
113 if (DBG) Log.d(TAG, "Daemon is already started.");
114 return;
115 }
116 mMDnsManager.registerEventListener(mMDnsEventCallback);
117 mMDnsManager.startDaemon();
118 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000119 maybeScheduleStop();
120 }
121
paulhu2b9ed952022-02-10 21:58:32 +0800122 private void maybeStopDaemon() {
123 if (!mIsDaemonStarted) {
124 if (DBG) Log.d(TAG, "Daemon has not been started.");
125 return;
126 }
127 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
128 mMDnsManager.stopDaemon();
129 mIsDaemonStarted = false;
130 }
131
Luke Huang92860f92021-06-23 06:29:30 +0000132 private boolean isAnyRequestActive() {
133 return mIdToClientInfoMap.size() != 0;
134 }
135
136 private void scheduleStop() {
137 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
138 }
139 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800140 // The native daemon should stay alive and can't be cleanup
141 // if any legacy client connected.
142 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000143 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000144 }
145 }
146
Luke Huang92860f92021-06-23 06:29:30 +0000147 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000148 this.removeMessages(NsdManager.DAEMON_CLEANUP);
149 }
150
Hugo Benichi803a2f02017-04-24 11:35:06 +0900151 NsdStateMachine(String name, Handler handler) {
152 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700153 addState(mDefaultState);
154 addState(mDisabledState, mDefaultState);
155 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800156 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900157 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700158 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700159 }
160
161 class DefaultState extends State {
162 @Override
163 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900164 final ClientInfo cInfo;
165 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700166 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900167 case NsdManager.REGISTER_CLIENT:
168 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
169 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
170 final INsdManagerCallback cb = arg.second;
171 try {
172 cb.asBinder().linkToDeath(arg.first, 0);
173 cInfo = new ClientInfo(cb);
174 mClients.put(arg.first, cInfo);
175 } catch (RemoteException e) {
176 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700177 }
178 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900179 case NsdManager.UNREGISTER_CLIENT:
180 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
181 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800182 if (cInfo != null) {
183 cInfo.expungeAllRequests();
Luke Huangf7277ed2021-07-12 21:15:10 +0800184 if (cInfo.isLegacy()) {
185 mLegacyClientCount -= 1;
186 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800187 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800188 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700189 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700190 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900191 cInfo = getClientInfoForReply(msg);
192 if (cInfo != null) {
193 cInfo.onDiscoverServicesFailed(
194 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
195 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700196 break;
197 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900198 cInfo = getClientInfoForReply(msg);
199 if (cInfo != null) {
200 cInfo.onStopDiscoveryFailed(
201 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
202 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700203 break;
204 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900205 cInfo = getClientInfoForReply(msg);
206 if (cInfo != null) {
207 cInfo.onRegisterServiceFailed(
208 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
209 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700210 break;
211 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900212 cInfo = getClientInfoForReply(msg);
213 if (cInfo != null) {
214 cInfo.onUnregisterServiceFailed(
215 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
216 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700217 break;
218 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900219 cInfo = getClientInfoForReply(msg);
220 if (cInfo != null) {
221 cInfo.onResolveServiceFailed(
222 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
223 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700224 break;
Luke Huang05298582021-06-13 16:52:05 +0000225 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800226 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000227 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800228 // This event should be only sent by the legacy (target SDK < S) clients.
229 // Mark the sending client as legacy.
230 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900231 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800232 if (cInfo != null) {
233 cancelStop();
234 cInfo.setLegacy();
235 mLegacyClientCount += 1;
236 maybeStartDaemon();
237 }
238 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700239 default:
paulhub2225702021-11-17 09:35:33 +0800240 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700241 return NOT_HANDLED;
242 }
243 return HANDLED;
244 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900245
246 private ClientInfo getClientInfoForReply(Message msg) {
247 final ListenerArgs args = (ListenerArgs) msg.obj;
248 return mClients.get(args.connector);
249 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700250 }
251
252 class DisabledState extends State {
253 @Override
254 public void enter() {
255 sendNsdStateChangeBroadcast(false);
256 }
257
258 @Override
259 public boolean processMessage(Message msg) {
260 switch (msg.what) {
261 case NsdManager.ENABLE:
262 transitionTo(mEnabledState);
263 break;
264 default:
265 return NOT_HANDLED;
266 }
267 return HANDLED;
268 }
269 }
270
271 class EnabledState extends State {
272 @Override
273 public void enter() {
274 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700275 }
276
277 @Override
278 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000279 // TODO: it is incorrect to stop the daemon without expunging all requests
280 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000281 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700282 }
283
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700284 private boolean requestLimitReached(ClientInfo clientInfo) {
285 if (clientInfo.mClientIds.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800286 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700287 return true;
288 }
289 return false;
290 }
291
Dave Plattfeff2af2014-03-07 14:48:22 -0800292 private void storeRequestMap(int clientId, int globalId, ClientInfo clientInfo, int what) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700293 clientInfo.mClientIds.put(clientId, globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -0800294 clientInfo.mClientRequests.put(clientId, what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700295 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000296 // Remove the cleanup event because here comes a new request.
297 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700298 }
299
300 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900301 clientInfo.mClientIds.delete(clientId);
302 clientInfo.mClientRequests.delete(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700303 mIdToClientInfoMap.remove(globalId);
Luke Huang05298582021-06-13 16:52:05 +0000304 maybeScheduleStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700305 }
306
Irfan Sheriff75006652012-04-17 23:15:29 -0700307 @Override
308 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900309 final ClientInfo clientInfo;
310 final int id;
311 final int clientId = msg.arg2;
312 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700313 switch (msg.what) {
Irfan Sheriff75006652012-04-17 23:15:29 -0700314 case NsdManager.DISABLE:
315 //TODO: cleanup clients
316 transitionTo(mDisabledState);
317 break;
318 case NsdManager.DISCOVER_SERVICES:
paulhub2225702021-11-17 09:35:33 +0800319 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900320 args = (ListenerArgs) msg.obj;
321 clientInfo = mClients.get(args.connector);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700322
323 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900324 clientInfo.onDiscoverServicesFailed(
325 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700326 break;
327 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700328
Luke Huang05298582021-06-13 16:52:05 +0000329 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700330 id = getUniqueId();
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900331 if (discoverServices(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700332 if (DBG) {
paulhub2225702021-11-17 09:35:33 +0800333 Log.d(TAG, "Discover " + msg.arg2 + " " + id
334 + args.serviceInfo.getServiceType());
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700335 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900336 storeRequestMap(clientId, id, clientInfo, msg.what);
337 clientInfo.onDiscoverServicesStarted(clientId, args.serviceInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700338 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700339 stopServiceDiscovery(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900340 clientInfo.onDiscoverServicesFailed(clientId,
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700341 NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700342 }
343 break;
344 case NsdManager.STOP_DISCOVERY:
paulhub2225702021-11-17 09:35:33 +0800345 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900346 args = (ListenerArgs) msg.obj;
347 clientInfo = mClients.get(args.connector);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700348
349 try {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900350 id = clientInfo.mClientIds.get(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700351 } catch (NullPointerException e) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900352 clientInfo.onStopDiscoveryFailed(
353 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700354 break;
355 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900356 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700357 if (stopServiceDiscovery(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900358 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700359 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900360 clientInfo.onStopDiscoveryFailed(
361 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700362 }
363 break;
364 case NsdManager.REGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800365 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900366 args = (ListenerArgs) msg.obj;
367 clientInfo = mClients.get(args.connector);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700368 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900369 clientInfo.onRegisterServiceFailed(
370 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700371 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700372 }
373
Luke Huang05298582021-06-13 16:52:05 +0000374 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700375 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900376 if (registerService(id, args.serviceInfo)) {
paulhub2225702021-11-17 09:35:33 +0800377 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900378 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700379 // Return success after mDns reports success
Irfan Sheriff75006652012-04-17 23:15:29 -0700380 } else {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700381 unregisterService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900382 clientInfo.onRegisterServiceFailed(
383 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700384 }
385 break;
386 case NsdManager.UNREGISTER_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800387 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900388 args = (ListenerArgs) msg.obj;
389 clientInfo = mClients.get(args.connector);
390 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800391 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700392 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700393 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900394 id = clientInfo.mClientIds.get(clientId);
395 removeRequestMap(clientId, id, clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700396 if (unregisterService(id)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900397 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700398 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900399 clientInfo.onUnregisterServiceFailed(
400 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700401 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700402 break;
403 case NsdManager.RESOLVE_SERVICE:
paulhub2225702021-11-17 09:35:33 +0800404 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900405 args = (ListenerArgs) msg.obj;
406 clientInfo = mClients.get(args.connector);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700407
408 if (clientInfo.mResolvedService != null) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900409 clientInfo.onResolveServiceFailed(
410 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
Irfan Sheriff75006652012-04-17 23:15:29 -0700411 break;
412 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700413
Luke Huang05298582021-06-13 16:52:05 +0000414 maybeStartDaemon();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700415 id = getUniqueId();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900416 if (resolveService(id, args.serviceInfo)) {
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700417 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900418 storeRequestMap(clientId, id, clientInfo, msg.what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700419 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900420 clientInfo.onResolveServiceFailed(
421 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Irfan Sheriff75006652012-04-17 23:15:29 -0700422 }
423 break;
paulhu2b9ed952022-02-10 21:58:32 +0800424 case MDNS_SERVICE_EVENT:
425 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900426 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700427 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700428 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700429 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900430 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700431 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900432 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700433 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700434
paulhu2b9ed952022-02-10 21:58:32 +0800435 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700436 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700437 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
438 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800439 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900440 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700441 }
442
443 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700444 int clientId = clientInfo.getClientId(id);
445 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700446 // This can happen because of race conditions. For example,
447 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
448 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800449 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
450 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900451 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700452 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900453 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800454 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900455 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700456 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800457 case IMDnsEventListener.SERVICE_FOUND: {
458 final DiscoveryInfo info = (DiscoveryInfo) obj;
459 final String name = info.serviceName;
460 final String type = info.registrationType;
461 servInfo = new NsdServiceInfo(name, type);
462 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900463 if (foundNetId == 0L) {
464 // Ignore services that do not have a Network: they are not usable
465 // by apps, as they would need privileged permissions to use
466 // interfaces that do not have an associated Network.
467 break;
468 }
469 servInfo.setNetwork(new Network(foundNetId));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900470 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700471 break;
paulhu2b9ed952022-02-10 21:58:32 +0800472 }
473 case IMDnsEventListener.SERVICE_LOST: {
474 final DiscoveryInfo info = (DiscoveryInfo) obj;
475 final String name = info.serviceName;
476 final String type = info.registrationType;
477 final int lostNetId = info.netId;
478 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900479 // The network could be null if it was torn down when the service is lost
480 // TODO: avoid returning null in that case, possibly by remembering found
481 // services on the same interface index and their network at the time
482 servInfo.setNetwork(lostNetId == 0 ? null : new Network(lostNetId));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900483 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700484 break;
paulhu2b9ed952022-02-10 21:58:32 +0800485 }
486 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900487 clientInfo.onDiscoverServicesFailed(
488 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700489 break;
paulhu2b9ed952022-02-10 21:58:32 +0800490 case IMDnsEventListener.SERVICE_REGISTERED: {
491 final RegistrationInfo info = (RegistrationInfo) obj;
492 final String name = info.serviceName;
493 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900494 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700495 break;
paulhu2b9ed952022-02-10 21:58:32 +0800496 }
497 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900498 clientInfo.onRegisterServiceFailed(
499 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700500 break;
paulhu2b9ed952022-02-10 21:58:32 +0800501 case IMDnsEventListener.SERVICE_RESOLVED: {
502 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700503 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800504 final String fullName = info.serviceFullName;
505 while (index < fullName.length() && fullName.charAt(index) != '.') {
506 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700507 ++index;
508 }
509 ++index;
510 }
paulhu2b9ed952022-02-10 21:58:32 +0800511 if (index >= fullName.length()) {
512 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700513 break;
514 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900515
paulhu2b9ed952022-02-10 21:58:32 +0800516 String name = fullName.substring(0, index);
517 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700518 String type = rest.replace(".local.", "");
519
520 clientInfo.mResolvedService.setServiceName(name);
521 clientInfo.mResolvedService.setServiceType(type);
paulhu2b9ed952022-02-10 21:58:32 +0800522 clientInfo.mResolvedService.setPort(info.port);
523 clientInfo.mResolvedService.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900524 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700525
526 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800527 removeRequestMap(clientId, id, clientInfo);
528
paulhu2b9ed952022-02-10 21:58:32 +0800529 final int id2 = getUniqueId();
530 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800531 storeRequestMap(clientId, id2, clientInfo, NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800532 } else {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900533 clientInfo.onResolveServiceFailed(
534 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700535 clientInfo.mResolvedService = null;
536 }
537 break;
paulhu2b9ed952022-02-10 21:58:32 +0800538 }
539 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700540 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700541 stopResolveService(id);
542 removeRequestMap(clientId, id, clientInfo);
543 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900544 clientInfo.onResolveServiceFailed(
545 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700546 break;
paulhu2b9ed952022-02-10 21:58:32 +0800547 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700548 /* NNN resolveId errorCode */
549 stopGetAddrInfo(id);
550 removeRequestMap(clientId, id, clientInfo);
551 clientInfo.mResolvedService = null;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900552 clientInfo.onResolveServiceFailed(
553 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700554 break;
paulhu2b9ed952022-02-10 21:58:32 +0800555 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900556 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +0800557 final GetAddressInfo info = (GetAddressInfo) obj;
558 final String address = info.address;
559 final int netId = info.netId;
560 final Network network = netId == NETID_UNSET ? null : new Network(netId);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900561 InetAddress serviceHost = null;
562 try {
paulhu2b9ed952022-02-10 21:58:32 +0800563 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900564 } catch (UnknownHostException e) {
565 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
566 }
567
568 // If the resolved service is on an interface without a network, consider it
569 // as a failure: it would not be usable by apps as they would need
570 // privileged permissions.
571 if (network != null && serviceHost != null) {
572 clientInfo.mResolvedService.setHost(serviceHost);
573 clientInfo.mResolvedService.setNetwork(network);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900574 clientInfo.onResolveServiceSucceeded(
575 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900576 } else {
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 }
580 stopGetAddrInfo(id);
581 removeRequestMap(clientId, id, clientInfo);
582 clientInfo.mResolvedService = null;
583 break;
paulhu2b9ed952022-02-10 21:58:32 +0800584 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700585 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900586 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700587 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900588 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700589 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700590 }
591 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700592
Hugo Benichi803a2f02017-04-24 11:35:06 +0900593 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +0800594 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Luke Huang05298582021-06-13 16:52:05 +0000595 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900596 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +0900597 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +0800599 mMDnsManager = ctx.getSystemService(MDnsManager.class);
600 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700601 }
602
paulhu1b35e822022-04-08 14:48:41 +0800603 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900604 HandlerThread thread = new HandlerThread(TAG);
605 thread.start();
606 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +0800607 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700608 return service;
609 }
610
paulhu2b9ed952022-02-10 21:58:32 +0800611 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
612 private final StateMachine mStateMachine;
613
614 MDnsEventCallback(StateMachine sm) {
615 mStateMachine = sm;
616 }
617
618 @Override
619 public void onServiceRegistrationStatus(final RegistrationInfo status) {
620 mStateMachine.sendMessage(
621 MDNS_SERVICE_EVENT, status.result, status.id, status);
622 }
623
624 @Override
625 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
626 mStateMachine.sendMessage(
627 MDNS_SERVICE_EVENT, status.result, status.id, status);
628 }
629
630 @Override
631 public void onServiceResolutionStatus(final ResolutionInfo status) {
632 mStateMachine.sendMessage(
633 MDNS_SERVICE_EVENT, status.result, status.id, status);
634 }
635
636 @Override
637 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
638 mStateMachine.sendMessage(
639 MDNS_SERVICE_EVENT, status.result, status.id, status);
640 }
641
642 @Override
643 public int getInterfaceVersion() throws RemoteException {
644 return this.VERSION;
645 }
646
647 @Override
648 public String getInterfaceHash() throws RemoteException {
649 return this.HASH;
650 }
651 }
652
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900653 @Override
654 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +0900655 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900656 final INsdServiceConnector connector = new NsdServiceConnector();
657 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
658 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
659 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -0700660 }
661
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900662 private static class ListenerArgs {
663 public final NsdServiceConnector connector;
664 public final NsdServiceInfo serviceInfo;
665 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
666 this.connector = connector;
667 this.serviceInfo = serviceInfo;
668 }
669 }
670
671 private class NsdServiceConnector extends INsdServiceConnector.Stub
672 implements IBinder.DeathRecipient {
673 @Override
674 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
675 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
676 NsdManager.REGISTER_SERVICE, 0, listenerKey,
677 new ListenerArgs(this, serviceInfo)));
678 }
679
680 @Override
681 public void unregisterService(int listenerKey) {
682 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
683 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
684 new ListenerArgs(this, null)));
685 }
686
687 @Override
688 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
689 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
690 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
691 new ListenerArgs(this, serviceInfo)));
692 }
693
694 @Override
695 public void stopDiscovery(int listenerKey) {
696 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
697 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
698 }
699
700 @Override
701 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
702 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
703 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
704 new ListenerArgs(this, serviceInfo)));
705 }
706
707 @Override
708 public void startDaemon() {
709 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
710 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
711 }
712
713 @Override
714 public void binderDied() {
715 mNsdStateMachine.sendMessage(
716 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
717 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700718 }
719
Hugo Benichi912db992017-04-24 16:41:03 +0900720 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -0700721 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -0700722 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +0900723 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
724 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -0700725 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -0700726 }
727
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700728 private int getUniqueId() {
729 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
730 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700731 }
732
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700733 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +0900734 if (DBG) {
paulhub2225702021-11-17 09:35:33 +0800735 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700736 }
Hugo Benichi6d706442017-04-24 16:19:58 +0900737 String name = service.getServiceName();
738 String type = service.getServiceType();
739 int port = service.getPort();
740 byte[] textRecord = service.getTxtRecord();
paulhu2b9ed952022-02-10 21:58:32 +0800741 return mMDnsManager.registerService(regId, name, type, port, textRecord, IFACE_IDX_ANY);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700742 }
743
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700744 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +0800745 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700746 }
747
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900748 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
749 final Network network = serviceInfo.getNetwork();
paulhu2b9ed952022-02-10 21:58:32 +0800750 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900751 final int discoverInterface = getNetworkInterfaceIndex(network);
752 if (network != null && discoverInterface == IFACE_IDX_ANY) {
753 Log.e(TAG, "Interface to discover service on not found");
754 return false;
755 }
paulhu2b9ed952022-02-10 21:58:32 +0800756 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700757 }
758
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700759 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +0800760 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700761 }
762
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700763 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900764 final String name = service.getServiceName();
765 final String type = service.getServiceType();
766 final Network network = service.getNetwork();
767 final int resolveInterface = getNetworkInterfaceIndex(network);
768 if (network != null && resolveInterface == IFACE_IDX_ANY) {
769 Log.e(TAG, "Interface to resolve service on not found");
770 return false;
771 }
paulhu2b9ed952022-02-10 21:58:32 +0800772 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900773 }
774
775 /**
776 * Guess the interface to use to resolve or discover a service on a specific network.
777 *
778 * This is an imperfect guess, as for example the network may be gone or not yet fully
779 * registered. This is fine as failing is correct if the network is gone, and a client
780 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
781 * this is to support the legacy mdnsresponder implementation, which historically resolved
782 * services on an unspecified network.
783 */
784 private int getNetworkInterfaceIndex(Network network) {
785 if (network == null) return IFACE_IDX_ANY;
786
787 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
788 if (cm == null) {
789 Log.wtf(TAG, "No ConnectivityManager for resolveService");
790 return IFACE_IDX_ANY;
791 }
792 final LinkProperties lp = cm.getLinkProperties(network);
793 if (lp == null) return IFACE_IDX_ANY;
794
795 // Only resolve on non-stacked interfaces
796 final NetworkInterface iface;
797 try {
798 iface = NetworkInterface.getByName(lp.getInterfaceName());
799 } catch (SocketException e) {
800 Log.e(TAG, "Error querying interface", e);
801 return IFACE_IDX_ANY;
802 }
803
804 if (iface == null) {
805 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
806 return IFACE_IDX_ANY;
807 }
808
809 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700810 }
811
812 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +0800813 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700814 }
815
paulhu2b9ed952022-02-10 21:58:32 +0800816 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
817 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700818 }
819
820 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +0800821 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700822 }
823
824 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -0700825 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhub2225702021-11-17 09:35:33 +0800826 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
827 != PackageManager.PERMISSION_GRANTED) {
828 pw.println("Permission Denial: can't dump " + TAG
829 + " due to missing android.permission.DUMP permission");
830 return;
831 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700832
Irfan Sheriff75006652012-04-17 23:15:29 -0700833 for (ClientInfo client : mClients.values()) {
834 pw.println("Client Info");
835 pw.println(client);
836 }
837
838 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700839 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700840
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700841 /* Information tracked per client */
842 private class ClientInfo {
843
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700844 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900845 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700846 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700847 private NsdServiceInfo mResolvedService;
848
849 /* A map from client id to unique id sent to mDns */
Hugo Benichid2552ae2017-04-11 14:42:47 +0900850 private final SparseIntArray mClientIds = new SparseIntArray();
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700851
Dave Plattfeff2af2014-03-07 14:48:22 -0800852 /* A map from client id to the type of the request we had received */
Hugo Benichid2552ae2017-04-11 14:42:47 +0900853 private final SparseIntArray mClientRequests = new SparseIntArray();
Dave Plattfeff2af2014-03-07 14:48:22 -0800854
Luke Huangf7277ed2021-07-12 21:15:10 +0800855 // The target SDK of this client < Build.VERSION_CODES.S
856 private boolean mIsLegacy = false;
857
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900858 private ClientInfo(INsdManagerCallback cb) {
859 mCb = cb;
paulhub2225702021-11-17 09:35:33 +0800860 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700861 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700862
863 @Override
864 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -0600865 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -0700866 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Luke Huangf7277ed2021-07-12 21:15:10 +0800867 sb.append("mIsLegacy ").append(mIsLegacy).append("\n");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700868 for(int i = 0; i< mClientIds.size(); i++) {
Dave Plattfeff2af2014-03-07 14:48:22 -0800869 int clientID = mClientIds.keyAt(i);
870 sb.append("clientId ").append(clientID).
871 append(" mDnsId ").append(mClientIds.valueAt(i)).
872 append(" type ").append(mClientRequests.get(clientID)).append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -0700873 }
874 return sb.toString();
875 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800876
Luke Huangf7277ed2021-07-12 21:15:10 +0800877 private boolean isLegacy() {
878 return mIsLegacy;
879 }
880
881 private void setLegacy() {
882 mIsLegacy = true;
883 }
884
Dave Plattfeff2af2014-03-07 14:48:22 -0800885 // Remove any pending requests from the global map when we get rid of a client,
886 // and send cancellations to the daemon.
887 private void expungeAllRequests() {
888 int globalId, clientId, i;
Hugo Benichid2552ae2017-04-11 14:42:47 +0900889 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Dave Plattfeff2af2014-03-07 14:48:22 -0800890 for (i = 0; i < mClientIds.size(); i++) {
891 clientId = mClientIds.keyAt(i);
892 globalId = mClientIds.valueAt(i);
893 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +0800894 if (DBG) {
895 Log.d(TAG, "Terminating client-ID " + clientId
896 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
897 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800898 switch (mClientRequests.get(clientId)) {
899 case NsdManager.DISCOVER_SERVICES:
900 stopServiceDiscovery(globalId);
901 break;
902 case NsdManager.RESOLVE_SERVICE:
903 stopResolveService(globalId);
904 break;
905 case NsdManager.REGISTER_SERVICE:
906 unregisterService(globalId);
907 break;
908 default:
909 break;
910 }
911 }
912 mClientIds.clear();
913 mClientRequests.clear();
914 }
915
Christopher Lane74411222014-04-25 18:39:07 -0700916 // mClientIds is a sparse array of listener id -> mDnsClient id. For a given mDnsClient id,
917 // return the corresponding listener id. mDnsClient id is also called a global id.
918 private int getClientId(final int globalId) {
Hugo Benichid2552ae2017-04-11 14:42:47 +0900919 int idx = mClientIds.indexOfValue(globalId);
920 if (idx < 0) {
921 return idx;
Christopher Lane74411222014-04-25 18:39:07 -0700922 }
Hugo Benichid2552ae2017-04-11 14:42:47 +0900923 return mClientIds.keyAt(idx);
Christopher Lane74411222014-04-25 18:39:07 -0700924 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900925
926 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
927 try {
928 mCb.onDiscoverServicesStarted(listenerKey, info);
929 } catch (RemoteException e) {
930 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
931 }
932 }
933
934 void onDiscoverServicesFailed(int listenerKey, int error) {
935 try {
936 mCb.onDiscoverServicesFailed(listenerKey, error);
937 } catch (RemoteException e) {
938 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
939 }
940 }
941
942 void onServiceFound(int listenerKey, NsdServiceInfo info) {
943 try {
944 mCb.onServiceFound(listenerKey, info);
945 } catch (RemoteException e) {
946 Log.e(TAG, "Error calling onServiceFound(", e);
947 }
948 }
949
950 void onServiceLost(int listenerKey, NsdServiceInfo info) {
951 try {
952 mCb.onServiceLost(listenerKey, info);
953 } catch (RemoteException e) {
954 Log.e(TAG, "Error calling onServiceLost(", e);
955 }
956 }
957
958 void onStopDiscoveryFailed(int listenerKey, int error) {
959 try {
960 mCb.onStopDiscoveryFailed(listenerKey, error);
961 } catch (RemoteException e) {
962 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
963 }
964 }
965
966 void onStopDiscoverySucceeded(int listenerKey) {
967 try {
968 mCb.onStopDiscoverySucceeded(listenerKey);
969 } catch (RemoteException e) {
970 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
971 }
972 }
973
974 void onRegisterServiceFailed(int listenerKey, int error) {
975 try {
976 mCb.onRegisterServiceFailed(listenerKey, error);
977 } catch (RemoteException e) {
978 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
979 }
980 }
981
982 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
983 try {
984 mCb.onRegisterServiceSucceeded(listenerKey, info);
985 } catch (RemoteException e) {
986 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
987 }
988 }
989
990 void onUnregisterServiceFailed(int listenerKey, int error) {
991 try {
992 mCb.onUnregisterServiceFailed(listenerKey, error);
993 } catch (RemoteException e) {
994 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
995 }
996 }
997
998 void onUnregisterServiceSucceeded(int listenerKey) {
999 try {
1000 mCb.onUnregisterServiceSucceeded(listenerKey);
1001 } catch (RemoteException e) {
1002 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1003 }
1004 }
1005
1006 void onResolveServiceFailed(int listenerKey, int error) {
1007 try {
1008 mCb.onResolveServiceFailed(listenerKey, error);
1009 } catch (RemoteException e) {
1010 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1011 }
1012 }
1013
1014 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1015 try {
1016 mCb.onResolveServiceSucceeded(listenerKey, info);
1017 } catch (RemoteException e) {
1018 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1019 }
1020 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001021 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001022}