blob: b5a8332375f4e6a9a88a001de1ed6362a8a95362 [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;
Tetsutoki Shiozawae83724e2017-07-13 15:37:40 +090027import android.os.SystemProperties;
Robert Greenwalt470fd722012-01-18 12:51:15 -080028import android.util.LocalLog;
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 Sharkey8948c012015-11-03 12:33:54 -080032import com.android.internal.util.Preconditions;
Tetsutoki Shiozawae83724e2017-07-13 15:37:40 +090033import com.android.server.power.ShutdownThread;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080034import com.google.android.collect.Lists;
35
Robert Greenwalt470fd722012-01-18 12:51:15 -080036import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080037import java.io.IOException;
38import java.io.InputStream;
39import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080040import java.io.PrintWriter;
Elliott Hughesd396a442013-06-28 16:24:48 -070041import java.nio.charset.StandardCharsets;
San Mehat67bd2cd2010-01-12 12:18:49 -080042import java.util.ArrayList;
Robert Greenwalt470007f2012-02-07 11:36:55 -080043import java.util.concurrent.atomic.AtomicInteger;
Robert Greenwaltef215992012-06-05 11:48:40 -070044import java.util.concurrent.ArrayBlockingQueue;
45import java.util.concurrent.BlockingQueue;
Rebecca Silbersteinefdb8452016-04-21 12:14:41 -070046import java.util.concurrent.CountDownLatch;
Robert Greenwaltef215992012-06-05 11:48:40 -070047import java.util.concurrent.TimeUnit;
Robert Greenwalt470007f2012-02-07 11:36:55 -080048import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080049
50/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080051 * Generic connector class for interfacing with a native daemon which uses the
52 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080053 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070054final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Robert Greenwalt7f44ff82014-05-07 23:49:08 -070055 private final static boolean VDBG = false;
56
Jeff Sharkey31c6e482011-11-18 17:09:01 -080057 private final String TAG;
58
59 private String mSocket;
60 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080061 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080062
Jeff Sharkey48877892015-03-18 11:27:19 -070063 private volatile boolean mDebug = false;
Jeff Sharkey8948c012015-11-03 12:33:54 -080064 private volatile Object mWarnIfHeld;
Jeff Sharkey48877892015-03-18 11:27:19 -070065
Robert Greenwalt470007f2012-02-07 11:36:55 -080066 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080067
Dianne Hackborn77b987f2014-02-26 16:20:52 -080068 private final PowerManager.WakeLock mWakeLock;
69
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070070 private final Looper mLooper;
71
San Mehat67bd2cd2010-01-12 12:18:49 -080072 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080073 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080074
Robert Greenwalt470007f2012-02-07 11:36:55 -080075 private AtomicInteger mSequenceNumber;
76
Jeff Sharkey14cbe522015-07-08 14:06:37 -070077 private static final long DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070078 private static final long WARN_EXECUTE_DELAY_MS = 500; /* .5 sec */
Robert Greenwalt470007f2012-02-07 11:36:55 -080079
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070080 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080081 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070082
Kenny Root961aa8c2010-03-22 18:02:45 -070083 private final int BUFFER_SIZE = 4096;
84
Jeff Sharkey31c6e482011-11-18 17:09:01 -080085 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Dianne Hackborn77b987f2014-02-26 16:20:52 -080086 int responseQueueSize, String logTag, int maxLogSize, PowerManager.WakeLock wl) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070087 this(callbacks, socket, responseQueueSize, logTag, maxLogSize, wl,
88 FgThread.get().getLooper());
89 }
90
91 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
92 int responseQueueSize, String logTag, int maxLogSize, PowerManager.WakeLock wl,
93 Looper looper) {
San Mehat67bd2cd2010-01-12 12:18:49 -080094 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080095 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080096 mResponseQueue = new ResponseQueue(responseQueueSize);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080097 mWakeLock = wl;
98 if (mWakeLock != null) {
99 mWakeLock.setReferenceCounted(true);
100 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700101 mLooper = looper;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800102 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800103 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -0800104 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -0800105 }
106
Jeff Sharkey48877892015-03-18 11:27:19 -0700107 /**
108 * Enable Set debugging mode, which causes messages to also be written to both
109 * {@link Slog} in addition to internal log.
110 */
111 public void setDebug(boolean debug) {
112 mDebug = debug;
113 }
114
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800115 /**
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900116 * Like SystemClock.uptimeMillis, except truncated to an int so it will fit in a message arg.
117 * Inaccurate across 49.7 days of uptime, but only used for debugging.
118 */
119 private int uptimeMillisInt() {
120 return (int) SystemClock.uptimeMillis() & Integer.MAX_VALUE;
121 }
122
123 /**
Jeff Sharkey8948c012015-11-03 12:33:54 -0800124 * Yell loudly if someone tries making future {@link #execute(Command)}
125 * calls while holding a lock on the given object.
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800126 */
Jeff Sharkey8948c012015-11-03 12:33:54 -0800127 public void setWarnIfHeld(Object warnIfHeld) {
128 Preconditions.checkState(mWarnIfHeld == null);
129 mWarnIfHeld = Preconditions.checkNotNull(warnIfHeld);
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800130 }
131
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700132 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -0800133 public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700134 mCallbackHandler = new Handler(mLooper, this);
San Mehat67bd2cd2010-01-12 12:18:49 -0800135
136 while (true) {
137 try {
138 listenToSocket();
139 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800140 loge("Error in NativeDaemonConnector: " + e);
Tetsutoki Shiozawae83724e2017-07-13 15:37:40 +0900141 String shutdownAct = SystemProperties.get(
142 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
143 if (shutdownAct != null && shutdownAct.length() > 0) {
144 // The device is in middle of shutdown.
145 break;
146 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800147 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -0800148 }
149 }
150 }
151
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700152 @Override
153 public boolean handleMessage(Message msg) {
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900154 final String event = (String) msg.obj;
155 final int start = uptimeMillisInt();
156 final int sent = msg.arg1;
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700157 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700158 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800159 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700160 }
161 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800162 loge("Error handling '" + event + "': " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800163 } finally {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700164 if (mCallbacks.onCheckHoldWakeLock(msg.what) && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800165 mWakeLock.release();
166 }
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900167 final int end = uptimeMillisInt();
168 if (start > sent && start - sent > WARN_EXECUTE_DELAY_MS) {
169 loge(String.format("NDC event {%s} processed too late: %dms", event, start - sent));
170 }
171 if (end > start && end - start > WARN_EXECUTE_DELAY_MS) {
172 loge(String.format("NDC event {%s} took too long: %dms", event, end - start));
173 }
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700174 }
175 return true;
176 }
177
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900178 private LocalSocketAddress determineSocketAddress() {
179 // If we're testing, set up a socket in a namespace that's accessible to test code.
180 // In order to ensure that unprivileged apps aren't able to impersonate native daemons on
181 // production devices, even if said native daemons ill-advisedly pick a socket name that
182 // starts with __test__, only allow this on debug builds.
183 if (mSocket.startsWith("__test__") && Build.IS_DEBUGGABLE) {
184 return new LocalSocketAddress(mSocket);
185 } else {
186 return new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);
187 }
188 }
189
San Mehat4c27e0e2010-01-29 05:22:17 -0800190 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700191 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800192
193 try {
194 socket = new LocalSocket();
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900195 LocalSocketAddress address = determineSocketAddress();
San Mehat67bd2cd2010-01-12 12:18:49 -0800196
197 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800198
199 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800200 synchronized (mDaemonLock) {
201 mOutputStream = socket.getOutputStream();
202 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800203
anga030bc882011-02-01 14:10:25 +0100204 mCallbacks.onDaemonConnected();
205
Daichi Hironodda65522015-11-19 16:58:57 +0900206 FileDescriptor[] fdList = null;
Kenny Root961aa8c2010-03-22 18:02:45 -0700207 byte[] buffer = new byte[BUFFER_SIZE];
208 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800209
210 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700211 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800212 if (count < 0) {
213 loge("got " + count + " reading with start = " + start);
214 break;
215 }
Daichi Hironodda65522015-11-19 16:58:57 +0900216 fdList = socket.getAncillaryFileDescriptors();
San Mehat67bd2cd2010-01-12 12:18:49 -0800217
Kenny Root12da9d72010-09-02 22:18:14 -0700218 // Add our starting point to the count and reset the start.
219 count += start;
220 start = 0;
221
San Mehat67bd2cd2010-01-12 12:18:49 -0800222 for (int i = 0; i < count; i++) {
223 if (buffer[i] == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800224 // Note - do not log this raw message since it may contain
225 // sensitive data
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800226 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700227 buffer, start, i - start, StandardCharsets.UTF_8);
San Mehat67bd2cd2010-01-12 12:18:49 -0800228
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800229 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800230 try {
Daichi Hironodda65522015-11-19 16:58:57 +0900231 final NativeDaemonEvent event =
232 NativeDaemonEvent.parseRawEvent(rawEvent, fdList);
Paul Lawrencec38182f2014-11-11 12:23:22 -0800233
234 log("RCV <- {" + event + "}");
235
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800236 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800237 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn4590e522014-03-24 13:36:46 -0700238 if (mCallbacks.onCheckHoldWakeLock(event.getCode())
239 && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800240 mWakeLock.acquire();
241 releaseWl = true;
242 }
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900243 Message msg = mCallbackHandler.obtainMessage(
244 event.getCode(), uptimeMillisInt(), 0, event.getRawEvent());
245 if (mCallbackHandler.sendMessage(msg)) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800246 releaseWl = false;
247 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800248 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800249 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800250 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800251 } catch (IllegalArgumentException e) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800252 log("Problem parsing message " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800253 } finally {
254 if (releaseWl) {
Lorenzo Colittiae107af2016-04-11 17:08:10 +0900255 mWakeLock.release();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800256 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800257 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800258
San Mehat67bd2cd2010-01-12 12:18:49 -0800259 start = i + 1;
260 }
261 }
Paul Lawrencec38182f2014-11-11 12:23:22 -0800262
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800263 if (start == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800264 log("RCV incomplete");
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800265 }
Kenny Root12da9d72010-09-02 22:18:14 -0700266
267 // We should end at the amount we read. If not, compact then
268 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700269 if (start != count) {
270 final int remaining = BUFFER_SIZE - start;
271 System.arraycopy(buffer, start, buffer, 0, remaining);
272 start = remaining;
273 } else {
274 start = 0;
275 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800276 }
277 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800278 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800279 throw ex;
280 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700281 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800282 if (mOutputStream != null) {
283 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800284 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800285 mOutputStream.close();
286 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800287 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800288 }
289 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800290 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800291 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800292
San Mehat4c27e0e2010-01-29 05:22:17 -0800293 try {
294 if (socket != null) {
295 socket.close();
296 }
297 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800298 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800299 }
300 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800301 }
302
San Mehat67bd2cd2010-01-12 12:18:49 -0800303 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700304 * Wrapper around argument that indicates it's sensitive and shouldn't be
305 * logged.
306 */
307 public static class SensitiveArg {
308 private final Object mArg;
309
310 public SensitiveArg(Object arg) {
311 mArg = arg;
312 }
313
314 @Override
315 public String toString() {
316 return String.valueOf(mArg);
317 }
318 }
319
320 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800321 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800322 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700323 @VisibleForTesting
324 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
325 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800326 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800327 throw new IllegalArgumentException("Unexpected command: " + cmd);
328 }
329 if (cmd.indexOf(' ') >= 0) {
330 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700331 }
332
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700333 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
334 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800335 for (Object arg : args) {
336 final String argString = String.valueOf(arg);
337 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800338 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700339 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800340
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700341 rawBuilder.append(' ');
342 logBuilder.append(' ');
343
344 appendEscaped(rawBuilder, argString);
345 if (arg instanceof SensitiveArg) {
346 logBuilder.append("[scrubbed]");
347 } else {
348 appendEscaped(logBuilder, argString);
349 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800350 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700351
352 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800353 }
San Mehatdeba6932010-01-20 15:14:31 -0800354
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700355 /**
Rebecca Silbersteinefdb8452016-04-21 12:14:41 -0700356 * Method that waits until all asychronous notifications sent by the native daemon have
357 * been processed. This method must not be called on the notification thread or an
358 * exception will be thrown.
359 */
360 public void waitForCallbacks() {
361 if (Thread.currentThread() == mLooper.getThread()) {
362 throw new IllegalStateException("Must not call this method on callback thread");
363 }
364
365 final CountDownLatch latch = new CountDownLatch(1);
366 mCallbackHandler.post(new Runnable() {
367 @Override
368 public void run() {
369 latch.countDown();
370 }
371 });
372 try {
373 latch.await();
374 } catch (InterruptedException e) {
375 Slog.wtf(TAG, "Interrupted while waiting for unsolicited response handling", e);
376 }
377 }
378
379 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800380 * Issue the given command to the native daemon and return a single expected
381 * response.
382 *
383 * @throws NativeDaemonConnectorException when problem communicating with
384 * native daemon, or if the response matches
385 * {@link NativeDaemonEvent#isClassClientError()} or
386 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800387 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800388 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
389 return execute(cmd.mCmd, cmd.mArguments.toArray());
390 }
391
392 /**
393 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800394 * response. Any arguments must be separated from base command so they can
395 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800396 *
397 * @throws NativeDaemonConnectorException when problem communicating with
398 * native daemon, or if the response matches
399 * {@link NativeDaemonEvent#isClassClientError()} or
400 * {@link NativeDaemonEvent#isClassServerError()}.
401 */
402 public NativeDaemonEvent execute(String cmd, Object... args)
403 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700404 return execute(DEFAULT_TIMEOUT, cmd, args);
405 }
406
407 public NativeDaemonEvent execute(long timeoutMs, String cmd, Object... args)
408 throws NativeDaemonConnectorException {
409 final NativeDaemonEvent[] events = executeForList(timeoutMs, cmd, args);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800410 if (events.length != 1) {
411 throw new NativeDaemonConnectorException(
412 "Expected exactly one response, but received " + events.length);
413 }
414 return events[0];
415 }
416
417 /**
418 * Issue the given command to the native daemon and return any
419 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
420 * final terminal response.
421 *
422 * @throws NativeDaemonConnectorException when problem communicating with
423 * native daemon, or if the response matches
424 * {@link NativeDaemonEvent#isClassClientError()} or
425 * {@link NativeDaemonEvent#isClassServerError()}.
426 */
427 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
428 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
429 }
430
431 /**
432 * Issue the given command to the native daemon and return any
433 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800434 * final terminal response. Any arguments must be separated from base
435 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800436 *
437 * @throws NativeDaemonConnectorException when problem communicating with
438 * native daemon, or if the response matches
439 * {@link NativeDaemonEvent#isClassClientError()} or
440 * {@link NativeDaemonEvent#isClassServerError()}.
441 */
442 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800443 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700444 return executeForList(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800445 }
San Mehatdeba6932010-01-20 15:14:31 -0800446
Robert Greenwalt470007f2012-02-07 11:36:55 -0800447 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800448 * Issue the given command to the native daemon and return any {@linke
449 * NativeDaemonEvent@isClassContinue()} responses, including the final
450 * terminal response. Note that the timeout does not count time in deep
451 * sleep. Any arguments must be separated from base command so they can be
452 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800453 *
454 * @throws NativeDaemonConnectorException when problem communicating with
455 * native daemon, or if the response matches
456 * {@link NativeDaemonEvent#isClassClientError()} or
457 * {@link NativeDaemonEvent#isClassServerError()}.
458 */
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700459 public NativeDaemonEvent[] executeForList(long timeoutMs, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800460 throws NativeDaemonConnectorException {
Jeff Sharkey8948c012015-11-03 12:33:54 -0800461 if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
462 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
463 + Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800464 }
465
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700466 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700467
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700468 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700469
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700470 final StringBuilder rawBuilder = new StringBuilder();
471 final StringBuilder logBuilder = new StringBuilder();
472 final int sequenceNumber = mSequenceNumber.incrementAndGet();
473
474 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
475
476 final String rawCmd = rawBuilder.toString();
477 final String logCmd = logBuilder.toString();
478
Robert Greenwaltd1925982012-03-12 15:37:40 -0700479 log("SND -> {" + logCmd + "}");
480
Robert Greenwaltd1925982012-03-12 15:37:40 -0700481 synchronized (mDaemonLock) {
482 if (mOutputStream == null) {
483 throw new NativeDaemonConnectorException("missing output stream");
484 } else {
485 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700486 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700487 } catch (IOException e) {
488 throw new NativeDaemonConnectorException("problem sending command", e);
489 }
490 }
491 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800492
493 NativeDaemonEvent event = null;
494 do {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700495 event = mResponseQueue.remove(sequenceNumber, timeoutMs, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800496 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700497 loge("timed-out waiting for response to " + logCmd);
Todd Kennedy8101ee62015-06-23 13:35:28 -0700498 throw new NativeDaemonTimeoutException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800499 }
Robert Greenwalt7f44ff82014-05-07 23:49:08 -0700500 if (VDBG) log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800501 events.add(event);
502 } while (event.isClassContinue());
503
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700504 final long endTime = SystemClock.elapsedRealtime();
505 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
506 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
507 }
508
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800509 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700510 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800511 }
512 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700513 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800514 }
515
516 return events.toArray(new NativeDaemonEvent[events.size()]);
517 }
518
519 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800520 * Append the given argument to {@link StringBuilder}, escaping as needed,
521 * and surrounding with quotes when it contains spaces.
522 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800523 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800524 static void appendEscaped(StringBuilder builder, String arg) {
525 final boolean hasSpaces = arg.indexOf(' ') >= 0;
526 if (hasSpaces) {
527 builder.append('"');
528 }
529
530 final int length = arg.length();
531 for (int i = 0; i < length; i++) {
532 final char c = arg.charAt(i);
533
534 if (c == '"') {
535 builder.append("\\\"");
536 } else if (c == '\\') {
537 builder.append("\\\\");
538 } else {
539 builder.append(c);
540 }
541 }
542
543 if (hasSpaces) {
544 builder.append('"');
545 }
546 }
547
548 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
549 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
550 super(command, event);
551 }
552
553 @Override
554 public IllegalArgumentException rethrowAsParcelableException() {
555 throw new IllegalArgumentException(getMessage(), this);
556 }
557 }
558
559 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
560 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
561 super(command, event);
562 }
San Mehatdeba6932010-01-20 15:14:31 -0800563 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700564
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800565 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800566 * Command builder that handles argument list building. Any arguments must
567 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800568 */
569 public static class Command {
570 private String mCmd;
571 private ArrayList<Object> mArguments = Lists.newArrayList();
572
573 public Command(String cmd, Object... args) {
574 mCmd = cmd;
575 for (Object arg : args) {
576 appendArg(arg);
577 }
578 }
579
580 public Command appendArg(Object arg) {
581 mArguments.add(arg);
582 return this;
583 }
584 }
585
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700586 /** {@inheritDoc} */
587 public void monitor() {
588 synchronized (mDaemonLock) { }
589 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800590
591 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
592 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800593 pw.println();
594 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800595 }
596
597 private void log(String logstring) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700598 if (mDebug) Slog.d(TAG, logstring);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800599 mLocalLog.log(logstring);
600 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800601
602 private void loge(String logstring) {
603 Slog.e(TAG, logstring);
604 mLocalLog.log(logstring);
605 }
606
607 private static class ResponseQueue {
608
Robert Greenwaltef215992012-06-05 11:48:40 -0700609 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700610 public final int cmdNum;
611 public final String logCmd;
612
Robert Greenwaltef215992012-06-05 11:48:40 -0700613 public BlockingQueue<NativeDaemonEvent> responses =
614 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700615
616 // The availableResponseCount member is used to track when we can remove this
617 // instance from the ResponseQueue.
618 // This is used under the protection of a sync of the mPendingCmds object.
619 // A positive value means we've had more writers retreive this object while
620 // a negative value means we've had more readers. When we've had an equal number
621 // (it goes to zero) we can remove this object from the mPendingCmds list.
622 // Note that we may have more responses for this command (and more readers
623 // coming), but that would result in a new PendingCmd instance being created
624 // and added with the same cmdNum.
625 // Also note that when this goes to zero it just means a parity of readers and
626 // writers have retrieved this object - not that they are done using it. The
627 // responses queue may well have more responses yet to be read or may get more
628 // responses added to it. But all those readers/writers have retreived and
629 // hold references to this instance already so it can be removed from
630 // mPendingCmds queue.
631 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700632
633 public PendingCmd(int cmdNum, String logCmd) {
634 this.cmdNum = cmdNum;
635 this.logCmd = logCmd;
636 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800637 }
638
Robert Greenwaltef215992012-06-05 11:48:40 -0700639 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800640 private int mMaxCount;
641
642 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700643 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800644 mMaxCount = maxCount;
645 }
646
647 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700648 PendingCmd found = null;
649 synchronized (mPendingCmds) {
650 for (PendingCmd pendingCmd : mPendingCmds) {
651 if (pendingCmd.cmdNum == cmdNum) {
652 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800653 break;
654 }
655 }
656 if (found == null) {
657 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700658 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800659 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700660 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800661 " >= " + mMaxCount);
662 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700663 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800664 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700665 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700666 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800667 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700668 found = new PendingCmd(cmdNum, null);
669 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800670 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700671 found.availableResponseCount++;
672 // if a matching remove call has already retrieved this we can remove this
673 // instance from our list
674 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800675 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700676 try {
677 found.responses.put(response);
678 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800679 }
680
681 // note that the timeout does not count time in deep sleep. If you don't want
682 // the device to sleep, hold a wakelock
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700683 public NativeDaemonEvent remove(int cmdNum, long timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700684 PendingCmd found = null;
685 synchronized (mPendingCmds) {
686 for (PendingCmd pendingCmd : mPendingCmds) {
687 if (pendingCmd.cmdNum == cmdNum) {
688 found = pendingCmd;
689 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800690 }
691 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700692 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700693 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700694 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800695 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700696 found.availableResponseCount--;
697 // if a matching add call has already retrieved this we can remove this
698 // instance from our list
699 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800700 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700701 NativeDaemonEvent result = null;
702 try {
703 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
704 } catch (InterruptedException e) {}
705 if (result == null) {
706 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
707 }
708 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800709 }
710
711 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
712 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700713 synchronized (mPendingCmds) {
714 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700715 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800716 }
717 }
718 }
719 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800720}