blob: d6dbad87b06049ab9125e17a22d90e35460ef5d7 [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
Daichi Hironodda65522015-11-19 16:58:57 +0900180 FileDescriptor[] fdList = null;
Kenny Root961aa8c2010-03-22 18:02:45 -0700181 byte[] buffer = new byte[BUFFER_SIZE];
182 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800183
184 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700185 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800186 if (count < 0) {
187 loge("got " + count + " reading with start = " + start);
188 break;
189 }
Daichi Hironodda65522015-11-19 16:58:57 +0900190 fdList = socket.getAncillaryFileDescriptors();
San Mehat67bd2cd2010-01-12 12:18:49 -0800191
Kenny Root12da9d72010-09-02 22:18:14 -0700192 // Add our starting point to the count and reset the start.
193 count += start;
194 start = 0;
195
San Mehat67bd2cd2010-01-12 12:18:49 -0800196 for (int i = 0; i < count; i++) {
197 if (buffer[i] == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800198 // Note - do not log this raw message since it may contain
199 // sensitive data
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800200 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700201 buffer, start, i - start, StandardCharsets.UTF_8);
San Mehat67bd2cd2010-01-12 12:18:49 -0800202
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800203 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800204 try {
Daichi Hironodda65522015-11-19 16:58:57 +0900205 final NativeDaemonEvent event =
206 NativeDaemonEvent.parseRawEvent(rawEvent, fdList);
Paul Lawrencec38182f2014-11-11 12:23:22 -0800207
208 log("RCV <- {" + event + "}");
209
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800210 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800211 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn4590e522014-03-24 13:36:46 -0700212 if (mCallbacks.onCheckHoldWakeLock(event.getCode())
213 && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800214 mWakeLock.acquire();
215 releaseWl = true;
216 }
217 if (mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
218 event.getCode(), event.getRawEvent()))) {
219 releaseWl = false;
220 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800221 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800222 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800223 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800224 } catch (IllegalArgumentException e) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800225 log("Problem parsing message " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800226 } finally {
227 if (releaseWl) {
228 mWakeLock.acquire();
229 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800230 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800231
San Mehat67bd2cd2010-01-12 12:18:49 -0800232 start = i + 1;
233 }
234 }
Paul Lawrencec38182f2014-11-11 12:23:22 -0800235
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800236 if (start == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800237 log("RCV incomplete");
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800238 }
Kenny Root12da9d72010-09-02 22:18:14 -0700239
240 // We should end at the amount we read. If not, compact then
241 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700242 if (start != count) {
243 final int remaining = BUFFER_SIZE - start;
244 System.arraycopy(buffer, start, buffer, 0, remaining);
245 start = remaining;
246 } else {
247 start = 0;
248 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800249 }
250 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800251 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800252 throw ex;
253 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700254 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800255 if (mOutputStream != null) {
256 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800257 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800258 mOutputStream.close();
259 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800260 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800261 }
262 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800263 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800264 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800265
San Mehat4c27e0e2010-01-29 05:22:17 -0800266 try {
267 if (socket != null) {
268 socket.close();
269 }
270 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800271 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800272 }
273 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800274 }
275
San Mehat67bd2cd2010-01-12 12:18:49 -0800276 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700277 * Wrapper around argument that indicates it's sensitive and shouldn't be
278 * logged.
279 */
280 public static class SensitiveArg {
281 private final Object mArg;
282
283 public SensitiveArg(Object arg) {
284 mArg = arg;
285 }
286
287 @Override
288 public String toString() {
289 return String.valueOf(mArg);
290 }
291 }
292
293 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800294 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800295 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700296 @VisibleForTesting
297 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
298 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800299 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800300 throw new IllegalArgumentException("Unexpected command: " + cmd);
301 }
302 if (cmd.indexOf(' ') >= 0) {
303 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700304 }
305
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700306 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
307 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800308 for (Object arg : args) {
309 final String argString = String.valueOf(arg);
310 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800311 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700312 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800313
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700314 rawBuilder.append(' ');
315 logBuilder.append(' ');
316
317 appendEscaped(rawBuilder, argString);
318 if (arg instanceof SensitiveArg) {
319 logBuilder.append("[scrubbed]");
320 } else {
321 appendEscaped(logBuilder, argString);
322 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800323 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700324
325 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800326 }
San Mehatdeba6932010-01-20 15:14:31 -0800327
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700328 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800329 * Issue the given command to the native daemon and return a single expected
330 * response.
331 *
332 * @throws NativeDaemonConnectorException when problem communicating with
333 * native daemon, or if the response matches
334 * {@link NativeDaemonEvent#isClassClientError()} or
335 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800336 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800337 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
338 return execute(cmd.mCmd, cmd.mArguments.toArray());
339 }
340
341 /**
342 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800343 * response. Any arguments must be separated from base command so they can
344 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800345 *
346 * @throws NativeDaemonConnectorException when problem communicating with
347 * native daemon, or if the response matches
348 * {@link NativeDaemonEvent#isClassClientError()} or
349 * {@link NativeDaemonEvent#isClassServerError()}.
350 */
351 public NativeDaemonEvent execute(String cmd, Object... args)
352 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700353 return execute(DEFAULT_TIMEOUT, cmd, args);
354 }
355
356 public NativeDaemonEvent execute(long timeoutMs, String cmd, Object... args)
357 throws NativeDaemonConnectorException {
358 final NativeDaemonEvent[] events = executeForList(timeoutMs, cmd, args);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800359 if (events.length != 1) {
360 throw new NativeDaemonConnectorException(
361 "Expected exactly one response, but received " + events.length);
362 }
363 return events[0];
364 }
365
366 /**
367 * Issue the given command to the native daemon and return any
368 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
369 * final terminal response.
370 *
371 * @throws NativeDaemonConnectorException when problem communicating with
372 * native daemon, or if the response matches
373 * {@link NativeDaemonEvent#isClassClientError()} or
374 * {@link NativeDaemonEvent#isClassServerError()}.
375 */
376 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
377 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
378 }
379
380 /**
381 * Issue the given command to the native daemon and return any
382 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800383 * final terminal response. Any arguments must be separated from base
384 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800385 *
386 * @throws NativeDaemonConnectorException when problem communicating with
387 * native daemon, or if the response matches
388 * {@link NativeDaemonEvent#isClassClientError()} or
389 * {@link NativeDaemonEvent#isClassServerError()}.
390 */
391 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800392 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700393 return executeForList(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800394 }
San Mehatdeba6932010-01-20 15:14:31 -0800395
Robert Greenwalt470007f2012-02-07 11:36:55 -0800396 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800397 * Issue the given command to the native daemon and return any {@linke
398 * NativeDaemonEvent@isClassContinue()} responses, including the final
399 * terminal response. Note that the timeout does not count time in deep
400 * sleep. Any arguments must be separated from base command so they can be
401 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800402 *
403 * @throws NativeDaemonConnectorException when problem communicating with
404 * native daemon, or if the response matches
405 * {@link NativeDaemonEvent#isClassClientError()} or
406 * {@link NativeDaemonEvent#isClassServerError()}.
407 */
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700408 public NativeDaemonEvent[] executeForList(long timeoutMs, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800409 throws NativeDaemonConnectorException {
Jeff Sharkey8948c012015-11-03 12:33:54 -0800410 if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
411 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
412 + Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800413 }
414
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700415 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700416
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700417 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700418
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700419 final StringBuilder rawBuilder = new StringBuilder();
420 final StringBuilder logBuilder = new StringBuilder();
421 final int sequenceNumber = mSequenceNumber.incrementAndGet();
422
423 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
424
425 final String rawCmd = rawBuilder.toString();
426 final String logCmd = logBuilder.toString();
427
Robert Greenwaltd1925982012-03-12 15:37:40 -0700428 log("SND -> {" + logCmd + "}");
429
Robert Greenwaltd1925982012-03-12 15:37:40 -0700430 synchronized (mDaemonLock) {
431 if (mOutputStream == null) {
432 throw new NativeDaemonConnectorException("missing output stream");
433 } else {
434 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700435 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700436 } catch (IOException e) {
437 throw new NativeDaemonConnectorException("problem sending command", e);
438 }
439 }
440 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800441
442 NativeDaemonEvent event = null;
443 do {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700444 event = mResponseQueue.remove(sequenceNumber, timeoutMs, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800445 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700446 loge("timed-out waiting for response to " + logCmd);
Todd Kennedy8101ee62015-06-23 13:35:28 -0700447 throw new NativeDaemonTimeoutException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800448 }
Robert Greenwalt7f44ff82014-05-07 23:49:08 -0700449 if (VDBG) log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800450 events.add(event);
451 } while (event.isClassContinue());
452
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700453 final long endTime = SystemClock.elapsedRealtime();
454 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
455 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
456 }
457
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800458 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700459 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800460 }
461 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700462 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800463 }
464
465 return events.toArray(new NativeDaemonEvent[events.size()]);
466 }
467
468 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800469 * Append the given argument to {@link StringBuilder}, escaping as needed,
470 * and surrounding with quotes when it contains spaces.
471 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800472 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800473 static void appendEscaped(StringBuilder builder, String arg) {
474 final boolean hasSpaces = arg.indexOf(' ') >= 0;
475 if (hasSpaces) {
476 builder.append('"');
477 }
478
479 final int length = arg.length();
480 for (int i = 0; i < length; i++) {
481 final char c = arg.charAt(i);
482
483 if (c == '"') {
484 builder.append("\\\"");
485 } else if (c == '\\') {
486 builder.append("\\\\");
487 } else {
488 builder.append(c);
489 }
490 }
491
492 if (hasSpaces) {
493 builder.append('"');
494 }
495 }
496
497 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
498 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
499 super(command, event);
500 }
501
502 @Override
503 public IllegalArgumentException rethrowAsParcelableException() {
504 throw new IllegalArgumentException(getMessage(), this);
505 }
506 }
507
508 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
509 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
510 super(command, event);
511 }
San Mehatdeba6932010-01-20 15:14:31 -0800512 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700513
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800514 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800515 * Command builder that handles argument list building. Any arguments must
516 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800517 */
518 public static class Command {
519 private String mCmd;
520 private ArrayList<Object> mArguments = Lists.newArrayList();
521
522 public Command(String cmd, Object... args) {
523 mCmd = cmd;
524 for (Object arg : args) {
525 appendArg(arg);
526 }
527 }
528
529 public Command appendArg(Object arg) {
530 mArguments.add(arg);
531 return this;
532 }
533 }
534
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700535 /** {@inheritDoc} */
536 public void monitor() {
537 synchronized (mDaemonLock) { }
538 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800539
540 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
541 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800542 pw.println();
543 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800544 }
545
546 private void log(String logstring) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700547 if (mDebug) Slog.d(TAG, logstring);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800548 mLocalLog.log(logstring);
549 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800550
551 private void loge(String logstring) {
552 Slog.e(TAG, logstring);
553 mLocalLog.log(logstring);
554 }
555
556 private static class ResponseQueue {
557
Robert Greenwaltef215992012-06-05 11:48:40 -0700558 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700559 public final int cmdNum;
560 public final String logCmd;
561
Robert Greenwaltef215992012-06-05 11:48:40 -0700562 public BlockingQueue<NativeDaemonEvent> responses =
563 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700564
565 // The availableResponseCount member is used to track when we can remove this
566 // instance from the ResponseQueue.
567 // This is used under the protection of a sync of the mPendingCmds object.
568 // A positive value means we've had more writers retreive this object while
569 // a negative value means we've had more readers. When we've had an equal number
570 // (it goes to zero) we can remove this object from the mPendingCmds list.
571 // Note that we may have more responses for this command (and more readers
572 // coming), but that would result in a new PendingCmd instance being created
573 // and added with the same cmdNum.
574 // Also note that when this goes to zero it just means a parity of readers and
575 // writers have retrieved this object - not that they are done using it. The
576 // responses queue may well have more responses yet to be read or may get more
577 // responses added to it. But all those readers/writers have retreived and
578 // hold references to this instance already so it can be removed from
579 // mPendingCmds queue.
580 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700581
582 public PendingCmd(int cmdNum, String logCmd) {
583 this.cmdNum = cmdNum;
584 this.logCmd = logCmd;
585 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800586 }
587
Robert Greenwaltef215992012-06-05 11:48:40 -0700588 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800589 private int mMaxCount;
590
591 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700592 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800593 mMaxCount = maxCount;
594 }
595
596 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700597 PendingCmd found = null;
598 synchronized (mPendingCmds) {
599 for (PendingCmd pendingCmd : mPendingCmds) {
600 if (pendingCmd.cmdNum == cmdNum) {
601 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800602 break;
603 }
604 }
605 if (found == null) {
606 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700607 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800608 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700609 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800610 " >= " + mMaxCount);
611 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700612 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800613 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700614 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700615 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800616 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700617 found = new PendingCmd(cmdNum, null);
618 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800619 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700620 found.availableResponseCount++;
621 // if a matching remove call has already retrieved this we can remove this
622 // instance from our list
623 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800624 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700625 try {
626 found.responses.put(response);
627 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800628 }
629
630 // note that the timeout does not count time in deep sleep. If you don't want
631 // the device to sleep, hold a wakelock
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700632 public NativeDaemonEvent remove(int cmdNum, long timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700633 PendingCmd found = null;
634 synchronized (mPendingCmds) {
635 for (PendingCmd pendingCmd : mPendingCmds) {
636 if (pendingCmd.cmdNum == cmdNum) {
637 found = pendingCmd;
638 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800639 }
640 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700641 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700642 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700643 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800644 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700645 found.availableResponseCount--;
646 // if a matching add call has already retrieved this we can remove this
647 // instance from our list
648 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800649 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700650 NativeDaemonEvent result = null;
651 try {
652 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
653 } catch (InterruptedException e) {}
654 if (result == null) {
655 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
656 }
657 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800658 }
659
660 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
661 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700662 synchronized (mPendingCmds) {
663 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700664 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800665 }
666 }
667 }
668 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800669}