blob: f475dd6e3344a060638427ed634e7bc3fbd9ec89 [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;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070021import android.os.Handler;
22import android.os.HandlerThread;
23import android.os.Message;
San Mehat67bd2cd2010-01-12 12:18:49 -080024import android.os.SystemClock;
Robert Greenwalt470fd722012-01-18 12:51:15 -080025import android.util.LocalLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080026import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080027
Jeff Sharkey31c6e482011-11-18 17:09:01 -080028import com.google.android.collect.Lists;
29
Robert Greenwalt470fd722012-01-18 12:51:15 -080030import java.nio.charset.Charsets;
31import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080032import java.io.IOException;
33import java.io.InputStream;
34import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080035import java.io.PrintWriter;
San Mehat67bd2cd2010-01-12 12:18:49 -080036import java.util.ArrayList;
San Mehat67bd2cd2010-01-12 12:18:49 -080037import java.util.concurrent.BlockingQueue;
38import java.util.concurrent.LinkedBlockingQueue;
39
40/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080041 * Generic connector class for interfacing with a native daemon which uses the
42 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080043 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070044final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Jeff Sharkey31c6e482011-11-18 17:09:01 -080045 private static final boolean LOGD = false;
San Mehat67bd2cd2010-01-12 12:18:49 -080046
Jeff Sharkey31c6e482011-11-18 17:09:01 -080047 private final String TAG;
48
49 private String mSocket;
50 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080051 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080052
53 private final BlockingQueue<NativeDaemonEvent> mResponseQueue;
54
San Mehat67bd2cd2010-01-12 12:18:49 -080055 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080056 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080057
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070058 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080059 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070060
Kenny Root961aa8c2010-03-22 18:02:45 -070061 private final int BUFFER_SIZE = 4096;
62
Jeff Sharkey31c6e482011-11-18 17:09:01 -080063 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Robert Greenwalt470fd722012-01-18 12:51:15 -080064 int responseQueueSize, String logTag, int maxLogSize) {
San Mehat67bd2cd2010-01-12 12:18:49 -080065 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080066 mSocket = socket;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080067 mResponseQueue = new LinkedBlockingQueue<NativeDaemonEvent>(responseQueueSize);
68 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -080069 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -080070 }
71
Chia-chi Yehe5750a32011-08-03 14:42:11 -070072 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -080073 public void run() {
Chia-chi Yehe5750a32011-08-03 14:42:11 -070074 HandlerThread thread = new HandlerThread(TAG + ".CallbackHandler");
75 thread.start();
76 mCallbackHandler = new Handler(thread.getLooper(), this);
San Mehat67bd2cd2010-01-12 12:18:49 -080077
78 while (true) {
79 try {
80 listenToSocket();
81 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080082 Slog.e(TAG, "Error in NativeDaemonConnector", e);
San Mehat4c27e0e2010-01-29 05:22:17 -080083 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -080084 }
85 }
86 }
87
Chia-chi Yehe5750a32011-08-03 14:42:11 -070088 @Override
89 public boolean handleMessage(Message msg) {
90 String event = (String) msg.obj;
91 try {
92 if (!mCallbacks.onEvent(msg.what, event, event.split(" "))) {
93 Slog.w(TAG, String.format(
94 "Unhandled event '%s'", event));
95 }
96 } catch (Exception e) {
97 Slog.e(TAG, String.format(
98 "Error handling '%s'", event), e);
99 }
100 return true;
101 }
102
San Mehat4c27e0e2010-01-29 05:22:17 -0800103 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700104 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800105
106 try {
107 socket = new LocalSocket();
108 LocalSocketAddress address = new LocalSocketAddress(mSocket,
109 LocalSocketAddress.Namespace.RESERVED);
110
111 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800112
113 InputStream inputStream = socket.getInputStream();
114 mOutputStream = socket.getOutputStream();
115
anga030bc882011-02-01 14:10:25 +0100116 mCallbacks.onDaemonConnected();
117
Kenny Root961aa8c2010-03-22 18:02:45 -0700118 byte[] buffer = new byte[BUFFER_SIZE];
119 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800120
121 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700122 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
San Mehat67bd2cd2010-01-12 12:18:49 -0800123 if (count < 0) break;
124
Kenny Root12da9d72010-09-02 22:18:14 -0700125 // Add our starting point to the count and reset the start.
126 count += start;
127 start = 0;
128
San Mehat67bd2cd2010-01-12 12:18:49 -0800129 for (int i = 0; i < count; i++) {
130 if (buffer[i] == 0) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800131 final String rawEvent = new String(
132 buffer, start, i - start, Charsets.UTF_8);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800133 log("RCV <- {" + rawEvent + "}");
San Mehat67bd2cd2010-01-12 12:18:49 -0800134
San Mehat67bd2cd2010-01-12 12:18:49 -0800135 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800136 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
137 rawEvent);
138 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800139 // TODO: migrate to sending NativeDaemonEvent instances
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800140 mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
141 event.getCode(), event.getRawEvent()));
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800142 } else {
143 try {
144 mResponseQueue.put(event);
145 } catch (InterruptedException ex) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800146 Slog.e(TAG, "Failed to put response onto queue: " + ex);
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800147 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800148 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800149 } catch (IllegalArgumentException e) {
150 Slog.w(TAG, "Problem parsing message: " + rawEvent, e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800151 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800152
San Mehat67bd2cd2010-01-12 12:18:49 -0800153 start = i + 1;
154 }
155 }
Kenny Root12da9d72010-09-02 22:18:14 -0700156
157 // We should end at the amount we read. If not, compact then
158 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700159 if (start != count) {
160 final int remaining = BUFFER_SIZE - start;
161 System.arraycopy(buffer, start, buffer, 0, remaining);
162 start = remaining;
163 } else {
164 start = 0;
165 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800166 }
167 } catch (IOException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800168 Slog.e(TAG, "Communications error", ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800169 throw ex;
170 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700171 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800172 if (mOutputStream != null) {
173 try {
174 mOutputStream.close();
175 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800176 Slog.w(TAG, "Failed closing output stream", e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800177 }
178 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800179 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800180 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800181
San Mehat4c27e0e2010-01-29 05:22:17 -0800182 try {
183 if (socket != null) {
184 socket.close();
185 }
186 } catch (IOException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800187 Slog.w(TAG, "Failed closing socket", ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800188 }
189 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800190 }
191
San Mehat67bd2cd2010-01-12 12:18:49 -0800192 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800193 * Send command to daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800194 *
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800195 * @return the final command issued.
San Mehat67bd2cd2010-01-12 12:18:49 -0800196 */
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800197 private String sendCommandLocked(String cmd, Object... args)
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700198 throws NativeDaemonConnectorException {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800199 // TODO: eventually enforce that cmd doesn't contain arguments
200 if (cmd.indexOf('\0') >= 0) {
201 throw new IllegalArgumentException("unexpected command: " + cmd);
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700202 }
203
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800204 final StringBuilder builder = new StringBuilder(cmd);
205 for (Object arg : args) {
206 final String argString = String.valueOf(arg);
207 if (argString.indexOf('\0') >= 0) {
208 throw new IllegalArgumentException("unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700209 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800210
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800211 builder.append(' ');
212 appendEscaped(builder, argString);
213 }
214
215 final String unterminated = builder.toString();
Robert Greenwalt470fd722012-01-18 12:51:15 -0800216 log("SND -> {" + unterminated + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800217
218 builder.append('\0');
219
220 if (mOutputStream == null) {
221 throw new NativeDaemonConnectorException("missing output stream");
222 } else {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700223 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800224 mOutputStream.write(builder.toString().getBytes(Charsets.UTF_8));
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800225 } catch (IOException e) {
226 throw new NativeDaemonConnectorException("problem sending command", e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800227 }
228 }
229
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800230 return unterminated;
San Mehat67bd2cd2010-01-12 12:18:49 -0800231 }
San Mehatdeba6932010-01-20 15:14:31 -0800232
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700233 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800234 * Issue the given command to the native daemon and return a single expected
235 * response.
236 *
237 * @throws NativeDaemonConnectorException when problem communicating with
238 * native daemon, or if the response matches
239 * {@link NativeDaemonEvent#isClassClientError()} or
240 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800241 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800242 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
243 return execute(cmd.mCmd, cmd.mArguments.toArray());
244 }
245
246 /**
247 * Issue the given command to the native daemon and return a single expected
248 * response.
249 *
250 * @throws NativeDaemonConnectorException when problem communicating with
251 * native daemon, or if the response matches
252 * {@link NativeDaemonEvent#isClassClientError()} or
253 * {@link NativeDaemonEvent#isClassServerError()}.
254 */
255 public NativeDaemonEvent execute(String cmd, Object... args)
256 throws NativeDaemonConnectorException {
257 final NativeDaemonEvent[] events = executeForList(cmd, args);
258 if (events.length != 1) {
259 throw new NativeDaemonConnectorException(
260 "Expected exactly one response, but received " + events.length);
261 }
262 return events[0];
263 }
264
265 /**
266 * Issue the given command to the native daemon and return any
267 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
268 * final terminal response.
269 *
270 * @throws NativeDaemonConnectorException when problem communicating with
271 * native daemon, or if the response matches
272 * {@link NativeDaemonEvent#isClassClientError()} or
273 * {@link NativeDaemonEvent#isClassServerError()}.
274 */
275 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
276 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
277 }
278
279 /**
280 * Issue the given command to the native daemon and return any
281 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
282 * final terminal response.
283 *
284 * @throws NativeDaemonConnectorException when problem communicating with
285 * native daemon, or if the response matches
286 * {@link NativeDaemonEvent#isClassClientError()} or
287 * {@link NativeDaemonEvent#isClassServerError()}.
288 */
289 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800290 throws NativeDaemonConnectorException {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800291 synchronized (mDaemonLock) {
292 return executeLocked(cmd, args);
293 }
294 }
San Mehatdeba6932010-01-20 15:14:31 -0800295
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800296 private NativeDaemonEvent[] executeLocked(String cmd, Object... args)
297 throws NativeDaemonConnectorException {
298 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
San Mehatdeba6932010-01-20 15:14:31 -0800299
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800300 mResponseQueue.clear();
301
302 final String sentCommand = sendCommandLocked(cmd, args);
303
304 NativeDaemonEvent event = null;
305 do {
San Mehatdeba6932010-01-20 15:14:31 -0800306 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800307 event = mResponseQueue.take();
308 } catch (InterruptedException e) {
309 Slog.w(TAG, "interrupted waiting for event line");
310 continue;
311 }
312 events.add(event);
313 } while (event.isClassContinue());
314
315 if (event.isClassClientError()) {
316 throw new NativeDaemonArgumentException(sentCommand, event);
317 }
318 if (event.isClassServerError()) {
319 throw new NativeDaemonFailureException(sentCommand, event);
320 }
321
322 return events.toArray(new NativeDaemonEvent[events.size()]);
323 }
324
325 /**
326 * Issue a command to the native daemon and return the raw responses.
327 *
328 * @deprecated callers should move to {@link #execute(String, Object...)}
329 * which returns parsed {@link NativeDaemonEvent}.
330 */
331 @Deprecated
332 public ArrayList<String> doCommand(String cmd) throws NativeDaemonConnectorException {
333 final ArrayList<String> rawEvents = Lists.newArrayList();
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800334 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800335 for (NativeDaemonEvent event : events) {
336 rawEvents.add(event.getRawEvent());
337 }
338 return rawEvents;
339 }
340
341 /**
342 * Issues a list command and returns the cooked list of all
343 * {@link NativeDaemonEvent#getMessage()} which match requested code.
344 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800345 @Deprecated
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800346 public String[] doListCommand(String cmd, int expectedCode)
347 throws NativeDaemonConnectorException {
348 final ArrayList<String> list = Lists.newArrayList();
349
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800350 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800351 for (int i = 0; i < events.length - 1; i++) {
352 final NativeDaemonEvent event = events[i];
353 final int code = event.getCode();
354 if (code == expectedCode) {
355 list.add(event.getMessage());
356 } else {
San Mehat4c27e0e2010-01-29 05:22:17 -0800357 throw new NativeDaemonConnectorException(
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800358 "unexpected list response " + code + " instead of " + expectedCode);
San Mehatdeba6932010-01-20 15:14:31 -0800359 }
360 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800361
362 final NativeDaemonEvent finalEvent = events[events.length - 1];
363 if (!finalEvent.isClassOk()) {
364 throw new NativeDaemonConnectorException("unexpected final event: " + finalEvent);
365 }
366
367 return list.toArray(new String[list.size()]);
368 }
369
370 /**
371 * Append the given argument to {@link StringBuilder}, escaping as needed,
372 * and surrounding with quotes when it contains spaces.
373 */
374 // @VisibleForTesting
375 static void appendEscaped(StringBuilder builder, String arg) {
376 final boolean hasSpaces = arg.indexOf(' ') >= 0;
377 if (hasSpaces) {
378 builder.append('"');
379 }
380
381 final int length = arg.length();
382 for (int i = 0; i < length; i++) {
383 final char c = arg.charAt(i);
384
385 if (c == '"') {
386 builder.append("\\\"");
387 } else if (c == '\\') {
388 builder.append("\\\\");
389 } else {
390 builder.append(c);
391 }
392 }
393
394 if (hasSpaces) {
395 builder.append('"');
396 }
397 }
398
399 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
400 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
401 super(command, event);
402 }
403
404 @Override
405 public IllegalArgumentException rethrowAsParcelableException() {
406 throw new IllegalArgumentException(getMessage(), this);
407 }
408 }
409
410 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
411 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
412 super(command, event);
413 }
San Mehatdeba6932010-01-20 15:14:31 -0800414 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700415
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800416 /**
417 * Command builder that handles argument list building.
418 */
419 public static class Command {
420 private String mCmd;
421 private ArrayList<Object> mArguments = Lists.newArrayList();
422
423 public Command(String cmd, Object... args) {
424 mCmd = cmd;
425 for (Object arg : args) {
426 appendArg(arg);
427 }
428 }
429
430 public Command appendArg(Object arg) {
431 mArguments.add(arg);
432 return this;
433 }
434 }
435
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700436 /** {@inheritDoc} */
437 public void monitor() {
438 synchronized (mDaemonLock) { }
439 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800440
441 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
442 mLocalLog.dump(fd, pw, args);
443 }
444
445 private void log(String logstring) {
446 if (LOGD) Slog.d(TAG, logstring);
447 mLocalLog.log(logstring);
448 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800449}