summaryrefslogtreecommitdiff
path: root/fakeadbserver/src/main/java/com/android/fakeadbserver/services/ShellCommandOutput.kt
blob: 1dc6846b146e33d255df83db09d74b9c91908fa5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.fakeadbserver.services

import com.android.fakeadbserver.DeviceState
import com.android.fakeadbserver.ShellV2Protocol
import java.io.EOFException
import java.net.Socket
import java.nio.charset.StandardCharsets.UTF_8

/**
 * Abstraction over access to stdin/stdout/stderr/exit code of an ADB shell command.
 *
 * This allows shell command implementor in [FakeAdbServer] to have a single implementation
 * that can deal with the simplified stdin/stdout protocol, or the full [ShellV2Protocol].
 */
interface ShellCommandOutput {

    fun writeStdout(bytes: ByteArray)
    fun writeStderr(bytes: ByteArray)

    fun writeStdout(text: String) {
        writeStdout(text.toByteArray(UTF_8))
    }

    fun writeStderr(text: String) {
        writeStderr(text.toByteArray(UTF_8))
    }

    fun writeExitCode(exitCode: Int)

    fun readStdin(bytes: ByteArray, offset: Int, length: Int): Int
}

/**
 * Implementation of [ShellCommandOutput] that writes stdout/stderr directly to
 * [Socket.getOutputStream], and ignores exit code. This corresponds to how
 * the legacy "shell:" ADB service works.
 */
class LegacyShellOutput(socket: Socket, val device: DeviceState) : ShellCommandOutput {

    private val input = socket.getInputStream()
    private val output = socket.getOutputStream()

    override fun writeStdout(bytes: ByteArray) {
        output.write(bytes.replaceNewLineForOlderDevices(device))
    }

    override fun writeStderr(bytes: ByteArray) {
        output.write(bytes.replaceNewLineForOlderDevices(device))
    }

    override fun writeExitCode(exitCode: Int) {
        // This is not implemented for this version of the protocol
    }

    override fun readStdin(bytes: ByteArray, offset: Int, length: Int): Int {
        return input.read(bytes, offset, length)
    }
}

/**
 * Implementation of [ShellCommandOutput] that writes stdout/stderr directly to
 * [Socket.getOutputStream], and ignores exit code. This corresponds to how
 * the legacy "exec:" ADB service works
 */
class ExecOutput(socket: Socket) : ShellCommandOutput {

    private val input = socket.getInputStream()
    private val output = socket.getOutputStream()

    override fun writeStdout(bytes: ByteArray) {
        output.write(bytes)
    }

    override fun writeStderr(bytes: ByteArray) {
        output.write(bytes)
    }

    override fun writeExitCode(exitCode: Int) {
        // This is not implemented for this version of the protocol
    }

    override fun readStdin(bytes: ByteArray, offset: Int, length: Int): Int {
        return input.read(bytes, offset, length)
    }
}

/** Replaces '\n'->'\r\n' for older devices */
fun ByteArray.replaceNewLineForOlderDevices(device: DeviceState): ByteArray {
    val newLineByte = '\n'.code.toByte()
    if (device.apiLevel > 23 || !contains(newLineByte)) {
        return this
    }

    val newLineCount = this.count { it == newLineByte }
    val result = ByteArray(size + newLineCount)
    var outputIndex = 0
    for (byte in this) {
        if (byte == newLineByte) {
            result[outputIndex++] = '\r'.code.toByte()
        }
        result[outputIndex++] = byte
    }
    return result
}

/**
 * Implementation of [ShellCommandOutput] that read and writes from/to the underlying socket
 * using the [ShellV2Protocol]. This corresponds to how the "shell,v2:" ADB service works.
 */
class ShellV2Output(socket: Socket) : ShellCommandOutput {

    private val protocol = ShellV2Protocol(socket)

    private var currentStdinPacket: ShellV2Protocol.Packet? = null
    private var currentStdinPacketOffset = 0

    override fun writeStdout(bytes: ByteArray) {
        protocol.writeStdout(bytes)
    }

    override fun writeStderr(bytes: ByteArray) {
        protocol.writeStderr(bytes)
    }

    override fun writeExitCode(exitCode: Int) {
        protocol.writeExitCode(exitCode)
    }

    override fun readStdin(bytes: ByteArray, offset: Int, length: Int): Int {
        while (true) {
            // Process current packet if there is one (and it has remaining data)
            val packet = currentStdinPacket
            if (packet != null) {
                if (currentStdinPacketOffset < packet.bytes.size) {
                    val count = Integer.min(length, packet.bytes.size - currentStdinPacketOffset)
                    System.arraycopy(packet.bytes, currentStdinPacketOffset, bytes, offset, count)
                    currentStdinPacketOffset += count
                    return count
                }
            }

            // We need a new packet, forget the old one and read a new one
            assert(currentStdinPacket.let { it == null || it.bytes.size == currentStdinPacketOffset })
            currentStdinPacket = null
            currentStdinPacketOffset = 0

            try {
                val newPacket = protocol.readPacket()
                when (newPacket.kind) {
                    ShellV2Protocol.PacketKind.STDIN -> {
                        currentStdinPacket = newPacket
                    }
                    ShellV2Protocol.PacketKind.CLOSE_STDIN -> {
                        return -1
                    }
                    else -> {
                        // TODO: Handle other type of packets
                    }
                }
            } catch (e: EOFException) {
                return -1
            }
        }
    }
}