blob: e6b6074abf9c4f432c89d44bf72284bd0f73af17 [file] [log] [blame]
San Mehat67bd2cd2010-01-12 12:18:49 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
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
San Mehat67bd2cd2010-01-12 12:18:49 -080019import android.net.LocalSocket;
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070020import android.net.LocalSocketAddress;
Lorenzo Colitti7421a012013-08-20 22:51:24 +090021import android.os.Build;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070022import android.os.Handler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070023import android.os.Looper;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070024import android.os.Message;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080025import android.os.PowerManager;
San Mehat67bd2cd2010-01-12 12:18:49 -080026import android.os.SystemClock;
Robert Greenwalt470fd722012-01-18 12:51:15 -080027import android.util.LocalLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080028import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080029
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080030import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey8948c012015-11-03 12:33:54 -080031import com.android.internal.util.Preconditions;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080032import com.google.android.collect.Lists;
33
Robert Greenwalt470fd722012-01-18 12:51:15 -080034import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080035import java.io.IOException;
36import java.io.InputStream;
37import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080038import java.io.PrintWriter;
Elliott Hughesd396a442013-06-28 16:24:48 -070039import java.nio.charset.StandardCharsets;
San Mehat67bd2cd2010-01-12 12:18:49 -080040import java.util.ArrayList;
Robert Greenwalt470007f2012-02-07 11:36:55 -080041import java.util.concurrent.atomic.AtomicInteger;
Robert Greenwaltef215992012-06-05 11:48:40 -070042import java.util.concurrent.ArrayBlockingQueue;
43import java.util.concurrent.BlockingQueue;
44import java.util.concurrent.TimeUnit;
Robert Greenwalt470007f2012-02-07 11:36:55 -080045import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080046
47/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080048 * Generic connector class for interfacing with a native daemon which uses the
49 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080050 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070051final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Robert Greenwalt7f44ff82014-05-07 23:49:08 -070052 private final static boolean VDBG = false;
53
Jeff Sharkey31c6e482011-11-18 17:09:01 -080054 private final String TAG;
55
56 private String mSocket;
57 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080058 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080059
Jeff Sharkey48877892015-03-18 11:27:19 -070060 private volatile boolean mDebug = false;
Jeff Sharkey8948c012015-11-03 12:33:54 -080061 private volatile Object mWarnIfHeld;
Jeff Sharkey48877892015-03-18 11:27:19 -070062
Robert Greenwalt470007f2012-02-07 11:36:55 -080063 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080064
Dianne Hackborn77b987f2014-02-26 16:20:52 -080065 private final PowerManager.WakeLock mWakeLock;
66
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070067 private final Looper mLooper;
68
San Mehat67bd2cd2010-01-12 12:18:49 -080069 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080070 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080071
Robert Greenwalt470007f2012-02-07 11:36:55 -080072 private AtomicInteger mSequenceNumber;
73
Jeff Sharkey14cbe522015-07-08 14:06:37 -070074 private static final long DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070075 private static final long WARN_EXECUTE_DELAY_MS = 500; /* .5 sec */
Robert Greenwalt470007f2012-02-07 11:36:55 -080076
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070077 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080078 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070079
Kenny Root961aa8c2010-03-22 18:02:45 -070080 private final int BUFFER_SIZE = 4096;
81
Jeff Sharkey31c6e482011-11-18 17:09:01 -080082 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Dianne Hackborn77b987f2014-02-26 16:20:52 -080083 int responseQueueSize, String logTag, int maxLogSize, PowerManager.WakeLock wl) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070084 this(callbacks, socket, responseQueueSize, logTag, maxLogSize, wl,
85 FgThread.get().getLooper());
86 }
87
88 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
89 int responseQueueSize, String logTag, int maxLogSize, PowerManager.WakeLock wl,
90 Looper looper) {
San Mehat67bd2cd2010-01-12 12:18:49 -080091 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080092 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080093 mResponseQueue = new ResponseQueue(responseQueueSize);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080094 mWakeLock = wl;
95 if (mWakeLock != null) {
96 mWakeLock.setReferenceCounted(true);
97 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070098 mLooper = looper;
Robert Greenwalt470007f2012-02-07 11:36:55 -080099 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800100 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -0800101 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -0800102 }
103
Jeff Sharkey48877892015-03-18 11:27:19 -0700104 /**
105 * Enable Set debugging mode, which causes messages to also be written to both
106 * {@link Slog} in addition to internal log.
107 */
108 public void setDebug(boolean debug) {
109 mDebug = debug;
110 }
111
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800112 /**
Jeff Sharkey8948c012015-11-03 12:33:54 -0800113 * Yell loudly if someone tries making future {@link #execute(Command)}
114 * calls while holding a lock on the given object.
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800115 */
Jeff Sharkey8948c012015-11-03 12:33:54 -0800116 public void setWarnIfHeld(Object warnIfHeld) {
117 Preconditions.checkState(mWarnIfHeld == null);
118 mWarnIfHeld = Preconditions.checkNotNull(warnIfHeld);
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800119 }
120
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700121 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -0800122 public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700123 mCallbackHandler = new Handler(mLooper, this);
San Mehat67bd2cd2010-01-12 12:18:49 -0800124
125 while (true) {
126 try {
127 listenToSocket();
128 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800129 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800130 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -0800131 }
132 }
133 }
134
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700135 @Override
136 public boolean handleMessage(Message msg) {
137 String event = (String) msg.obj;
138 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700139 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800140 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700141 }
142 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800143 loge("Error handling '" + event + "': " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800144 } finally {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700145 if (mCallbacks.onCheckHoldWakeLock(msg.what) && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800146 mWakeLock.release();
147 }
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700148 }
149 return true;
150 }
151
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900152 private LocalSocketAddress determineSocketAddress() {
153 // If we're testing, set up a socket in a namespace that's accessible to test code.
154 // In order to ensure that unprivileged apps aren't able to impersonate native daemons on
155 // production devices, even if said native daemons ill-advisedly pick a socket name that
156 // starts with __test__, only allow this on debug builds.
157 if (mSocket.startsWith("__test__") && Build.IS_DEBUGGABLE) {
158 return new LocalSocketAddress(mSocket);
159 } else {
160 return new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);
161 }
162 }
163
San Mehat4c27e0e2010-01-29 05:22:17 -0800164 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700165 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800166
167 try {
168 socket = new LocalSocket();
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900169 LocalSocketAddress address = determineSocketAddress();
San Mehat67bd2cd2010-01-12 12:18:49 -0800170
171 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800172
173 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800174 synchronized (mDaemonLock) {
175 mOutputStream = socket.getOutputStream();
176 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800177
anga030bc882011-02-01 14:10:25 +0100178 mCallbacks.onDaemonConnected();
179
Kenny Root961aa8c2010-03-22 18:02:45 -0700180 byte[] buffer = new byte[BUFFER_SIZE];
181 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800182
183 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700184 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800185 if (count < 0) {
186 loge("got " + count + " reading with start = " + start);
187 break;
188 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800189
Kenny Root12da9d72010-09-02 22:18:14 -0700190 // Add our starting point to the count and reset the start.
191 count += start;
192 start = 0;
193
San Mehat67bd2cd2010-01-12 12:18:49 -0800194 for (int i = 0; i < count; i++) {
195 if (buffer[i] == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800196 // Note - do not log this raw message since it may contain
197 // sensitive data
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800198 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700199 buffer, start, i - start, StandardCharsets.UTF_8);
San Mehat67bd2cd2010-01-12 12:18:49 -0800200
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800201 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800202 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800203 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
204 rawEvent);
Paul Lawrencec38182f2014-11-11 12:23:22 -0800205
206 log("RCV <- {" + event + "}");
207
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800208 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800209 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn4590e522014-03-24 13:36:46 -0700210 if (mCallbacks.onCheckHoldWakeLock(event.getCode())
211 && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800212 mWakeLock.acquire();
213 releaseWl = true;
214 }
215 if (mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
216 event.getCode(), event.getRawEvent()))) {
217 releaseWl = false;
218 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800219 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800220 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800221 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800222 } catch (IllegalArgumentException e) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800223 log("Problem parsing message " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800224 } finally {
225 if (releaseWl) {
226 mWakeLock.acquire();
227 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800228 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800229
San Mehat67bd2cd2010-01-12 12:18:49 -0800230 start = i + 1;
231 }
232 }
Paul Lawrencec38182f2014-11-11 12:23:22 -0800233
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800234 if (start == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800235 log("RCV incomplete");
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800236 }
Kenny Root12da9d72010-09-02 22:18:14 -0700237
238 // We should end at the amount we read. If not, compact then
239 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700240 if (start != count) {
241 final int remaining = BUFFER_SIZE - start;
242 System.arraycopy(buffer, start, buffer, 0, remaining);
243 start = remaining;
244 } else {
245 start = 0;
246 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800247 }
248 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800249 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800250 throw ex;
251 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700252 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800253 if (mOutputStream != null) {
254 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800255 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800256 mOutputStream.close();
257 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800258 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800259 }
260 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800261 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800262 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800263
San Mehat4c27e0e2010-01-29 05:22:17 -0800264 try {
265 if (socket != null) {
266 socket.close();
267 }
268 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800269 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800270 }
271 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800272 }
273
San Mehat67bd2cd2010-01-12 12:18:49 -0800274 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700275 * Wrapper around argument that indicates it's sensitive and shouldn't be
276 * logged.
277 */
278 public static class SensitiveArg {
279 private final Object mArg;
280
281 public SensitiveArg(Object arg) {
282 mArg = arg;
283 }
284
285 @Override
286 public String toString() {
287 return String.valueOf(mArg);
288 }
289 }
290
291 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800292 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800293 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700294 @VisibleForTesting
295 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
296 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800297 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800298 throw new IllegalArgumentException("Unexpected command: " + cmd);
299 }
300 if (cmd.indexOf(' ') >= 0) {
301 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700302 }
303
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700304 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
305 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800306 for (Object arg : args) {
307 final String argString = String.valueOf(arg);
308 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800309 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700310 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800311
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700312 rawBuilder.append(' ');
313 logBuilder.append(' ');
314
315 appendEscaped(rawBuilder, argString);
316 if (arg instanceof SensitiveArg) {
317 logBuilder.append("[scrubbed]");
318 } else {
319 appendEscaped(logBuilder, argString);
320 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800321 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700322
323 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800324 }
San Mehatdeba6932010-01-20 15:14:31 -0800325
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700326 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800327 * Issue the given command to the native daemon and return a single expected
328 * response.
329 *
330 * @throws NativeDaemonConnectorException when problem communicating with
331 * native daemon, or if the response matches
332 * {@link NativeDaemonEvent#isClassClientError()} or
333 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800334 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800335 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
336 return execute(cmd.mCmd, cmd.mArguments.toArray());
337 }
338
339 /**
340 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800341 * response. Any arguments must be separated from base command so they can
342 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800343 *
344 * @throws NativeDaemonConnectorException when problem communicating with
345 * native daemon, or if the response matches
346 * {@link NativeDaemonEvent#isClassClientError()} or
347 * {@link NativeDaemonEvent#isClassServerError()}.
348 */
349 public NativeDaemonEvent execute(String cmd, Object... args)
350 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700351 return execute(DEFAULT_TIMEOUT, cmd, args);
352 }
353
354 public NativeDaemonEvent execute(long timeoutMs, String cmd, Object... args)
355 throws NativeDaemonConnectorException {
356 final NativeDaemonEvent[] events = executeForList(timeoutMs, cmd, args);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800357 if (events.length != 1) {
358 throw new NativeDaemonConnectorException(
359 "Expected exactly one response, but received " + events.length);
360 }
361 return events[0];
362 }
363
364 /**
365 * Issue the given command to the native daemon and return any
366 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
367 * final terminal response.
368 *
369 * @throws NativeDaemonConnectorException when problem communicating with
370 * native daemon, or if the response matches
371 * {@link NativeDaemonEvent#isClassClientError()} or
372 * {@link NativeDaemonEvent#isClassServerError()}.
373 */
374 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
375 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
376 }
377
378 /**
379 * Issue the given command to the native daemon and return any
380 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800381 * final terminal response. Any arguments must be separated from base
382 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800383 *
384 * @throws NativeDaemonConnectorException when problem communicating with
385 * native daemon, or if the response matches
386 * {@link NativeDaemonEvent#isClassClientError()} or
387 * {@link NativeDaemonEvent#isClassServerError()}.
388 */
389 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800390 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700391 return executeForList(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800392 }
San Mehatdeba6932010-01-20 15:14:31 -0800393
Robert Greenwalt470007f2012-02-07 11:36:55 -0800394 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800395 * Issue the given command to the native daemon and return any {@linke
396 * NativeDaemonEvent@isClassContinue()} responses, including the final
397 * terminal response. Note that the timeout does not count time in deep
398 * sleep. Any arguments must be separated from base command so they can be
399 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800400 *
401 * @throws NativeDaemonConnectorException when problem communicating with
402 * native daemon, or if the response matches
403 * {@link NativeDaemonEvent#isClassClientError()} or
404 * {@link NativeDaemonEvent#isClassServerError()}.
405 */
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700406 public NativeDaemonEvent[] executeForList(long timeoutMs, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800407 throws NativeDaemonConnectorException {
Jeff Sharkey8948c012015-11-03 12:33:54 -0800408 if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
409 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
410 + Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800411 }
412
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700413 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700414
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700415 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700416
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700417 final StringBuilder rawBuilder = new StringBuilder();
418 final StringBuilder logBuilder = new StringBuilder();
419 final int sequenceNumber = mSequenceNumber.incrementAndGet();
420
421 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
422
423 final String rawCmd = rawBuilder.toString();
424 final String logCmd = logBuilder.toString();
425
Robert Greenwaltd1925982012-03-12 15:37:40 -0700426 log("SND -> {" + logCmd + "}");
427
Robert Greenwaltd1925982012-03-12 15:37:40 -0700428 synchronized (mDaemonLock) {
429 if (mOutputStream == null) {
430 throw new NativeDaemonConnectorException("missing output stream");
431 } else {
432 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700433 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700434 } catch (IOException e) {
435 throw new NativeDaemonConnectorException("problem sending command", e);
436 }
437 }
438 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800439
440 NativeDaemonEvent event = null;
441 do {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700442 event = mResponseQueue.remove(sequenceNumber, timeoutMs, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800443 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700444 loge("timed-out waiting for response to " + logCmd);
Todd Kennedy8101ee62015-06-23 13:35:28 -0700445 throw new NativeDaemonTimeoutException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800446 }
Robert Greenwalt7f44ff82014-05-07 23:49:08 -0700447 if (VDBG) log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800448 events.add(event);
449 } while (event.isClassContinue());
450
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700451 final long endTime = SystemClock.elapsedRealtime();
452 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
453 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
454 }
455
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800456 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700457 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800458 }
459 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700460 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800461 }
462
463 return events.toArray(new NativeDaemonEvent[events.size()]);
464 }
465
466 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800467 * Append the given argument to {@link StringBuilder}, escaping as needed,
468 * and surrounding with quotes when it contains spaces.
469 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800470 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800471 static void appendEscaped(StringBuilder builder, String arg) {
472 final boolean hasSpaces = arg.indexOf(' ') >= 0;
473 if (hasSpaces) {
474 builder.append('"');
475 }
476
477 final int length = arg.length();
478 for (int i = 0; i < length; i++) {
479 final char c = arg.charAt(i);
480
481 if (c == '"') {
482 builder.append("\\\"");
483 } else if (c == '\\') {
484 builder.append("\\\\");
485 } else {
486 builder.append(c);
487 }
488 }
489
490 if (hasSpaces) {
491 builder.append('"');
492 }
493 }
494
495 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
496 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
497 super(command, event);
498 }
499
500 @Override
501 public IllegalArgumentException rethrowAsParcelableException() {
502 throw new IllegalArgumentException(getMessage(), this);
503 }
504 }
505
506 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
507 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
508 super(command, event);
509 }
San Mehatdeba6932010-01-20 15:14:31 -0800510 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700511
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800512 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800513 * Command builder that handles argument list building. Any arguments must
514 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800515 */
516 public static class Command {
517 private String mCmd;
518 private ArrayList<Object> mArguments = Lists.newArrayList();
519
520 public Command(String cmd, Object... args) {
521 mCmd = cmd;
522 for (Object arg : args) {
523 appendArg(arg);
524 }
525 }
526
527 public Command appendArg(Object arg) {
528 mArguments.add(arg);
529 return this;
530 }
531 }
532
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700533 /** {@inheritDoc} */
534 public void monitor() {
535 synchronized (mDaemonLock) { }
536 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800537
538 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
539 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800540 pw.println();
541 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800542 }
543
544 private void log(String logstring) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700545 if (mDebug) Slog.d(TAG, logstring);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800546 mLocalLog.log(logstring);
547 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800548
549 private void loge(String logstring) {
550 Slog.e(TAG, logstring);
551 mLocalLog.log(logstring);
552 }
553
554 private static class ResponseQueue {
555
Robert Greenwaltef215992012-06-05 11:48:40 -0700556 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700557 public final int cmdNum;
558 public final String logCmd;
559
Robert Greenwaltef215992012-06-05 11:48:40 -0700560 public BlockingQueue<NativeDaemonEvent> responses =
561 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700562
563 // The availableResponseCount member is used to track when we can remove this
564 // instance from the ResponseQueue.
565 // This is used under the protection of a sync of the mPendingCmds object.
566 // A positive value means we've had more writers retreive this object while
567 // a negative value means we've had more readers. When we've had an equal number
568 // (it goes to zero) we can remove this object from the mPendingCmds list.
569 // Note that we may have more responses for this command (and more readers
570 // coming), but that would result in a new PendingCmd instance being created
571 // and added with the same cmdNum.
572 // Also note that when this goes to zero it just means a parity of readers and
573 // writers have retrieved this object - not that they are done using it. The
574 // responses queue may well have more responses yet to be read or may get more
575 // responses added to it. But all those readers/writers have retreived and
576 // hold references to this instance already so it can be removed from
577 // mPendingCmds queue.
578 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700579
580 public PendingCmd(int cmdNum, String logCmd) {
581 this.cmdNum = cmdNum;
582 this.logCmd = logCmd;
583 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800584 }
585
Robert Greenwaltef215992012-06-05 11:48:40 -0700586 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800587 private int mMaxCount;
588
589 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700590 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800591 mMaxCount = maxCount;
592 }
593
594 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700595 PendingCmd found = null;
596 synchronized (mPendingCmds) {
597 for (PendingCmd pendingCmd : mPendingCmds) {
598 if (pendingCmd.cmdNum == cmdNum) {
599 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800600 break;
601 }
602 }
603 if (found == null) {
604 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700605 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800606 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700607 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800608 " >= " + mMaxCount);
609 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700610 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800611 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700612 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700613 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800614 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700615 found = new PendingCmd(cmdNum, null);
616 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800617 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700618 found.availableResponseCount++;
619 // if a matching remove call has already retrieved this we can remove this
620 // instance from our list
621 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800622 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700623 try {
624 found.responses.put(response);
625 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800626 }
627
628 // note that the timeout does not count time in deep sleep. If you don't want
629 // the device to sleep, hold a wakelock
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700630 public NativeDaemonEvent remove(int cmdNum, long timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700631 PendingCmd found = null;
632 synchronized (mPendingCmds) {
633 for (PendingCmd pendingCmd : mPendingCmds) {
634 if (pendingCmd.cmdNum == cmdNum) {
635 found = pendingCmd;
636 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800637 }
638 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700639 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700640 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700641 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800642 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700643 found.availableResponseCount--;
644 // if a matching add call has already retrieved this we can remove this
645 // instance from our list
646 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800647 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700648 NativeDaemonEvent result = null;
649 try {
650 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
651 } catch (InterruptedException e) {}
652 if (result == null) {
653 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
654 }
655 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800656 }
657
658 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
659 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700660 synchronized (mPendingCmds) {
661 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700662 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800663 }
664 }
665 }
666 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800667}