|
| 1 | +/* |
| 2 | + * Copyright (C) 2024 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 | + |
| 17 | +package androidx.test.services.shellexecutor |
| 18 | + |
| 19 | +import android.net.LocalSocket |
| 20 | +import android.net.LocalSocketAddress |
| 21 | +import android.util.Log |
| 22 | +import androidx.test.services.shellexecutor.LocalSocketProtocolProto.RunCommandRequest |
| 23 | +import androidx.test.services.shellexecutor.LocalSocketProtocolProto.RunCommandResponse |
| 24 | +import com.google.protobuf.ByteString |
| 25 | +import java.io.IOException |
| 26 | +import java.net.URLDecoder |
| 27 | +import java.net.URLEncoder |
| 28 | +import kotlin.time.Duration |
| 29 | + |
| 30 | +/** |
| 31 | + * Protocol for ShellCommandLocalSocketClient to talk to ShellCommandLocalSocketExecutorServer. |
| 32 | + * |
| 33 | + * Since androidx.test.services already includes the protobuf runtime, we aren't paying much extra |
| 34 | + * for adding some more protos to ship back and forth, which is vastly easier to deal with than |
| 35 | + * PersistableBundles (which don't even support ByteArray types). |
| 36 | + * |
| 37 | + * A conversation consists of a single RunCommandRequest from the client followed by a stream of |
| 38 | + * RunCommandResponses from the server; the final response has an exit code. |
| 39 | + */ |
| 40 | +object LocalSocketProtocol { |
| 41 | + /** Composes a RunCommandRequest and sends it over the LocalSocket. */ |
| 42 | + fun LocalSocket.sendRequest( |
| 43 | + secret: String, |
| 44 | + argv: List<String>, |
| 45 | + env: Map<String, String>? = null, |
| 46 | + timeout: Duration, |
| 47 | + ) { |
| 48 | + val builder = RunCommandRequest.newBuilder() |
| 49 | + builder.setSecret(secret) |
| 50 | + builder.addAllArgv(argv) |
| 51 | + env?.forEach { (k, v) -> builder.putEnvironment(k, v) } |
| 52 | + if (timeout.isInfinite() || timeout.isNegative() || timeout == Duration.ZERO) { |
| 53 | + builder.setTimeoutMs(0) // <= 0 means no timeout |
| 54 | + } else { |
| 55 | + builder.setTimeoutMs(timeout.inWholeMilliseconds) |
| 56 | + } |
| 57 | + builder.build().writeDelimitedTo(outputStream) |
| 58 | + } |
| 59 | + |
| 60 | + /** Reads a RunCommandRequest from the LocalSocket. */ |
| 61 | + fun LocalSocket.readRequest(): RunCommandRequest { |
| 62 | + return RunCommandRequest.parseDelimitedFrom(inputStream)!! |
| 63 | + } |
| 64 | + |
| 65 | + /** Composes a RunCommandResponse and sends it over the LocalSocket. */ |
| 66 | + fun LocalSocket.sendResponse( |
| 67 | + buffer: ByteArray? = null, |
| 68 | + size: Int = 0, |
| 69 | + exitCode: Int? = null, |
| 70 | + ): Boolean { |
| 71 | + val builder = RunCommandResponse.newBuilder() |
| 72 | + buffer?.let { |
| 73 | + val bufferSize = if (size > 0) size else it.size |
| 74 | + builder.buffer = ByteString.copyFrom(it, 0, bufferSize) |
| 75 | + } |
| 76 | + // Since we're currently stuck on a version of protobuf where we don't have hasExitCode(), we |
| 77 | + // use a magic value to indicate that exitCode is not set. When we upgrade to a newer version |
| 78 | + // of protobuf, we can obsolete this. |
| 79 | + if (exitCode != null) { |
| 80 | + builder.exitCode = exitCode |
| 81 | + } else { |
| 82 | + builder.exitCode = HAS_NOT_EXITED |
| 83 | + } |
| 84 | + |
| 85 | + try { |
| 86 | + builder.build().writeDelimitedTo(outputStream) |
| 87 | + } catch (x: IOException) { |
| 88 | + // Sadly, the only way to discover that the client cut the connection is an exception that |
| 89 | + // can only be distinguished by its text. |
| 90 | + if (x.message.equals("Broken pipe")) { |
| 91 | + Log.i(TAG, "LocalSocket stream closed early") |
| 92 | + } else { |
| 93 | + Log.w(TAG, "LocalSocket write failed", x) |
| 94 | + } |
| 95 | + return false |
| 96 | + } |
| 97 | + return true |
| 98 | + } |
| 99 | + |
| 100 | + /** Reads a RunCommandResponse from the LocalSocket. */ |
| 101 | + fun LocalSocket.readResponse(): RunCommandResponse? { |
| 102 | + return RunCommandResponse.parseDelimitedFrom(inputStream) |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Is this the end of the stream? |
| 107 | + * |
| 108 | + * Once we upgrade to a newer version of protobuf, we can switch to hasExitCode(). |
| 109 | + */ |
| 110 | + fun RunCommandResponse.hasExited() = exitCode != HAS_NOT_EXITED |
| 111 | + |
| 112 | + /** |
| 113 | + * Builds a binder key, given the server address and secret. Binder keys should be opaque outside |
| 114 | + * this directory. |
| 115 | + * |
| 116 | + * The address can contain spaces, and since it gets passed through a command line, we need to |
| 117 | + * encode it so it doesn't get split by argv. java.net.URLEncoder is conveniently available on all |
| 118 | + * SDK versions. |
| 119 | + */ |
| 120 | + @JvmStatic |
| 121 | + fun LocalSocketAddress.asBinderKey(secret: String) = buildString { |
| 122 | + append(":") |
| 123 | + append(URLEncoder.encode(name, "UTF-8")) // Will convert any : to %3A |
| 124 | + append(":") |
| 125 | + append(URLEncoder.encode(secret, "UTF-8")) |
| 126 | + append(":") |
| 127 | + } |
| 128 | + |
| 129 | + /** Extracts the address from a binder key. */ |
| 130 | + @JvmStatic |
| 131 | + fun addressFromBinderKey(binderKey: String) = |
| 132 | + LocalSocketAddress(URLDecoder.decode(binderKey.split(":")[1], "UTF-8")) |
| 133 | + |
| 134 | + /** Extracts the secret from a binder key. */ |
| 135 | + @JvmStatic |
| 136 | + fun secretFromBinderKey(binderKey: String) = URLDecoder.decode(binderKey.split(":")[2], "UTF-8") |
| 137 | + |
| 138 | + /** Is this a valid binder key? */ |
| 139 | + @JvmStatic |
| 140 | + fun isBinderKey(maybeKey: String) = |
| 141 | + maybeKey.startsWith(':') && maybeKey.endsWith(':') && maybeKey.split(":").size == 4 |
| 142 | + |
| 143 | + const val TAG = "LocalSocketProtocol" |
| 144 | + private const val HAS_NOT_EXITED = 0xCA7F00D |
| 145 | +} |
0 commit comments