blob: ad02aad6e4cde1f7b1bfa5bc9bf95d5f883c819e [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) {
Tetsutoki Shiozawabe12b812017-10-27 14:03:00 +0900137 if (isShuttingDown()) break;
San Mehat67bd2cd2010-01-12 12:18:49 -0800138 try {
139 listenToSocket();
140 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800141 loge("Error in NativeDaemonConnector: " + e);
Tetsutoki Shiozawabe12b812017-10-27 14:03:00 +0900142 if (isShuttingDown()) break;
San Mehat4c27e0e2010-01-29 05:22:17 -0800143 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -0800144 }
145 }
146 }
147
Tetsutoki Shiozawabe12b812017-10-27 14:03:00 +0900148 private static boolean isShuttingDown() {
149 String shutdownAct = SystemProperties.get(
150 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
151 return shutdownAct != null && shutdownAct.length() > 0;
152 }
153
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700154 @Override
155 public boolean handleMessage(Message msg) {
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900156 final String event = (String) msg.obj;
157 final int start = uptimeMillisInt();
158 final int sent = msg.arg1;
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700159 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700160 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800161 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700162 }
163 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800164 loge("Error handling '" + event + "': " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800165 } finally {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700166 if (mCallbacks.onCheckHoldWakeLock(msg.what) && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800167 mWakeLock.release();
168 }
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900169 final int end = uptimeMillisInt();
170 if (start > sent && start - sent > WARN_EXECUTE_DELAY_MS) {
171 loge(String.format("NDC event {%s} processed too late: %dms", event, start - sent));
172 }
173 if (end > start && end - start > WARN_EXECUTE_DELAY_MS) {
174 loge(String.format("NDC event {%s} took too long: %dms", event, end - start));
175 }
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700176 }
177 return true;
178 }
179
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900180 private LocalSocketAddress determineSocketAddress() {
181 // If we're testing, set up a socket in a namespace that's accessible to test code.
182 // In order to ensure that unprivileged apps aren't able to impersonate native daemons on
183 // production devices, even if said native daemons ill-advisedly pick a socket name that
184 // starts with __test__, only allow this on debug builds.
185 if (mSocket.startsWith("__test__") && Build.IS_DEBUGGABLE) {
186 return new LocalSocketAddress(mSocket);
187 } else {
188 return new LocalSocketAddress(mSocket, LocalSocketAddress.Namespace.RESERVED);
189 }
190 }
191
San Mehat4c27e0e2010-01-29 05:22:17 -0800192 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700193 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800194
195 try {
196 socket = new LocalSocket();
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900197 LocalSocketAddress address = determineSocketAddress();
San Mehat67bd2cd2010-01-12 12:18:49 -0800198
199 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800200
201 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800202 synchronized (mDaemonLock) {
203 mOutputStream = socket.getOutputStream();
204 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800205
anga030bc882011-02-01 14:10:25 +0100206 mCallbacks.onDaemonConnected();
207
Daichi Hironodda65522015-11-19 16:58:57 +0900208 FileDescriptor[] fdList = null;
Kenny Root961aa8c2010-03-22 18:02:45 -0700209 byte[] buffer = new byte[BUFFER_SIZE];
210 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800211
212 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700213 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800214 if (count < 0) {
215 loge("got " + count + " reading with start = " + start);
216 break;
217 }
Daichi Hironodda65522015-11-19 16:58:57 +0900218 fdList = socket.getAncillaryFileDescriptors();
San Mehat67bd2cd2010-01-12 12:18:49 -0800219
Kenny Root12da9d72010-09-02 22:18:14 -0700220 // Add our starting point to the count and reset the start.
221 count += start;
222 start = 0;
223
San Mehat67bd2cd2010-01-12 12:18:49 -0800224 for (int i = 0; i < count; i++) {
225 if (buffer[i] == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800226 // Note - do not log this raw message since it may contain
227 // sensitive data
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800228 final String rawEvent = new String(
Elliott Hughesd396a442013-06-28 16:24:48 -0700229 buffer, start, i - start, StandardCharsets.UTF_8);
San Mehat67bd2cd2010-01-12 12:18:49 -0800230
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800231 boolean releaseWl = false;
San Mehat67bd2cd2010-01-12 12:18:49 -0800232 try {
Daichi Hironodda65522015-11-19 16:58:57 +0900233 final NativeDaemonEvent event =
234 NativeDaemonEvent.parseRawEvent(rawEvent, fdList);
Paul Lawrencec38182f2014-11-11 12:23:22 -0800235
236 log("RCV <- {" + event + "}");
237
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800238 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800239 // TODO: migrate to sending NativeDaemonEvent instances
Dianne Hackborn4590e522014-03-24 13:36:46 -0700240 if (mCallbacks.onCheckHoldWakeLock(event.getCode())
241 && mWakeLock != null) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800242 mWakeLock.acquire();
243 releaseWl = true;
244 }
Lorenzo Colitticd63d242016-04-10 15:39:53 +0900245 Message msg = mCallbackHandler.obtainMessage(
246 event.getCode(), uptimeMillisInt(), 0, event.getRawEvent());
247 if (mCallbackHandler.sendMessage(msg)) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800248 releaseWl = false;
249 }
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800250 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800251 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800252 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800253 } catch (IllegalArgumentException e) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800254 log("Problem parsing message " + e);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800255 } finally {
256 if (releaseWl) {
Lorenzo Colittiae107af2016-04-11 17:08:10 +0900257 mWakeLock.release();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800258 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800259 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800260
San Mehat67bd2cd2010-01-12 12:18:49 -0800261 start = i + 1;
262 }
263 }
Paul Lawrencec38182f2014-11-11 12:23:22 -0800264
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800265 if (start == 0) {
Paul Lawrencec38182f2014-11-11 12:23:22 -0800266 log("RCV incomplete");
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800267 }
Kenny Root12da9d72010-09-02 22:18:14 -0700268
269 // We should end at the amount we read. If not, compact then
270 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700271 if (start != count) {
272 final int remaining = BUFFER_SIZE - start;
273 System.arraycopy(buffer, start, buffer, 0, remaining);
274 start = remaining;
275 } else {
276 start = 0;
277 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800278 }
279 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800280 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800281 throw ex;
282 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700283 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800284 if (mOutputStream != null) {
285 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800286 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800287 mOutputStream.close();
288 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800289 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800290 }
291 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800292 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800293 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800294
San Mehat4c27e0e2010-01-29 05:22:17 -0800295 try {
296 if (socket != null) {
297 socket.close();
298 }
299 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800300 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800301 }
302 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800303 }
304
San Mehat67bd2cd2010-01-12 12:18:49 -0800305 /**
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700306 * Wrapper around argument that indicates it's sensitive and shouldn't be
307 * logged.
308 */
309 public static class SensitiveArg {
310 private final Object mArg;
311
312 public SensitiveArg(Object arg) {
313 mArg = arg;
314 }
315
316 @Override
317 public String toString() {
318 return String.valueOf(mArg);
319 }
320 }
321
322 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800323 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800324 */
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700325 @VisibleForTesting
326 static void makeCommand(StringBuilder rawBuilder, StringBuilder logBuilder, int sequenceNumber,
327 String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800328 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800329 throw new IllegalArgumentException("Unexpected command: " + cmd);
330 }
331 if (cmd.indexOf(' ') >= 0) {
332 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700333 }
334
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700335 rawBuilder.append(sequenceNumber).append(' ').append(cmd);
336 logBuilder.append(sequenceNumber).append(' ').append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800337 for (Object arg : args) {
338 final String argString = String.valueOf(arg);
339 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800340 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700341 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800342
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700343 rawBuilder.append(' ');
344 logBuilder.append(' ');
345
346 appendEscaped(rawBuilder, argString);
347 if (arg instanceof SensitiveArg) {
348 logBuilder.append("[scrubbed]");
349 } else {
350 appendEscaped(logBuilder, argString);
351 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800352 }
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700353
354 rawBuilder.append('\0');
San Mehat67bd2cd2010-01-12 12:18:49 -0800355 }
San Mehatdeba6932010-01-20 15:14:31 -0800356
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700357 /**
Rebecca Silbersteinefdb8452016-04-21 12:14:41 -0700358 * Method that waits until all asychronous notifications sent by the native daemon have
359 * been processed. This method must not be called on the notification thread or an
360 * exception will be thrown.
361 */
362 public void waitForCallbacks() {
363 if (Thread.currentThread() == mLooper.getThread()) {
364 throw new IllegalStateException("Must not call this method on callback thread");
365 }
366
367 final CountDownLatch latch = new CountDownLatch(1);
368 mCallbackHandler.post(new Runnable() {
369 @Override
370 public void run() {
371 latch.countDown();
372 }
373 });
374 try {
375 latch.await();
376 } catch (InterruptedException e) {
377 Slog.wtf(TAG, "Interrupted while waiting for unsolicited response handling", e);
378 }
379 }
380
381 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800382 * Issue the given command to the native daemon and return a single expected
383 * response.
384 *
385 * @throws NativeDaemonConnectorException when problem communicating with
386 * native daemon, or if the response matches
387 * {@link NativeDaemonEvent#isClassClientError()} or
388 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800389 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800390 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
391 return execute(cmd.mCmd, cmd.mArguments.toArray());
392 }
393
394 /**
395 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800396 * response. Any arguments must be separated from base command so they can
397 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800398 *
399 * @throws NativeDaemonConnectorException when problem communicating with
400 * native daemon, or if the response matches
401 * {@link NativeDaemonEvent#isClassClientError()} or
402 * {@link NativeDaemonEvent#isClassServerError()}.
403 */
404 public NativeDaemonEvent execute(String cmd, Object... args)
405 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700406 return execute(DEFAULT_TIMEOUT, cmd, args);
407 }
408
409 public NativeDaemonEvent execute(long timeoutMs, String cmd, Object... args)
410 throws NativeDaemonConnectorException {
411 final NativeDaemonEvent[] events = executeForList(timeoutMs, cmd, args);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800412 if (events.length != 1) {
413 throw new NativeDaemonConnectorException(
414 "Expected exactly one response, but received " + events.length);
415 }
416 return events[0];
417 }
418
419 /**
420 * Issue the given command to the native daemon and return any
421 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
422 * final terminal response.
423 *
424 * @throws NativeDaemonConnectorException when problem communicating with
425 * native daemon, or if the response matches
426 * {@link NativeDaemonEvent#isClassClientError()} or
427 * {@link NativeDaemonEvent#isClassServerError()}.
428 */
429 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
430 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
431 }
432
433 /**
434 * Issue the given command to the native daemon and return any
435 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800436 * final terminal response. Any arguments must be separated from base
437 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800438 *
439 * @throws NativeDaemonConnectorException when problem communicating with
440 * native daemon, or if the response matches
441 * {@link NativeDaemonEvent#isClassClientError()} or
442 * {@link NativeDaemonEvent#isClassServerError()}.
443 */
444 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800445 throws NativeDaemonConnectorException {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700446 return executeForList(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800447 }
San Mehatdeba6932010-01-20 15:14:31 -0800448
Robert Greenwalt470007f2012-02-07 11:36:55 -0800449 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800450 * Issue the given command to the native daemon and return any {@linke
451 * NativeDaemonEvent@isClassContinue()} responses, including the final
452 * terminal response. Note that the timeout does not count time in deep
453 * sleep. Any arguments must be separated from base command so they can be
454 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800455 *
456 * @throws NativeDaemonConnectorException when problem communicating with
457 * native daemon, or if the response matches
458 * {@link NativeDaemonEvent#isClassClientError()} or
459 * {@link NativeDaemonEvent#isClassServerError()}.
460 */
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700461 public NativeDaemonEvent[] executeForList(long timeoutMs, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800462 throws NativeDaemonConnectorException {
Jeff Sharkey8948c012015-11-03 12:33:54 -0800463 if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
464 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
465 + Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
Jeff Sharkeye41dc592015-11-03 10:39:42 -0800466 }
467
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700468 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700469
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700470 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700471
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700472 final StringBuilder rawBuilder = new StringBuilder();
473 final StringBuilder logBuilder = new StringBuilder();
474 final int sequenceNumber = mSequenceNumber.incrementAndGet();
475
476 makeCommand(rawBuilder, logBuilder, sequenceNumber, cmd, args);
477
478 final String rawCmd = rawBuilder.toString();
479 final String logCmd = logBuilder.toString();
480
Robert Greenwaltd1925982012-03-12 15:37:40 -0700481 log("SND -> {" + logCmd + "}");
482
Robert Greenwaltd1925982012-03-12 15:37:40 -0700483 synchronized (mDaemonLock) {
484 if (mOutputStream == null) {
485 throw new NativeDaemonConnectorException("missing output stream");
486 } else {
487 try {
Elliott Hughesb8292832013-06-28 16:50:13 -0700488 mOutputStream.write(rawCmd.getBytes(StandardCharsets.UTF_8));
Robert Greenwaltd1925982012-03-12 15:37:40 -0700489 } catch (IOException e) {
490 throw new NativeDaemonConnectorException("problem sending command", e);
491 }
492 }
493 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800494
495 NativeDaemonEvent event = null;
496 do {
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700497 event = mResponseQueue.remove(sequenceNumber, timeoutMs, logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800498 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700499 loge("timed-out waiting for response to " + logCmd);
Todd Kennedy8101ee62015-06-23 13:35:28 -0700500 throw new NativeDaemonTimeoutException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800501 }
Robert Greenwalt7f44ff82014-05-07 23:49:08 -0700502 if (VDBG) log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800503 events.add(event);
504 } while (event.isClassContinue());
505
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700506 final long endTime = SystemClock.elapsedRealtime();
507 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
508 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
509 }
510
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800511 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700512 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800513 }
514 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700515 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800516 }
517
518 return events.toArray(new NativeDaemonEvent[events.size()]);
519 }
520
521 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800522 * Append the given argument to {@link StringBuilder}, escaping as needed,
523 * and surrounding with quotes when it contains spaces.
524 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800525 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800526 static void appendEscaped(StringBuilder builder, String arg) {
527 final boolean hasSpaces = arg.indexOf(' ') >= 0;
528 if (hasSpaces) {
529 builder.append('"');
530 }
531
532 final int length = arg.length();
533 for (int i = 0; i < length; i++) {
534 final char c = arg.charAt(i);
535
536 if (c == '"') {
537 builder.append("\\\"");
538 } else if (c == '\\') {
539 builder.append("\\\\");
540 } else {
541 builder.append(c);
542 }
543 }
544
545 if (hasSpaces) {
546 builder.append('"');
547 }
548 }
549
550 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
551 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
552 super(command, event);
553 }
554
555 @Override
556 public IllegalArgumentException rethrowAsParcelableException() {
557 throw new IllegalArgumentException(getMessage(), this);
558 }
559 }
560
561 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
562 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
563 super(command, event);
564 }
San Mehatdeba6932010-01-20 15:14:31 -0800565 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700566
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800567 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800568 * Command builder that handles argument list building. Any arguments must
569 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800570 */
571 public static class Command {
572 private String mCmd;
573 private ArrayList<Object> mArguments = Lists.newArrayList();
574
575 public Command(String cmd, Object... args) {
576 mCmd = cmd;
577 for (Object arg : args) {
578 appendArg(arg);
579 }
580 }
581
582 public Command appendArg(Object arg) {
583 mArguments.add(arg);
584 return this;
585 }
586 }
587
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700588 /** {@inheritDoc} */
589 public void monitor() {
590 synchronized (mDaemonLock) { }
591 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800592
593 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
594 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800595 pw.println();
596 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800597 }
598
599 private void log(String logstring) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700600 if (mDebug) Slog.d(TAG, logstring);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800601 mLocalLog.log(logstring);
602 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800603
604 private void loge(String logstring) {
605 Slog.e(TAG, logstring);
606 mLocalLog.log(logstring);
607 }
608
609 private static class ResponseQueue {
610
Robert Greenwaltef215992012-06-05 11:48:40 -0700611 private static class PendingCmd {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700612 public final int cmdNum;
613 public final String logCmd;
614
Robert Greenwaltef215992012-06-05 11:48:40 -0700615 public BlockingQueue<NativeDaemonEvent> responses =
616 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwaltef215992012-06-05 11:48:40 -0700617
618 // The availableResponseCount member is used to track when we can remove this
619 // instance from the ResponseQueue.
620 // This is used under the protection of a sync of the mPendingCmds object.
621 // A positive value means we've had more writers retreive this object while
622 // a negative value means we've had more readers. When we've had an equal number
623 // (it goes to zero) we can remove this object from the mPendingCmds list.
624 // Note that we may have more responses for this command (and more readers
625 // coming), but that would result in a new PendingCmd instance being created
626 // and added with the same cmdNum.
627 // Also note that when this goes to zero it just means a parity of readers and
628 // writers have retrieved this object - not that they are done using it. The
629 // responses queue may well have more responses yet to be read or may get more
630 // responses added to it. But all those readers/writers have retreived and
631 // hold references to this instance already so it can be removed from
632 // mPendingCmds queue.
633 public int availableResponseCount;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700634
635 public PendingCmd(int cmdNum, String logCmd) {
636 this.cmdNum = cmdNum;
637 this.logCmd = logCmd;
638 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800639 }
640
Robert Greenwaltef215992012-06-05 11:48:40 -0700641 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800642 private int mMaxCount;
643
644 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700645 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800646 mMaxCount = maxCount;
647 }
648
649 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700650 PendingCmd found = null;
651 synchronized (mPendingCmds) {
652 for (PendingCmd pendingCmd : mPendingCmds) {
653 if (pendingCmd.cmdNum == cmdNum) {
654 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800655 break;
656 }
657 }
658 if (found == null) {
659 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700660 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800661 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700662 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800663 " >= " + mMaxCount);
664 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700665 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800666 Slog.e("NativeDaemonConnector.ResponseQueue",
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700667 "Removing request: " + pendingCmd.logCmd + " (" +
Robert Greenwaltef215992012-06-05 11:48:40 -0700668 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800669 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700670 found = new PendingCmd(cmdNum, null);
671 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800672 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700673 found.availableResponseCount++;
674 // if a matching remove call has already retrieved this we can remove this
675 // instance from our list
676 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800677 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700678 try {
679 found.responses.put(response);
680 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800681 }
682
683 // note that the timeout does not count time in deep sleep. If you don't want
684 // the device to sleep, hold a wakelock
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700685 public NativeDaemonEvent remove(int cmdNum, long timeoutMs, String logCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700686 PendingCmd found = null;
687 synchronized (mPendingCmds) {
688 for (PendingCmd pendingCmd : mPendingCmds) {
689 if (pendingCmd.cmdNum == cmdNum) {
690 found = pendingCmd;
691 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800692 }
693 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700694 if (found == null) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700695 found = new PendingCmd(cmdNum, logCmd);
Robert Greenwaltef215992012-06-05 11:48:40 -0700696 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800697 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700698 found.availableResponseCount--;
699 // if a matching add call has already retrieved this we can remove this
700 // instance from our list
701 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800702 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700703 NativeDaemonEvent result = null;
704 try {
705 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
706 } catch (InterruptedException e) {}
707 if (result == null) {
708 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
709 }
710 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800711 }
712
713 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
714 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700715 synchronized (mPendingCmds) {
716 for (PendingCmd pendingCmd : mPendingCmds) {
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700717 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.logCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800718 }
719 }
720 }
721 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800722}