blob: 265b95704bbb3251460599389accd98056d71e3d [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;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070023import android.os.Message;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080024import android.os.PowerManager;
San Mehat67bd2cd2010-01-12 12:18:49 -080025import android.os.SystemClock;
Robert Greenwalt470fd722012-01-18 12:51:15 -080026import android.util.LocalLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080027import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080028
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080029import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080030import com.google.android.collect.Lists;
31
Robert Greenwalt470fd722012-01-18 12:51:15 -080032import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080033import java.io.IOException;
34import java.io.InputStream;
35import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080036import java.io.PrintWriter;
Elliott Hughesd396a442013-06-28 16:24:48 -070037import java.nio.charset.StandardCharsets;
San Mehat67bd2cd2010-01-12 12:18:49 -080038import java.util.ArrayList;
Robert Greenwalt470007f2012-02-07 11:36:55 -080039import java.util.concurrent.atomic.AtomicInteger;
Robert Greenwaltef215992012-06-05 11:48:40 -070040import java.util.concurrent.ArrayBlockingQueue;
41import java.util.concurrent.BlockingQueue;
42import java.util.concurrent.TimeUnit;
Robert Greenwalt470007f2012-02-07 11:36:55 -080043import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080044
45/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080046 * Generic connector class for interfacing with a native daemon which uses the
47 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080048 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070049final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Jeff Sharkey31c6e482011-11-18 17:09:01 -080050 private static final boolean LOGD = false;
San Mehat67bd2cd2010-01-12 12:18:49 -080051
Jeff Sharkey31c6e482011-11-18 17:09:01 -080052 private final String TAG;
53
54 private String mSocket;
55 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080056 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080057
Robert Greenwalt470007f2012-02-07 11:36:55 -080058 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080059
Dianne Hackborn77b987f2014-02-26 16:20:52 -080060 private final PowerManager.WakeLock mWakeLock;
61
San Mehat67bd2cd2010-01-12 12:18:49 -080062 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080063 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080064
Robert Greenwalt470007f2012-02-07 11:36:55 -080065 private AtomicInteger mSequenceNumber;
66
67 private static final int DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070068 private static final long WARN_EXECUTE_DELAY_MS = 500; /* .5 sec */
Robert Greenwalt470007f2012-02-07 11:36:55 -080069
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070070 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080071 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070072
Kenny Root961aa8c2010-03-22 18:02:45 -070073 private final int BUFFER_SIZE = 4096;
74
Jeff Sharkey31c6e482011-11-18 17:09:01 -080075 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Dianne Hackborn77b987f2014-02-26 16:20:52 -080076 int responseQueueSize, String logTag, int maxLogSize, PowerManager.WakeLock wl) {
San Mehat67bd2cd2010-01-12 12:18:49 -080077 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080078 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080079 mResponseQueue = new ResponseQueue(responseQueueSize);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080080 mWakeLock = wl;
81 if (mWakeLock != null) {
82 mWakeLock.setReferenceCounted(true);
83 }
Robert Greenwalt470007f2012-02-07 11:36:55 -080084 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -080085 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -080086 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -080087 }
88
Chia-chi Yehe5750a32011-08-03 14:42:11 -070089 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -080090 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -070091 mCallbackHandler = new Handler(FgThread.get().getLooper(), this);
San Mehat67bd2cd2010-01-12 12:18:49 -080092
93 while (true) {
94 try {
95 listenToSocket();
96 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -080097 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -080098 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -080099 }
100 }
101 }
102
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700103 @Override
104 public boolean handleMessage(Message msg) {
105 String event = (String) msg.obj;
106 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700107 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800108 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700109 }
110 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800111 loge("Error handling '" + event + "': " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800112 } finally {
113 if (mCallbacks.onCheckHoldWakeLock(msg.what)) {
114 mWakeLock.release();
115 }
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700116 }
117 return true;
118 }
119
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900120 private LocalSocketAddress determineSocketAddress() {
121 // If we're testing, set up a socket in a namespace that's accessible to test code.
122 // In order to ensure that unprivileged apps aren't able to impersonate native daemons on
123 // production devices, even if said native daemons ill-advisedly pick a socket name that
124 // starts with __test__, only allow this on debug builds.
125 if (mSocket.startsWith("__test__") && Build.IS_DEBUGGABLE) {
126 return new LocalSocketAddress(mSocket);
127 } else {
128 return new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);
129 }
130 }
131
San Mehat4c27e0e2010-01-29 05:22:17 -0800132 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700133 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800134
135 try {
136 socket = new LocalSocket();
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900137 LocalSocketAddress address = determineSocketAddress();
San Mehat67bd2cd2010-01-12 12:18:49 -0800138
139 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800140
141 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800142 synchronized (mDaemonLock) {
143 mOutputStream = socket.getOutputStream();
144 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800145
anga030bc882011-02-01 14:10:25 +0100146 mCallbacks.onDaemonConnected();
147
Kenny Root961aa8c2010-03-22 18:02:45 -0700148 byte[] buffer = new byte[BUFFER_SIZE];
149 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800150
151 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700152 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800153 if (count < 0) {
154 loge("got " + count + " reading with start = " + start);
155 break;
156 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800157
Kenny Root12da9d72010-09-02 22:18:14 -0700158 // Add our starting point to the count and reset the start.
159 count += start;
160 start = 0;
161
San Mehat67bd2cd2010-01-12 12:18:49 -0800162 for (int i = 0; i < count; i++) {
163 if (buffer[i] == 0) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800164 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700165 buffer, start, i - start, StandardCharsets.UTF_8);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800166 log("RCV <- {" + rawEvent + "}");
San Mehat67bd2cd2010-01-12 12:18:49 -0800167
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800168 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800169 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800170 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
171 rawEvent);
172 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800173 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800174 if (mCallbacks.onCheckHoldWakeLock(event.getCode())) {
175 mWakeLock.acquire();
176 releaseWl = true;
177 }
178 if (mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
179 event.getCode(), event.getRawEvent()))) {
180 releaseWl = false;
181 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800182 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800183 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800184 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800185 } catch (IllegalArgumentException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800186 log("Problem parsing message: " + rawEvent + " - " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800187 } finally {
188 if (releaseWl) {
189 mWakeLock.acquire();
190 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800191 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800192
San Mehat67bd2cd2010-01-12 12:18:49 -0800193 start = i + 1;
194 }
195 }
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800196 if (start == 0) {
Elliott Hughesd396a442013-06-28 16:24:48 -0700197 final String rawEvent = new String(buffer, start, count, StandardCharsets.UTF_8);
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800198 log("RCV incomplete <- {" + rawEvent + "}");
199 }
Kenny Root12da9d72010-09-02 22:18:14 -0700200
201 // We should end at the amount we read. If not, compact then
202 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700203 if (start != count) {
204 final int remaining = BUFFER_SIZE - start;
205 System.arraycopy(buffer, start, buffer, 0, remaining);
206 start = remaining;
207 } else {
208 start = 0;
209 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800210 }
211 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800212 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800213 throw ex;
214 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700215 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800216 if (mOutputStream != null) {
217 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800218 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800219 mOutputStream.close();
220 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800221 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800222 }
223 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800224 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800225 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800226
San Mehat4c27e0e2010-01-29 05:22:17 -0800227 try {
228 if (socket != null) {
229 socket.close();
230 }
231 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800232 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800233 }
234 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800235 }
236
San Mehat67bd2cd2010-01-12 12:18:49 -0800237 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700238 * Wrapper around argument that indicates it's sensitive and shouldn't be
239 * logged.
240 */
241 public static class SensitiveArg {
242 private final Object mArg;
243
244 public SensitiveArg(Object arg) {
245 mArg = arg;
246 }
247
248 @Override
249 public String toString() {
250 return String.valueOf(mArg);
251 }
252 }
253
254 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800255 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800256 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700257 @VisibleForTesting
258 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
259 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800260 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800261 throw new IllegalArgumentException("Unexpected command: " + cmd);
262 }
263 if (cmd.indexOf(' ') >= 0) {
264 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700265 }
266
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700267 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
268 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800269 for (Object arg : args) {
270 final String argString = String.valueOf(arg);
271 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800272 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700273 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800274
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700275 rawBuilder.append(' ');
276 logBuilder.append(' ');
277
278 appendEscaped(rawBuilder, argString);
279 if (arg instanceof SensitiveArg) {
280 logBuilder.append("[scrubbed]");
281 } else {
282 appendEscaped(logBuilder, argString);
283 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800284 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700285
286 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800287 }
San Mehatdeba6932010-01-20 15:14:31 -0800288
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700289 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800290 * Issue the given command to the native daemon and return a single expected
291 * response.
292 *
293 * @throws NativeDaemonConnectorException when problem communicating with
294 * native daemon, or if the response matches
295 * {@link NativeDaemonEvent#isClassClientError()} or
296 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800297 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800298 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
299 return execute(cmd.mCmd, cmd.mArguments.toArray());
300 }
301
302 /**
303 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800304 * response. Any arguments must be separated from base command so they can
305 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800306 *
307 * @throws NativeDaemonConnectorException when problem communicating with
308 * native daemon, or if the response matches
309 * {@link NativeDaemonEvent#isClassClientError()} or
310 * {@link NativeDaemonEvent#isClassServerError()}.
311 */
312 public NativeDaemonEvent execute(String cmd, Object... args)
313 throws NativeDaemonConnectorException {
314 final NativeDaemonEvent[] events = executeForList(cmd, args);
315 if (events.length != 1) {
316 throw new NativeDaemonConnectorException(
317 "Expected exactly one response, but received " + events.length);
318 }
319 return events[0];
320 }
321
322 /**
323 * Issue the given command to the native daemon and return any
324 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
325 * final terminal response.
326 *
327 * @throws NativeDaemonConnectorException when problem communicating with
328 * native daemon, or if the response matches
329 * {@link NativeDaemonEvent#isClassClientError()} or
330 * {@link NativeDaemonEvent#isClassServerError()}.
331 */
332 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
333 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
334 }
335
336 /**
337 * Issue the given command to the native daemon and return any
338 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800339 * final terminal response. Any arguments must be separated from base
340 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800341 *
342 * @throws NativeDaemonConnectorException when problem communicating with
343 * native daemon, or if the response matches
344 * {@link NativeDaemonEvent#isClassClientError()} or
345 * {@link NativeDaemonEvent#isClassServerError()}.
346 */
347 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800348 throws NativeDaemonConnectorException {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800349 return execute(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800350 }
San Mehatdeba6932010-01-20 15:14:31 -0800351
Robert Greenwalt470007f2012-02-07 11:36:55 -0800352 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800353 * Issue the given command to the native daemon and return any {@linke
354 * NativeDaemonEvent@isClassContinue()} responses, including the final
355 * terminal response. Note that the timeout does not count time in deep
356 * sleep. Any arguments must be separated from base command so they can be
357 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800358 *
359 * @throws NativeDaemonConnectorException when problem communicating with
360 * native daemon, or if the response matches
361 * {@link NativeDaemonEvent#isClassClientError()} or
362 * {@link NativeDaemonEvent#isClassServerError()}.
363 */
364 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800365 throws NativeDaemonConnectorException {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700366 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700367
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700368 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700369
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700370 final StringBuilder rawBuilder = new StringBuilder();
371 final StringBuilder logBuilder = new StringBuilder();
372 final int sequenceNumber = mSequenceNumber.incrementAndGet();
373
374 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
375
376 final String rawCmd = rawBuilder.toString();
377 final String logCmd = logBuilder.toString();
378
Robert Greenwaltd1925982012-03-12 15:37:40 -0700379 log("SND -> {" + logCmd + "}");
380
Robert Greenwaltd1925982012-03-12 15:37:40 -0700381 synchronized (mDaemonLock) {
382 if (mOutputStream == null) {
383 throw new NativeDaemonConnectorException("missing output stream");
384 } else {
385 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700386 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700387 } catch (IOException e) {
388 throw new NativeDaemonConnectorException("problem sending command", e);
389 }
390 }
391 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800392
393 NativeDaemonEvent event = null;
394 do {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700395 event = mResponseQueue.remove(sequenceNumber, timeout, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800396 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700397 loge("timed-out waiting for response to " + logCmd);
398 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800399 }
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700400 log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800401 events.add(event);
402 } while (event.isClassContinue());
403
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700404 final long endTime = SystemClock.elapsedRealtime();
405 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
406 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
407 }
408
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800409 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700410 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800411 }
412 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700413 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800414 }
415
416 return events.toArray(new NativeDaemonEvent[events.size()]);
417 }
418
419 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800420 * Append the given argument to {@link StringBuilder}, escaping as needed,
421 * and surrounding with quotes when it contains spaces.
422 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800423 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800424 static void appendEscaped(StringBuilder builder, String arg) {
425 final boolean hasSpaces = arg.indexOf(' ') >= 0;
426 if (hasSpaces) {
427 builder.append('"');
428 }
429
430 final int length = arg.length();
431 for (int i = 0; i < length; i++) {
432 final char c = arg.charAt(i);
433
434 if (c == '"') {
435 builder.append("\\\"");
436 } else if (c == '\\') {
437 builder.append("\\\\");
438 } else {
439 builder.append(c);
440 }
441 }
442
443 if (hasSpaces) {
444 builder.append('"');
445 }
446 }
447
448 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
449 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
450 super(command, event);
451 }
452
453 @Override
454 public IllegalArgumentException rethrowAsParcelableException() {
455 throw new IllegalArgumentException(getMessage(), this);
456 }
457 }
458
459 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
460 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
461 super(command, event);
462 }
San Mehatdeba6932010-01-20 15:14:31 -0800463 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700464
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800465 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800466 * Command builder that handles argument list building. Any arguments must
467 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800468 */
469 public static class Command {
470 private String mCmd;
471 private ArrayList<Object> mArguments = Lists.newArrayList();
472
473 public Command(String cmd, Object... args) {
474 mCmd = cmd;
475 for (Object arg : args) {
476 appendArg(arg);
477 }
478 }
479
480 public Command appendArg(Object arg) {
481 mArguments.add(arg);
482 return this;
483 }
484 }
485
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700486 /** {@inheritDoc} */
487 public void monitor() {
488 synchronized (mDaemonLock) { }
489 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800490
491 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
492 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800493 pw.println();
494 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800495 }
496
497 private void log(String logstring) {
498 if (LOGD) Slog.d(TAG, logstring);
499 mLocalLog.log(logstring);
500 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800501
502 private void loge(String logstring) {
503 Slog.e(TAG, logstring);
504 mLocalLog.log(logstring);
505 }
506
507 private static class ResponseQueue {
508
Robert Greenwaltef215992012-06-05 11:48:40 -0700509 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700510 public final int cmdNum;
511 public final String logCmd;
512
Robert Greenwaltef215992012-06-05 11:48:40 -0700513 public BlockingQueue<NativeDaemonEvent> responses =
514 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700515
516 // The availableResponseCount member is used to track when we can remove this
517 // instance from the ResponseQueue.
518 // This is used under the protection of a sync of the mPendingCmds object.
519 // A positive value means we've had more writers retreive this object while
520 // a negative value means we've had more readers. When we've had an equal number
521 // (it goes to zero) we can remove this object from the mPendingCmds list.
522 // Note that we may have more responses for this command (and more readers
523 // coming), but that would result in a new PendingCmd instance being created
524 // and added with the same cmdNum.
525 // Also note that when this goes to zero it just means a parity of readers and
526 // writers have retrieved this object - not that they are done using it. The
527 // responses queue may well have more responses yet to be read or may get more
528 // responses added to it. But all those readers/writers have retreived and
529 // hold references to this instance already so it can be removed from
530 // mPendingCmds queue.
531 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700532
533 public PendingCmd(int cmdNum, String logCmd) {
534 this.cmdNum = cmdNum;
535 this.logCmd = logCmd;
536 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800537 }
538
Robert Greenwaltef215992012-06-05 11:48:40 -0700539 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800540 private int mMaxCount;
541
542 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700543 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800544 mMaxCount = maxCount;
545 }
546
547 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700548 PendingCmd found = null;
549 synchronized (mPendingCmds) {
550 for (PendingCmd pendingCmd : mPendingCmds) {
551 if (pendingCmd.cmdNum == cmdNum) {
552 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800553 break;
554 }
555 }
556 if (found == null) {
557 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700558 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800559 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700560 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800561 " >= " + mMaxCount);
562 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700563 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800564 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700565 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700566 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800567 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700568 found = new PendingCmd(cmdNum, null);
569 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800570 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700571 found.availableResponseCount++;
572 // if a matching remove call has already retrieved this we can remove this
573 // instance from our list
574 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800575 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700576 try {
577 found.responses.put(response);
578 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800579 }
580
581 // note that the timeout does not count time in deep sleep. If you don't want
582 // the device to sleep, hold a wakelock
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700583 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700584 PendingCmd found = null;
585 synchronized (mPendingCmds) {
586 for (PendingCmd pendingCmd : mPendingCmds) {
587 if (pendingCmd.cmdNum == cmdNum) {
588 found = pendingCmd;
589 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800590 }
591 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700592 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700593 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700594 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800595 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700596 found.availableResponseCount--;
597 // if a matching add call has already retrieved this we can remove this
598 // instance from our list
599 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800600 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700601 NativeDaemonEvent result = null;
602 try {
603 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
604 } catch (InterruptedException e) {}
605 if (result == null) {
606 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
607 }
608 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800609 }
610
611 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
612 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700613 synchronized (mPendingCmds) {
614 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700615 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800616 }
617 }
618 }
619 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800620}