blob: 3a6fa0563da5e3d1fb88e969633db7142a798cee [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;
Jeff Sharkeye41dc592015-11-03 10:39:42 -080028import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080029import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080030
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080031import com.android.internal.annotations.VisibleForTesting;
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 Sharkeye41dc592015-11-03 10:39:42 -080061 private volatile Object mLockWarning;
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 /**
113 * Yell loudly if someone tries making future {@link #execute(Command)} calls while holding a
114 * lock on the given object.
115 */
116 public void setLockWarning(Object lockWarning) {
117 mLockWarning = lockWarning;
118 }
119
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700120 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -0800121 public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700122 mCallbackHandler = new Handler(mLooper, this);
San Mehat67bd2cd2010-01-12 12:18:49 -0800123
124 while (true) {
125 try {
126 listenToSocket();
127 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800128 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800129 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -0800130 }
131 }
132 }
133
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700134 @Override
135 public boolean handleMessage(Message msg) {
136 String event = (String) msg.obj;
137 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700138 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800139 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700140 }
141 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800142 loge("Error handling '" + event + "': " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800143 } finally {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700144 if (mCallbacks.onCheckHoldWakeLock(msg.what) && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800145 mWakeLock.release();
146 }
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700147 }
148 return true;
149 }
150
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900151 private LocalSocketAddress determineSocketAddress() {
152 // If we're testing, set up a socket in a namespace that's accessible to test code.
153 // In order to ensure that unprivileged apps aren't able to impersonate native daemons on
154 // production devices, even if said native daemons ill-advisedly pick a socket name that
155 // starts with __test__, only allow this on debug builds.
156 if (mSocket.startsWith("__test__") && Build.IS_DEBUGGABLE) {
157 return new LocalSocketAddress(mSocket);
158 } else {
159 return new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);
160 }
161 }
162
San Mehat4c27e0e2010-01-29 05:22:17 -0800163 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700164 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800165
166 try {
167 socket = new LocalSocket();
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900168 LocalSocketAddress address = determineSocketAddress();
San Mehat67bd2cd2010-01-12 12:18:49 -0800169
170 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800171
172 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800173 synchronized (mDaemonLock) {
174 mOutputStream = socket.getOutputStream();
175 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800176
anga030bc882011-02-01 14:10:25 +0100177 mCallbacks.onDaemonConnected();
178
Kenny Root961aa8c2010-03-22 18:02:45 -0700179 byte[] buffer = new byte[BUFFER_SIZE];
180 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800181
182 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700183 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800184 if (count < 0) {
185 loge("got " + count + " reading with start = " + start);
186 break;
187 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800188
Kenny Root12da9d72010-09-02 22:18:14 -0700189 // Add our starting point to the count and reset the start.
190 count += start;
191 start = 0;
192
San Mehat67bd2cd2010-01-12 12:18:49 -0800193 for (int i = 0; i < count; i++) {
194 if (buffer[i] == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800195 // Note - do not log this raw message since it may contain
196 // sensitive data
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800197 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700198 buffer, start, i - start, StandardCharsets.UTF_8);
San Mehat67bd2cd2010-01-12 12:18:49 -0800199
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800200 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800201 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800202 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
203 rawEvent);
Paul Lawrencec38182f2014-11-11 12:23:22 -0800204
205 log("RCV <- {" + event + "}");
206
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800207 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800208 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn4590e522014-03-24 13:36:46 -0700209 if (mCallbacks.onCheckHoldWakeLock(event.getCode())
210 && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800211 mWakeLock.acquire();
212 releaseWl = true;
213 }
214 if (mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
215 event.getCode(), event.getRawEvent()))) {
216 releaseWl = false;
217 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800218 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800219 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800220 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800221 } catch (IllegalArgumentException e) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800222 log("Problem parsing message " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800223 } finally {
224 if (releaseWl) {
225 mWakeLock.acquire();
226 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800227 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800228
San Mehat67bd2cd2010-01-12 12:18:49 -0800229 start = i + 1;
230 }
231 }
Paul Lawrencec38182f2014-11-11 12:23:22 -0800232
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800233 if (start == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800234 log("RCV incomplete");
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800235 }
Kenny Root12da9d72010-09-02 22:18:14 -0700236
237 // We should end at the amount we read. If not, compact then
238 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700239 if (start != count) {
240 final int remaining = BUFFER_SIZE - start;
241 System.arraycopy(buffer, start, buffer, 0, remaining);
242 start = remaining;
243 } else {
244 start = 0;
245 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800246 }
247 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800248 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800249 throw ex;
250 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700251 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800252 if (mOutputStream != null) {
253 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800254 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800255 mOutputStream.close();
256 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800257 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800258 }
259 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800260 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800261 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800262
San Mehat4c27e0e2010-01-29 05:22:17 -0800263 try {
264 if (socket != null) {
265 socket.close();
266 }
267 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800268 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800269 }
270 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800271 }
272
San Mehat67bd2cd2010-01-12 12:18:49 -0800273 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700274 * Wrapper around argument that indicates it's sensitive and shouldn't be
275 * logged.
276 */
277 public static class SensitiveArg {
278 private final Object mArg;
279
280 public SensitiveArg(Object arg) {
281 mArg = arg;
282 }
283
284 @Override
285 public String toString() {
286 return String.valueOf(mArg);
287 }
288 }
289
290 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800291 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800292 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700293 @VisibleForTesting
294 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
295 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800296 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800297 throw new IllegalArgumentException("Unexpected command: " + cmd);
298 }
299 if (cmd.indexOf(' ') >= 0) {
300 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700301 }
302
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700303 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
304 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800305 for (Object arg : args) {
306 final String argString = String.valueOf(arg);
307 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800308 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700309 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800310
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700311 rawBuilder.append(' ');
312 logBuilder.append(' ');
313
314 appendEscaped(rawBuilder, argString);
315 if (arg instanceof SensitiveArg) {
316 logBuilder.append("[scrubbed]");
317 } else {
318 appendEscaped(logBuilder, argString);
319 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800320 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700321
322 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800323 }
San Mehatdeba6932010-01-20 15:14:31 -0800324
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700325 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800326 * Issue the given command to the native daemon and return a single expected
327 * response.
328 *
329 * @throws NativeDaemonConnectorException when problem communicating with
330 * native daemon, or if the response matches
331 * {@link NativeDaemonEvent#isClassClientError()} or
332 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800333 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800334 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
335 return execute(cmd.mCmd, cmd.mArguments.toArray());
336 }
337
338 /**
339 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800340 * response. Any arguments must be separated from base command so they can
341 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800342 *
343 * @throws NativeDaemonConnectorException when problem communicating with
344 * native daemon, or if the response matches
345 * {@link NativeDaemonEvent#isClassClientError()} or
346 * {@link NativeDaemonEvent#isClassServerError()}.
347 */
348 public NativeDaemonEvent execute(String cmd, Object... args)
349 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700350 return execute(DEFAULT_TIMEOUT, cmd, args);
351 }
352
353 public NativeDaemonEvent execute(long timeoutMs, String cmd, Object... args)
354 throws NativeDaemonConnectorException {
355 final NativeDaemonEvent[] events = executeForList(timeoutMs, cmd, args);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800356 if (events.length != 1) {
357 throw new NativeDaemonConnectorException(
358 "Expected exactly one response, but received " + events.length);
359 }
360 return events[0];
361 }
362
363 /**
364 * Issue the given command to the native daemon and return any
365 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
366 * final terminal response.
367 *
368 * @throws NativeDaemonConnectorException when problem communicating with
369 * native daemon, or if the response matches
370 * {@link NativeDaemonEvent#isClassClientError()} or
371 * {@link NativeDaemonEvent#isClassServerError()}.
372 */
373 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
374 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
375 }
376
377 /**
378 * Issue the given command to the native daemon and return any
379 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800380 * final terminal response. Any arguments must be separated from base
381 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800382 *
383 * @throws NativeDaemonConnectorException when problem communicating with
384 * native daemon, or if the response matches
385 * {@link NativeDaemonEvent#isClassClientError()} or
386 * {@link NativeDaemonEvent#isClassServerError()}.
387 */
388 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800389 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700390 return executeForList(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800391 }
San Mehatdeba6932010-01-20 15:14:31 -0800392
Robert Greenwalt470007f2012-02-07 11:36:55 -0800393 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800394 * Issue the given command to the native daemon and return any {@linke
395 * NativeDaemonEvent@isClassContinue()} responses, including the final
396 * terminal response. Note that the timeout does not count time in deep
397 * sleep. Any arguments must be separated from base command so they can be
398 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800399 *
400 * @throws NativeDaemonConnectorException when problem communicating with
401 * native daemon, or if the response matches
402 * {@link NativeDaemonEvent#isClassClientError()} or
403 * {@link NativeDaemonEvent#isClassServerError()}.
404 */
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700405 public NativeDaemonEvent[] executeForList(long timeoutMs, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800406 throws NativeDaemonConnectorException {
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800407 if (mLockWarning != null && Thread.holdsLock(mLockWarning)) {
408 Log.wtf(TAG, "Calling thread is holding lock " + mLockWarning, new Throwable());
409 }
410
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700411 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700412
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700413 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700414
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700415 final StringBuilder rawBuilder = new StringBuilder();
416 final StringBuilder logBuilder = new StringBuilder();
417 final int sequenceNumber = mSequenceNumber.incrementAndGet();
418
419 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
420
421 final String rawCmd = rawBuilder.toString();
422 final String logCmd = logBuilder.toString();
423
Robert Greenwaltd1925982012-03-12 15:37:40 -0700424 log("SND -> {" + logCmd + "}");
425
Robert Greenwaltd1925982012-03-12 15:37:40 -0700426 synchronized (mDaemonLock) {
427 if (mOutputStream == null) {
428 throw new NativeDaemonConnectorException("missing output stream");
429 } else {
430 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700431 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700432 } catch (IOException e) {
433 throw new NativeDaemonConnectorException("problem sending command", e);
434 }
435 }
436 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800437
438 NativeDaemonEvent event = null;
439 do {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700440 event = mResponseQueue.remove(sequenceNumber, timeoutMs, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800441 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700442 loge("timed-out waiting for response to " + logCmd);
Todd Kennedy8101ee62015-06-23 13:35:28 -0700443 throw new NativeDaemonTimeoutException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800444 }
Robert Greenwalt7f44ff82014-05-07 23:49:08 -0700445 if (VDBG) log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800446 events.add(event);
447 } while (event.isClassContinue());
448
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700449 final long endTime = SystemClock.elapsedRealtime();
450 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
451 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
452 }
453
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800454 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700455 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800456 }
457 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700458 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800459 }
460
461 return events.toArray(new NativeDaemonEvent[events.size()]);
462 }
463
464 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800465 * Append the given argument to {@link StringBuilder}, escaping as needed,
466 * and surrounding with quotes when it contains spaces.
467 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800468 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800469 static void appendEscaped(StringBuilder builder, String arg) {
470 final boolean hasSpaces = arg.indexOf(' ') >= 0;
471 if (hasSpaces) {
472 builder.append('"');
473 }
474
475 final int length = arg.length();
476 for (int i = 0; i < length; i++) {
477 final char c = arg.charAt(i);
478
479 if (c == '"') {
480 builder.append("\\\"");
481 } else if (c == '\\') {
482 builder.append("\\\\");
483 } else {
484 builder.append(c);
485 }
486 }
487
488 if (hasSpaces) {
489 builder.append('"');
490 }
491 }
492
493 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
494 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
495 super(command, event);
496 }
497
498 @Override
499 public IllegalArgumentException rethrowAsParcelableException() {
500 throw new IllegalArgumentException(getMessage(), this);
501 }
502 }
503
504 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
505 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
506 super(command, event);
507 }
San Mehatdeba6932010-01-20 15:14:31 -0800508 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700509
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800510 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800511 * Command builder that handles argument list building. Any arguments must
512 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800513 */
514 public static class Command {
515 private String mCmd;
516 private ArrayList<Object> mArguments = Lists.newArrayList();
517
518 public Command(String cmd, Object... args) {
519 mCmd = cmd;
520 for (Object arg : args) {
521 appendArg(arg);
522 }
523 }
524
525 public Command appendArg(Object arg) {
526 mArguments.add(arg);
527 return this;
528 }
529 }
530
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700531 /** {@inheritDoc} */
532 public void monitor() {
533 synchronized (mDaemonLock) { }
534 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800535
536 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
537 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800538 pw.println();
539 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800540 }
541
542 private void log(String logstring) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700543 if (mDebug) Slog.d(TAG, logstring);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800544 mLocalLog.log(logstring);
545 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800546
547 private void loge(String logstring) {
548 Slog.e(TAG, logstring);
549 mLocalLog.log(logstring);
550 }
551
552 private static class ResponseQueue {
553
Robert Greenwaltef215992012-06-05 11:48:40 -0700554 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700555 public final int cmdNum;
556 public final String logCmd;
557
Robert Greenwaltef215992012-06-05 11:48:40 -0700558 public BlockingQueue<NativeDaemonEvent> responses =
559 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700560
561 // The availableResponseCount member is used to track when we can remove this
562 // instance from the ResponseQueue.
563 // This is used under the protection of a sync of the mPendingCmds object.
564 // A positive value means we've had more writers retreive this object while
565 // a negative value means we've had more readers. When we've had an equal number
566 // (it goes to zero) we can remove this object from the mPendingCmds list.
567 // Note that we may have more responses for this command (and more readers
568 // coming), but that would result in a new PendingCmd instance being created
569 // and added with the same cmdNum.
570 // Also note that when this goes to zero it just means a parity of readers and
571 // writers have retrieved this object - not that they are done using it. The
572 // responses queue may well have more responses yet to be read or may get more
573 // responses added to it. But all those readers/writers have retreived and
574 // hold references to this instance already so it can be removed from
575 // mPendingCmds queue.
576 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700577
578 public PendingCmd(int cmdNum, String logCmd) {
579 this.cmdNum = cmdNum;
580 this.logCmd = logCmd;
581 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800582 }
583
Robert Greenwaltef215992012-06-05 11:48:40 -0700584 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800585 private int mMaxCount;
586
587 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700588 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800589 mMaxCount = maxCount;
590 }
591
592 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700593 PendingCmd found = null;
594 synchronized (mPendingCmds) {
595 for (PendingCmd pendingCmd : mPendingCmds) {
596 if (pendingCmd.cmdNum == cmdNum) {
597 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800598 break;
599 }
600 }
601 if (found == null) {
602 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700603 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800604 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700605 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800606 " >= " + mMaxCount);
607 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700608 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800609 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700610 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700611 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800612 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700613 found = new PendingCmd(cmdNum, null);
614 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800615 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700616 found.availableResponseCount++;
617 // if a matching remove call has already retrieved this we can remove this
618 // instance from our list
619 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800620 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700621 try {
622 found.responses.put(response);
623 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800624 }
625
626 // note that the timeout does not count time in deep sleep. If you don't want
627 // the device to sleep, hold a wakelock
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700628 public NativeDaemonEvent remove(int cmdNum, long timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700629 PendingCmd found = null;
630 synchronized (mPendingCmds) {
631 for (PendingCmd pendingCmd : mPendingCmds) {
632 if (pendingCmd.cmdNum == cmdNum) {
633 found = pendingCmd;
634 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800635 }
636 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700637 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700638 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700639 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800640 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700641 found.availableResponseCount--;
642 // if a matching add call has already retrieved this we can remove this
643 // instance from our list
644 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800645 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700646 NativeDaemonEvent result = null;
647 try {
648 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
649 } catch (InterruptedException e) {}
650 if (result == null) {
651 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
652 }
653 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800654 }
655
656 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
657 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700658 synchronized (mPendingCmds) {
659 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700660 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800661 }
662 }
663 }
664 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800665}