leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

프로젝트 초기 구성

- Rust 호스트 클라이언트 크레이트와 제어 채널 프레이밍(12바이트 공통 헤더, 메시지 타입, 부분 수신을 처리하는 FrameDecoder) 및 테스트
- Android 동반 앱/데몬 Gradle 프로젝트(AGP 9.5.2, minSdk 35)와 데몬 진입점, 프로토콜 상수
- README, .gitignore, .gitattributes
작성자
LeeJunyoung
작성 시각
커밋
f1702c24c797574be9d1e454dc44d41544dc5a30
부모
없음 (첫 커밋)
이 시점의 파일 보기

변경된 파일 26개

+1,010-0
추가.gitattributes+3-0
@@ -0,0 +1,3 @@
1추가: * text=auto eol=lf
2추가: *.bat text eol=crlf
3추가: *.jar binary
추가.gitignore+21-0
@@ -0,0 +1,21 @@
1추가: # Rust
2추가: /target/
3추가:
4추가: # Gradle / Android
5추가: .gradle/
6추가: .kotlin/
7추가: build/
8추가: local.properties
9추가: captures/
10추가: .externalNativeBuild/
11추가: .cxx/
12추가: *.apk
13추가: *.aab
14추가: *.keystore
15추가: *.jks
16추가:
17추가: # IDE / OS
18추가: .idea/
19추가: *.iml
20추가: .vscode/
21추가: .DS_Store
추가Cargo.lock+16-0
@@ -0,0 +1,16 @@
1추가: # This file is automatically @generated by Cargo.
2추가: # It is not intended for manual editing.
3추가: version = 4
4추가:
5추가: [[package]]
6추가: name = "bytes"
7추가: version = "1.12.2"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
10추가:
11추가: [[package]]
12추가: name = "wayland-android-remote"
13추가: version = "0.1.0"
14추가: dependencies = [
15추가: "bytes",
16추가: ]
추가Cargo.toml+13-0
@@ -0,0 +1,13 @@
1추가: [package]
2추가: name = "wayland-android-remote"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: description = "Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 호스트 클라이언트"
6추가: publish = false
7추가:
8추가: [[bin]]
9추가: name = "android-remote"
10추가: path = "src/main.rs"
11추가:
12추가: [dependencies]
13추가: bytes = "1.12.2"
추가README.md+41-0
@@ -0,0 +1,41 @@
1추가: # wayland-android-remote
2추가:
3추가: Ubuntu(Wayland/X11)에서 Android 기기 화면을 실시간으로 미러링하고, PC의 마우스와 키보드로 원격 제어하는 프로젝트입니다. 호스트 PC와 휴대폰 간 텍스트를 Ctrl+C / Ctrl+V로 주고받는 양방향 클립보드 동기화를 지원합니다.
4추가:
5추가: 자세한 설계는 Google Docs의 "Android Remote 기획서"에 있습니다.
6추가:
7추가: ## 구성
8추가:
9추가: | 경로 | 내용 |
10추가: |---|---|
11추가: | `src/`, `tests/` | 호스트 클라이언트 (Rust). 현재는 제어 채널 프레이밍(`src/protocol`)만 구현되어 있습니다. |
12추가: | `android/` | Android 동반 앱과 shell 권한 데몬 (Kotlin, Gradle). 데몬은 동반 앱 APK 안에 함께 들어가며 `app_process`로 실행됩니다. |
13추가:
14추가: ## 연결 구조 요약
15추가:
16추가: 1. 동반 앱이 기기 자신의 무선 디버깅에 접속해 shell 권한 데몬을 띄웁니다. 호스트 PC에는 ADB가 필요 없습니다.
17추가: 2. 데몬은 TCP 27200 포트에서 대기하고, 모든 연결은 TLS 1.3으로 암호화합니다.
18추가: 3. 호스트는 IP를 입력해 접속하고 Ed25519 키로 인증합니다. 처음 접속하는 PC는 휴대폰에서 승인합니다.
19추가: 4. 제어 채널(입력, 클립보드)과 영상 채널(H.264/H.265/AV1)은 별도 TCP 연결로 나뉩니다.
20추가:
21추가: ## 개발 환경
22추가:
23추가: ### 호스트 (Rust)
24추가:
25추가: - Rust 1.85 이상 (edition 2024)
26추가:
27추가: ```bash
28추가: cargo test
29추가: cargo run
30추가: ```
31추가:
32추가: ### Android
33추가:
34추가: - JDK 17 이상 (javac 포함)
35추가: - Android SDK (compileSdk 36), `android/local.properties`에 `sdk.dir` 지정 또는 `ANDROID_HOME` 설정
36추가: - 대상 기기: Android 15(API 35) 이상
37추가:
38추가: ```bash
39추가: cd android
40추가: ./gradlew assembleDebug
41추가: ```
추가android/app/build.gradle.kts+33-0
@@ -0,0 +1,33 @@
1추가: plugins {
2추가: alias(libs.plugins.android.application)
3추가: }
4추가:
5추가: android {
6추가: namespace = "com.androidremote"
7추가: compileSdk = 36
8추가:
9추가: defaultConfig {
10추가: applicationId = "com.androidremote"
11추가: // 기획서 2절: Android 15(API 35) 이상
12추가: minSdk = 35
13추가: targetSdk = 36
14추가: // 데몬 버전 = APK versionCode (기획서 5.4)
15추가: versionCode = 1
16추가: versionName = "0.1.0"
17추가: }
18추가:
19추가: buildTypes {
20추가: release {
21추가: isMinifyEnabled = false
22추가: proguardFiles(
23추가: getDefaultProguardFile("proguard-android-optimize.txt"),
24추가: "proguard-rules.pro",
25추가: )
26추가: }
27추가: }
28추가:
29추가: compileOptions {
30추가: sourceCompatibility = JavaVersion.VERSION_17
31추가: targetCompatibility = JavaVersion.VERSION_17
32추가: }
33추가: }
추가android/app/proguard-rules.pro+4-0
@@ -0,0 +1,4 @@
1추가: # 데몬은 app_process로 직접 실행되므로 앱 코드에서 참조되지 않는다. 축소 시 지워지지 않게 유지한다.
2추가: -keep class com.androidremote.daemon.DaemonMain {
3추가: public static void main(java.lang.String[]);
4추가: }
추가android/app/src/main/AndroidManifest.xml+30-0
@@ -0,0 +1,30 @@
1추가: <?xml version="1.0" encoding="utf-8"?>
2추가: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3추가: xmlns:tools="http://schemas.android.com/tools">
4추가:
5추가: <!-- 로컬 adbd(무선 디버깅) 접속 및 mDNS 탐색 (기획서 5.4) -->
6추가: <uses-permission android:name="android.permission.INTERNET" />
7추가: <!-- 페어링 코드 입력 알림, 신규 PC 승인 알림 -->
8추가: <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
9추가: <!-- 재부팅 후 데몬 자동 재기동 -->
10추가: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
11추가: <!-- 데몬이 pm grant로 부여한다. adb_wifi_enabled 토글용 -->
12추가: <uses-permission
13추가: android:name="android.permission.WRITE_SECURE_SETTINGS"
14추가: tools:ignore="ProtectedPermissions" />
15추가:
16추가: <application
17추가: android:allowBackup="false"
18추가: android:label="@string/app_name"
19추가: android:theme="@android:style/Theme.DeviceDefault.DayNight">
20추가:
21추가: <activity
22추가: android:name=".companion.MainActivity"
23추가: android:exported="true">
24추가: <intent-filter>
25추가: <action android:name="android.intent.action.MAIN" />
26추가: <category android:name="android.intent.category.LAUNCHER" />
27추가: </intent-filter>
28추가: </activity>
29추가: </application>
30추가: </manifest>
추가android/app/src/main/java/com/androidremote/companion/MainActivity.kt+22-0
@@ -0,0 +1,22 @@
1추가: package com.androidremote.companion
2추가:
3추가: import android.app.Activity
4추가: import android.os.Bundle
5추가: import android.view.Gravity
6추가: import android.widget.TextView
7추가: import com.androidremote.R
8추가:
9추가: /**
10추가: * 동반 앱 진입 화면. 이후 온보딩(무선 디버깅 페어링), 허용 PC 목록, 승인 팝업이 들어간다 (기획서 5.1, 5.2, 5.4).
11추가: */
12추가: class MainActivity : Activity() {
13추가: override fun onCreate(savedInstanceState: Bundle?) {
14추가: super.onCreate(savedInstanceState)
15추가: setContentView(
16추가: TextView(this).apply {
17추가: setText(R.string.status_not_implemented)
18추가: gravity = Gravity.CENTER
19추가: },
20추가: )
21추가: }
22추가: }
추가android/app/src/main/java/com/androidremote/daemon/DaemonMain.kt+25-0
@@ -0,0 +1,25 @@
1추가: package com.androidremote.daemon
2추가:
3추가: /**
4추가: * shell 권한 데몬 진입점 (기획서 5.4).
5추가: *
6추가: * 동반 앱이 로컬 adbd에 접속해 다음처럼 실행한다.
7추가: * `CLASSPATH=<APK 경로> app_process / com.androidremote.daemon.DaemonMain --port 27200`
8추가: */
9추가: object DaemonMain {
10추가: const val DEFAULT_PORT = 27200
11추가:
12추가: @JvmStatic
13추가: fun main(args: Array<String>) {
14추가: val port = parsePort(args)
15추가: println("android-remote daemon: port=$port (아직 구현 전)")
16추가: }
17추가:
18추가: internal fun parsePort(args: Array<String>): Int {
19추가: val i = args.indexOf("--port")
20추가: if (i < 0) return DEFAULT_PORT
21추가: val value = args.getOrNull(i + 1)?.toIntOrNull()
22추가: require(value != null && value in 1..65535) { "--port 값이 올바르지 않습니다: ${args.getOrNull(i + 1)}" }
23추가: return value
24추가: }
25추가: }
추가android/app/src/main/java/com/androidremote/daemon/Protocol.kt+33-0
@@ -0,0 +1,33 @@
1추가: package com.androidremote.daemon
2추가:
3추가: /**
4추가: * 제어 채널 프레이밍 상수 (기획서 7.1, 7.2). 호스트의 Rust `protocol` 모듈과 값이 같아야 한다.
5추가: * JVM ByteBuffer/DataInputStream 기본 바이트 순서가 Big-Endian이라 별도 변환 없이 읽는다.
6추가: */
7추가: object Protocol {
8추가: const val MAGIC: Int = 0x4152
9추가: const val VERSION: Int = 0x01
10추가: const val HEADER_LEN: Int = 12
11추가: const val MAX_PAYLOAD_LEN: Int = 4 * 1024 * 1024
12추가:
13추가: object MsgType {
14추가: const val PING = 0x01
15추가: const val PONG = 0x02
16추가: const val AUTH_HELLO = 0x03
17추가: const val AUTH_CHALLENGE = 0x04
18추가: const val AUTH_RESPONSE = 0x05
19추가: const val AUTH_RESULT = 0x06
20추가: const val CHANNEL_ATTACH = 0x07
21추가: const val KEY_EVENT = 0x10
22추가: const val TEXT_INPUT = 0x11
23추가: const val SYSTEM_ACTION = 0x12
24추가: const val CLIPBOARD_SYNC = 0x20
25추가: const val TOUCH_EVENT = 0x30
26추가: const val SCROLL_EVENT = 0x31
27추가: const val VIDEO_CONFIG_REQUEST = 0x40
28추가: const val VIDEO_CONFIG = 0x41
29추가: const val VIDEO_REQUEST_KEYFRAME = 0x42
30추가: const val ACK = 0xF0
31추가: const val ERROR = 0xFF
32추가: }
33추가: }
추가android/app/src/main/res/values/strings.xml+5-0
@@ -0,0 +1,5 @@
1추가: <?xml version="1.0" encoding="utf-8"?>
2추가: <resources>
3추가: <string name="app_name">Android Remote</string>
4추가: <string name="status_not_implemented">동반 앱 준비 중입니다.</string>
5추가: </resources>
추가android/build.gradle.kts+3-0
@@ -0,0 +1,3 @@
1추가: plugins {
2추가: alias(libs.plugins.android.application) apply false
3추가: }
추가android/gradle.properties+2-0
@@ -0,0 +1,2 @@
1추가: org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
2추가: org.gradle.configuration-cache=true
추가android/gradle/libs.versions.toml+5-0
@@ -0,0 +1,5 @@
1추가: [versions]
2추가: agp = "9.5.2"
3추가:
4추가: [plugins]
5추가: android-application = { id = "com.android.application", version.ref = "agp" }
추가android/gradle/wrapper/gradle-wrapper.jar

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가android/gradle/wrapper/gradle-wrapper.properties+9-0
@@ -0,0 +1,9 @@
1추가: distributionBase=GRADLE_USER_HOME
2추가: distributionPath=wrapper/dists
3추가: distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-bin.zip
4추가: networkTimeout=10000
5추가: retries=0
6추가: retryBackOffMs=500
7추가: validateDistributionUrl=true
8추가: zipStoreBase=GRADLE_USER_HOME
9추가: zipStorePath=wrapper/dists
추가android/gradlew+248-0
@@ -0,0 +1,248 @@
1추가: #!/bin/sh
2추가:
3추가: #
4추가: # Copyright © 2015 the original authors.
5추가: #
6추가: # Licensed under the Apache License, Version 2.0 (the "License");
7추가: # you may not use this file except in compliance with the License.
8추가: # You may obtain a copy of the License at
9추가: #
10추가: # https://www.apache.org/licenses/LICENSE-2.0
11추가: #
12추가: # Unless required by applicable law or agreed to in writing, software
13추가: # distributed under the License is distributed on an "AS IS" BASIS,
14추가: # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15추가: # See the License for the specific language governing permissions and
16추가: # limitations under the License.
17추가: #
18추가: # SPDX-License-Identifier: Apache-2.0
19추가: #
20추가:
21추가: ##############################################################################
22추가: #
23추가: # gradlew start up script for POSIX generated by Gradle.
24추가: #
25추가: # Important for running:
26추가: #
27추가: # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28추가: # noncompliant, but you have some other compliant shell such as ksh or
29추가: # bash, then to run this script, type that shell name before the whole
30추가: # command line, like:
31추가: #
32추가: # ksh gradlew
33추가: #
34추가: # Busybox and similar reduced shells will NOT work, because this script
35추가: # requires all of these POSIX shell features:
36추가: # * functions;
37추가: # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38추가: # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39추가: # * compound commands having a testable exit status, especially «case»;
40추가: # * various built-in commands including «command», «set», and «ulimit».
41추가: #
42추가: # Important for patching:
43추가: #
44추가: # (2) This script targets any POSIX shell, so it avoids extensions provided
45추가: # by Bash, Ksh, etc; in particular arrays are avoided.
46추가: #
47추가: # The "traditional" practice of packing multiple parameters into a
48추가: # space-separated string is a well documented source of bugs and security
49추가: # problems, so this is (mostly) avoided, by progressively accumulating
50추가: # options in "$@", and eventually passing that to Java.
51추가: #
52추가: # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53추가: # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54추가: # see the in-line comments for details.
55추가: #
56추가: # There are tweaks for specific operating systems such as AIX, CygWin,
57추가: # Darwin, MinGW, and NonStop.
58추가: #
59추가: # (3) This script is generated from the Groovy template
60추가: # https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61추가: # within the Gradle project.
62추가: #
63추가: # You can find Gradle at https://github.com/gradle/gradle/.
64추가: #
65추가: ##############################################################################
66추가:
67추가: # Attempt to set APP_HOME
68추가:
69추가: # Resolve links: $0 may be a link
70추가: app_path=$0
71추가:
72추가: # Need this for daisy-chained symlinks.
73추가: while
74추가: APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75추가: [ -h "$app_path" ]
76추가: do
77추가: ls=$( ls -ld "$app_path" )
78추가: link=${ls#*' -> '}
79추가: case $link in #(
80추가: /*) app_path=$link ;; #(
81추가: *) app_path=$APP_HOME$link ;;
82추가: esac
83추가: done
84추가:
85추가: # This is normally unused
86추가: # shellcheck disable=SC2034
87추가: APP_BASE_NAME=${0##*/}
88추가: # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89추가: APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90추가:
91추가: # Use the maximum available, or set MAX_FD != -1 to use that value.
92추가: MAX_FD=maximum
93추가:
94추가: warn () {
95추가: echo "$*"
96추가: } >&2
97추가:
98추가: die () {
99추가: echo
100추가: echo "$*"
101추가: echo
102추가: exit 1
103추가: } >&2
104추가:
105추가: # OS specific support (must be 'true' or 'false').
106추가: cygwin=false
107추가: msys=false
108추가: darwin=false
109추가: nonstop=false
110추가: case "$( uname )" in #(
111추가: CYGWIN* ) cygwin=true ;; #(
112추가: Darwin* ) darwin=true ;; #(
113추가: MSYS* | MINGW* ) msys=true ;; #(
114추가: NONSTOP* ) nonstop=true ;;
115추가: esac
116추가:
117추가:
118추가:
119추가: # Determine the Java command to use to start the JVM.
120추가: if [ -n "$JAVA_HOME" ] ; then
121추가: if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
122추가: # IBM's JDK on AIX uses strange locations for the executables
123추가: JAVACMD=$JAVA_HOME/jre/sh/java
124추가: else
125추가: JAVACMD=$JAVA_HOME/bin/java
126추가: fi
127추가: if [ ! -x "$JAVACMD" ] ; then
128추가: die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
129추가:
130추가: Please set the JAVA_HOME variable in your environment to match the
131추가: location of your Java installation."
132추가: fi
133추가: else
134추가: JAVACMD=java
135추가: if ! command -v java >/dev/null 2>&1
136추가: then
137추가: die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
138추가:
139추가: Please set the JAVA_HOME variable in your environment to match the
140추가: location of your Java installation."
141추가: fi
142추가: fi
143추가:
144추가: # Increase the maximum file descriptors if we can.
145추가: if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
146추가: case $MAX_FD in #(
147추가: max*)
148추가: # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
149추가: # shellcheck disable=SC2039,SC3045
150추가: MAX_FD=$( ulimit -H -n ) ||
151추가: warn "Could not query maximum file descriptor limit"
152추가: esac
153추가: case $MAX_FD in #(
154추가: '' | soft) :;; #(
155추가: *)
156추가: # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
157추가: # shellcheck disable=SC2039,SC3045
158추가: ulimit -n "$MAX_FD" ||
159추가: warn "Could not set maximum file descriptor limit to $MAX_FD"
160추가: esac
161추가: fi
162추가:
163추가: # Collect all arguments for the java command, stacking in reverse order:
164추가: # * args from the command line
165추가: # * the main class name
166추가: # * -classpath
167추가: # * -D...appname settings
168추가: # * --module-path (only if needed)
169추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
170추가:
171추가: # For Cygwin or MSYS, switch paths to Windows format before running java
172추가: if "$cygwin" || "$msys" ; then
173추가: APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
174추가:
175추가: JAVACMD=$( cygpath --unix "$JAVACMD" )
176추가:
177추가: # Now convert the arguments - kludge to limit ourselves to /bin/sh
178추가: for arg do
179추가: if
180추가: case $arg in #(
181추가: -*) false ;; # don't mess with options #(
182추가: /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183추가: [ -e "$t" ] ;; #(
184추가: *) false ;;
185추가: esac
186추가: then
187추가: arg=$( cygpath --path --ignore --mixed "$arg" )
188추가: fi
189추가: # Roll the args list around exactly as many times as the number of
190추가: # args, so each arg winds up back in the position where it started, but
191추가: # possibly modified.
192추가: #
193추가: # NB: a `for` loop captures its iteration list before it begins, so
194추가: # changing the positional parameters here affects neither the number of
195추가: # iterations, nor the values presented in `arg`.
196추가: shift # remove old arg
197추가: set -- "$@" "$arg" # push replacement arg
198추가: done
199추가: fi
200추가:
201추가:
202추가: # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203추가: DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204추가:
205추가: # Collect all arguments for the java command:
206추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207추가: # and any embedded shellness will be escaped.
208추가: # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209추가: # treated as '${Hostname}' itself on the command line.
210추가:
211추가: set -- \
212추가: "-Dorg.gradle.appname=$APP_BASE_NAME" \
213추가: -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
214추가: "$@"
215추가:
216추가: # Stop when "xargs" is not available.
217추가: if ! command -v xargs >/dev/null 2>&1
218추가: then
219추가: die "xargs is not available"
220추가: fi
221추가:
222추가: # Use "xargs" to parse quoted args.
223추가: #
224추가: # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
225추가: #
226추가: # In Bash we could simply go:
227추가: #
228추가: # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
229추가: # set -- "${ARGS[@]}" "$@"
230추가: #
231추가: # but POSIX shell has neither arrays nor command substitution, so instead we
232추가: # post-process each arg (as a line of input to sed) to backslash-escape any
233추가: # character that might be a shell metacharacter, then use eval to reverse
234추가: # that process (while maintaining the separation between arguments), and wrap
235추가: # the whole thing up as a single "set" statement.
236추가: #
237추가: # This will of course break if any of these variables contains a newline or
238추가: # an unmatched quote.
239추가: #
240추가:
241추가: eval "set -- $(
242추가: printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
243추가: xargs -n1 |
244추가: sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
245추가: tr '\n' ' '
246추가: )" '"$@"'
247추가:
248추가: exec "$JAVACMD" "$@"
추가android/gradlew.bat+112-0
@@ -0,0 +1,112 @@
1추가: @rem
2추가: @rem Copyright 2015 the original author or authors.
3추가: @rem
4추가: @rem Licensed under the Apache License, Version 2.0 (the "License");
5추가: @rem you may not use this file except in compliance with the License.
6추가: @rem You may obtain a copy of the License at
7추가: @rem
8추가: @rem https://www.apache.org/licenses/LICENSE-2.0
9추가: @rem
10추가: @rem Unless required by applicable law or agreed to in writing, software
11추가: @rem distributed under the License is distributed on an "AS IS" BASIS,
12추가: @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13추가: @rem See the License for the specific language governing permissions and
14추가: @rem limitations under the License.
15추가: @rem
16추가: @rem SPDX-License-Identifier: Apache-2.0
17추가: @rem
18추가:
19추가: @if "%DEBUG%"=="" @echo off
20추가: @rem ##########################################################################
21추가: @rem
22추가: @rem gradlew startup script for Windows
23추가: @rem
24추가: @rem ##########################################################################
25추가:
26추가: @rem Set local scope for the variables, and ensure extensions are enabled
27추가: setlocal EnableExtensions
28추가:
29추가: @rem Catch executions from older scripts and ensure they exit cleanly.
30추가: @rem This can be removed once we can be reasonably confident that few people
31추가: @rem will be migrating directly to this new wrapper.
32추가: goto afterSafetyNet
33추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
34추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
35추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
36추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
37추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
38추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
39추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
40추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
41추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
42추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
43추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
44추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
45추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
46추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
47추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
48추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
49추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
50추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
51추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
52추가: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
53추가: goto exitWithErrorLevel
54추가: :afterSafetyNet
55추가:
56추가: set DIRNAME=%~dp0
57추가: if "%DIRNAME%"=="" set DIRNAME=.
58추가: @rem This is normally unused
59추가: set APP_BASE_NAME=%~n0
60추가: set APP_HOME=%DIRNAME%
61추가:
62추가: @rem Resolve any "." and ".." in APP_HOME to make it shorter.
63추가: for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
64추가:
65추가: @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
66추가: set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
67추가:
68추가: @rem Find java.exe
69추가: if defined JAVA_HOME goto findJavaFromJavaHome
70추가:
71추가: set JAVA_EXE=java.exe
72추가: %JAVA_EXE% -version >NUL 2>&1
73추가: if %ERRORLEVEL% equ 0 goto execute
74추가:
75추가: 1>&2 echo.
76추가: 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
77추가: 1>&2 echo.
78추가: 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
79추가: 1>&2 echo location of your Java installation.
80추가:
81추가: "%COMSPEC%" /c exit 1
82추가: goto exitWithErrorLevel
83추가:
84추가: :findJavaFromJavaHome
85추가: set JAVA_HOME=%JAVA_HOME:"=%
86추가: set JAVA_EXE=%JAVA_HOME%/bin/java.exe
87추가:
88추가: if exist "%JAVA_EXE%" goto execute
89추가:
90추가: 1>&2 echo.
91추가: 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
92추가: 1>&2 echo.
93추가: 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
94추가: 1>&2 echo location of your Java installation.
95추가:
96추가: "%COMSPEC%" /c exit 1
97추가: goto exitWithErrorLevel
98추가:
99추가: :execute
100추가: @rem Setup the command line
101추가:
102추가:
103추가:
104추가: @rem Execute gradlew
105추가: @rem endlocal doesn't take effect until after the line is parsed and variables are expanded
106추가: @rem which allows us to clear the local environment before executing the java command
107추가: endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
108추가:
109추가: @rem This label must not be changed. We rely on old scripts being able to jump to this point.
110추가: :exitWithErrorLevel
111추가: @rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
112추가: "%COMSPEC%" /c exit %ERRORLEVEL%
추가android/settings.gradle.kts+18-0
@@ -0,0 +1,18 @@
1추가: pluginManagement {
2추가: repositories {
3추가: google()
4추가: mavenCentral()
5추가: gradlePluginPortal()
6추가: }
7추가: }
8추가:
9추가: dependencyResolutionManagement {
10추가: repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
11추가: repositories {
12추가: google()
13추가: mavenCentral()
14추가: }
15추가: }
16추가:
17추가: rootProject.name = "android-remote"
18추가: include(":app")
추가src/lib.rs+5-0
@@ -0,0 +1,5 @@
1추가: //! Android Remote 호스트 클라이언트.
2추가: //!
3추가: //! Ubuntu(Wayland/X11)에서 Android 기기 화면을 미러링하고 마우스·키보드로 원격 제어한다.
4추가:
5추가: pub mod protocol;
추가src/main.rs+7-0
@@ -0,0 +1,7 @@
1추가: fn main() {
2추가: println!(
3추가: "android-remote {} (protocol v{}): 아직 구현 전입니다.",
4추가: env!("CARGO_PKG_VERSION"),
5추가: wayland_android_remote::protocol::VERSION
6추가: );
7추가: }
추가src/protocol/frame.rs+119-0
@@ -0,0 +1,119 @@
1추가: use bytes::{Buf, BufMut, Bytes, BytesMut};
2추가:
3추가: use super::{HEADER_LEN, MAGIC, MAX_PAYLOAD_LEN, MsgType, ProtocolError, VERSION};
4추가:
5추가: /// 12바이트 공통 프레임 헤더 (기획서 7.1). `payload_len`은 [`Frame`]의 페이로드에서 계산한다.
6추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7추가: pub struct FrameHeader {
8추가: pub msg_type: MsgType,
9추가: pub flags: u16,
10추가: pub seq_id: u16,
11추가: }
12추가:
13추가: /// 헤더와 페이로드가 모두 도착한 완성 프레임.
14추가: #[derive(Debug, Clone, PartialEq, Eq)]
15추가: pub struct Frame {
16추가: pub header: FrameHeader,
17추가: pub payload: Bytes,
18추가: }
19추가:
20추가: impl Frame {
21추가: pub fn new(msg_type: MsgType, seq_id: u16, payload: impl Into<Bytes>) -> Self {
22추가: Self {
23추가: header: FrameHeader {
24추가: msg_type,
25추가: flags: 0,
26추가: seq_id,
27추가: },
28추가: payload: payload.into(),
29추가: }
30추가: }
31추가: }
32추가:
33추가: /// 프레임을 직렬화해 `dst` 뒤에 붙인다.
34추가: ///
35추가: /// # Panics
36추가: /// 페이로드가 [`MAX_PAYLOAD_LEN`]을 넘으면 패닉한다. 상한을 넘는 데이터는 호출 측에서
37추가: /// 미리 나누거나 거부해야 한다.
38추가: pub fn encode_frame(frame: &Frame, dst: &mut BytesMut) {
39추가: let len = u32::try_from(frame.payload.len())
40추가: .ok()
41추가: .filter(|&n| n <= MAX_PAYLOAD_LEN)
42추가: .expect("payload exceeds MAX_PAYLOAD_LEN");
43추가: dst.reserve(HEADER_LEN + frame.payload.len());
44추가: dst.put_u16(MAGIC);
45추가: dst.put_u8(VERSION);
46추가: dst.put_u8(frame.header.msg_type.into());
47추가: dst.put_u16(frame.header.flags);
48추가: dst.put_u16(frame.header.seq_id);
49추가: dst.put_u32(len);
50추가: dst.put_slice(&frame.payload);
51추가: }
52추가:
53추가: /// TCP 스트림에서 읽은 바이트를 쌓아 두고 완성된 프레임만 꺼내는 디코더 (기획서 7.5).
54추가: #[derive(Debug, Default)]
55추가: pub struct FrameDecoder {
56추가: buf: BytesMut,
57추가: }
58추가:
59추가: impl FrameDecoder {
60추가: pub fn new() -> Self {
61추가: Self::default()
62추가: }
63추가:
64추가: /// 소켓에서 읽은 바이트를 버퍼에 추가한다.
65추가: pub fn extend(&mut self, data: &[u8]) {
66추가: self.buf.extend_from_slice(data);
67추가: }
68추가:
69추가: /// 버퍼에 남아 있는 아직 처리하지 않은 바이트 수.
70추가: pub fn buffered_len(&self) -> usize {
71추가: self.buf.len()
72추가: }
73추가:
74추가: /// 완성된 프레임 하나를 꺼낸다. 데이터가 모자라면 버퍼를 건드리지 않고 `Ok(None)`을 돌려준다.
75추가: ///
76추가: /// 헤더 검증은 헤더 12바이트가 도착하자마자 하므로, 잘못된 `payload_len`이 오면
77추가: /// 페이로드를 기다리지 않고 바로 오류를 낸다.
78추가: pub fn decode(&mut self) -> Result<Option<Frame>, ProtocolError> {
79추가: if self.buf.len() < HEADER_LEN {
80추가: return Ok(None);
81추가: }
82추가:
83추가: let mut h = &self.buf[..HEADER_LEN];
84추가: let magic = h.get_u16();
85추가: let version = h.get_u8();
86추가: let msg_type = h.get_u8();
87추가: let flags = h.get_u16();
88추가: let seq_id = h.get_u16();
89추가: let payload_len = h.get_u32();
90추가:
91추가: if magic != MAGIC {
92추가: return Err(ProtocolError::BadMagic(magic));
93추가: }
94추가: if version != VERSION {
95추가: return Err(ProtocolError::UnsupportedVersion(version));
96추가: }
97추가: if payload_len > MAX_PAYLOAD_LEN {
98추가: return Err(ProtocolError::PayloadTooLarge(payload_len));
99추가: }
100추가: let msg_type = MsgType::try_from(msg_type)?;
101추가:
102추가: let total = HEADER_LEN + payload_len as usize;
103추가: if self.buf.len() < total {
104추가: self.buf.reserve(total - self.buf.len());
105추가: return Ok(None);
106추가: }
107추가:
108추가: self.buf.advance(HEADER_LEN);
109추가: let payload = self.buf.split_to(payload_len as usize).freeze();
110추가: Ok(Some(Frame {
111추가: header: FrameHeader {
112추가: msg_type,
113추가: flags,
114추가: seq_id,
115추가: },
116추가: payload,
117추가: }))
118추가: }
119추가: }
추가src/protocol/mod.rs+52-0
@@ -0,0 +1,52 @@
1추가: //! 제어 채널 바이너리 프레이밍 프로토콜 (기획서 7절).
2추가: //!
3추가: //! 모든 제어 패킷은 12바이트 Big-Endian 공통 헤더와 가변 길이 페이로드로 이루어진다.
4추가: //! TCP(TLS) 스트림은 프레임 경계를 보장하지 않으므로 [`FrameDecoder`]가 부분 수신과
5추가: //! 여러 프레임이 한 번에 도착하는 경우를 모두 처리한다.
6추가:
7추가: mod frame;
8추가: mod msg_type;
9추가:
10추가: pub use frame::{Frame, FrameDecoder, FrameHeader, encode_frame};
11추가: pub use msg_type::MsgType;
12추가:
13추가: /// 프로토콜 식별자 (ASCII 'A', 'R').
14추가: pub const MAGIC: u16 = 0x4152;
15추가: /// 현재 프로토콜 버전.
16추가: pub const VERSION: u8 = 0x01;
17추가: /// 공통 헤더 길이 (바이트).
18추가: pub const HEADER_LEN: usize = 12;
19추가: /// 페이로드 최대 길이. 이보다 큰 `payload_len`은 OOM 방지를 위해 거부한다.
20추가: pub const MAX_PAYLOAD_LEN: u32 = 4 * 1024 * 1024;
21추가:
22추가: /// 헤더 `flags` 비트.
23추가: pub mod flags {
24추가: /// 수신 측에 ACK 응답을 요청한다.
25추가: pub const ACK_REQUESTED: u16 = 0x0001;
26추가: /// 페이로드가 압축되어 있다.
27추가: pub const COMPRESSED: u16 = 0x0002;
28추가: }
29추가:
30추가: /// 프레임 디코딩 중 발생하는 오류. 발생하면 스트림 동기가 깨진 것이므로 연결을 끊는다.
31추가: #[derive(Debug, Clone, PartialEq, Eq)]
32추가: pub enum ProtocolError {
33추가: BadMagic(u16),
34추가: UnsupportedVersion(u8),
35추가: UnknownMsgType(u8),
36추가: PayloadTooLarge(u32),
37추가: }
38추가:
39추가: impl std::fmt::Display for ProtocolError {
40추가: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41추가: match self {
42추가: Self::BadMagic(m) => write!(f, "잘못된 magic 값: {m:#06x}"),
43추가: Self::UnsupportedVersion(v) => write!(f, "지원하지 않는 프로토콜 버전: {v:#04x}"),
44추가: Self::UnknownMsgType(t) => write!(f, "알 수 없는 msg_type: {t:#04x}"),
45추가: Self::PayloadTooLarge(n) => {
46추가: write!(f, "payload_len {n}이 상한 {MAX_PAYLOAD_LEN}을 넘음")
47추가: }
48추가: }
49추가: }
50추가: }
51추가:
52추가: impl std::error::Error for ProtocolError {}
추가src/protocol/msg_type.rs+75-0
@@ -0,0 +1,75 @@
1추가: use super::ProtocolError;
2추가:
3추가: /// 제어 메시지 유형 (기획서 7.2).
4추가: #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5추가: #[repr(u8)]
6추가: pub enum MsgType {
7추가: Ping = 0x01,
8추가: Pong = 0x02,
9추가: AuthHello = 0x03,
10추가: AuthChallenge = 0x04,
11추가: AuthResponse = 0x05,
12추가: AuthResult = 0x06,
13추가: ChannelAttach = 0x07,
14추가: KeyEvent = 0x10,
15추가: TextInput = 0x11,
16추가: SystemAction = 0x12,
17추가: ClipboardSync = 0x20,
18추가: TouchEvent = 0x30,
19추가: ScrollEvent = 0x31,
20추가: VideoConfigRequest = 0x40,
21추가: VideoConfig = 0x41,
22추가: VideoRequestKeyframe = 0x42,
23추가: Ack = 0xF0,
24추가: Error = 0xFF,
25추가: }
26추가:
27추가: impl MsgType {
28추가: /// 인증 완료(AUTH_RESULT OK) 전에도 처리할 수 있는 메시지인지 여부 (기획서 7.3 6항).
29추가: pub fn allowed_before_auth(self) -> bool {
30추가: matches!(
31추가: self,
32추가: Self::Ping
33추가: | Self::Pong
34추가: | Self::AuthHello
35추가: | Self::AuthChallenge
36추가: | Self::AuthResponse
37추가: | Self::AuthResult
38추가: | Self::Error
39추가: )
40추가: }
41추가: }
42추가:
43추가: impl TryFrom<u8> for MsgType {
44추가: type Error = ProtocolError;
45추가:
46추가: fn try_from(value: u8) -> Result<Self, ProtocolError> {
47추가: Ok(match value {
48추가: 0x01 => Self::Ping,
49추가: 0x02 => Self::Pong,
50추가: 0x03 => Self::AuthHello,
51추가: 0x04 => Self::AuthChallenge,
52추가: 0x05 => Self::AuthResponse,
53추가: 0x06 => Self::AuthResult,
54추가: 0x07 => Self::ChannelAttach,
55추가: 0x10 => Self::KeyEvent,
56추가: 0x11 => Self::TextInput,
57추가: 0x12 => Self::SystemAction,
58추가: 0x20 => Self::ClipboardSync,
59추가: 0x30 => Self::TouchEvent,
60추가: 0x31 => Self::ScrollEvent,
61추가: 0x40 => Self::VideoConfigRequest,
62추가: 0x41 => Self::VideoConfig,
63추가: 0x42 => Self::VideoRequestKeyframe,
64추가: 0xF0 => Self::Ack,
65추가: 0xFF => Self::Error,
66추가: other => return Err(ProtocolError::UnknownMsgType(other)),
67추가: })
68추가: }
69추가: }
70추가:
71추가: impl From<MsgType> for u8 {
72추가: fn from(value: MsgType) -> Self {
73추가: value as u8
74추가: }
75추가: }
추가tests/protocol_frame.rs+109-0
@@ -0,0 +1,109 @@
1추가: use bytes::BytesMut;
2추가: use wayland_android_remote::protocol::{
3추가: Frame, FrameDecoder, HEADER_LEN, MAX_PAYLOAD_LEN, MsgType, ProtocolError, encode_frame, flags,
4추가: };
5추가:
6추가: fn encode(frame: &Frame) -> Vec<u8> {
7추가: let mut buf = BytesMut::new();
8추가: encode_frame(frame, &mut buf);
9추가: buf.to_vec()
10추가: }
11추가:
12추가: #[test]
13추가: fn header_layout_matches_spec() {
14추가: let mut frame = Frame::new(MsgType::SystemAction, 0x1234, vec![0x01, 0, 0, 0]);
15추가: frame.header.flags = flags::ACK_REQUESTED;
16추가: let bytes = encode(&frame);
17추가:
18추가: assert_eq!(
19추가: &bytes[..HEADER_LEN],
20추가: &[
21추가: 0x41, 0x52, 0x01, 0x12, 0x00, 0x01, 0x12, 0x34, 0x00, 0x00, 0x00, 0x04
22추가: ]
23추가: );
24추가: assert_eq!(&bytes[HEADER_LEN..], &[0x01, 0, 0, 0]);
25추가: }
26추가:
27추가: #[test]
28추가: fn roundtrip() {
29추가: let frame = Frame::new(MsgType::ClipboardSync, 7, "안녕하세요".as_bytes().to_vec());
30추가: let mut dec = FrameDecoder::new();
31추가: dec.extend(&encode(&frame));
32추가: assert_eq!(dec.decode().unwrap(), Some(frame));
33추가: assert_eq!(dec.decode().unwrap(), None);
34추가: assert_eq!(dec.buffered_len(), 0);
35추가: }
36추가:
37추가: #[test]
38추가: fn partial_reads_wait_without_consuming() {
39추가: let frame = Frame::new(MsgType::TouchEvent, 1, vec![0xAB; 20]);
40추가: let bytes = encode(&frame);
41추가: let mut dec = FrameDecoder::new();
42추가:
43추가: for (i, b) in bytes.iter().enumerate() {
44추가: if i < bytes.len() - 1 {
45추가: dec.extend(&[*b]);
46추가: assert_eq!(dec.decode().unwrap(), None, "byte {i}");
47추가: assert_eq!(dec.buffered_len(), i + 1);
48추가: } else {
49추가: dec.extend(&[*b]);
50추가: }
51추가: }
52추가: assert_eq!(dec.decode().unwrap(), Some(frame));
53추가: }
54추가:
55추가: #[test]
56추가: fn coalesced_frames_decode_in_order() {
57추가: let a = Frame::new(MsgType::Ping, 1, Vec::new());
58추가: let b = Frame::new(MsgType::KeyEvent, 2, vec![0; 12]);
59추가: let c = Frame::new(MsgType::Pong, 3, Vec::new());
60추가: let mut bytes = encode(&a);
61추가: bytes.extend(encode(&b));
62추가: bytes.extend(&encode(&c)[..5]);
63추가:
64추가: let mut dec = FrameDecoder::new();
65추가: dec.extend(&bytes);
66추가: assert_eq!(dec.decode().unwrap(), Some(a));
67추가: assert_eq!(dec.decode().unwrap(), Some(b));
68추가: assert_eq!(dec.decode().unwrap(), None);
69추가: dec.extend(&encode(&c)[5..]);
70추가: assert_eq!(dec.decode().unwrap(), Some(c));
71추가: }
72추가:
73추가: #[test]
74추가: fn rejects_bad_magic() {
75추가: let mut bytes = encode(&Frame::new(MsgType::Ping, 0, Vec::new()));
76추가: bytes[0] = 0x00;
77추가: let mut dec = FrameDecoder::new();
78추가: dec.extend(&bytes);
79추가: assert_eq!(dec.decode(), Err(ProtocolError::BadMagic(0x0052)));
80추가: }
81추가:
82추가: #[test]
83추가: fn rejects_oversized_payload_before_buffering_it() {
84추가: let mut bytes = encode(&Frame::new(MsgType::ClipboardSync, 0, Vec::new()));
85추가: bytes[8..12].copy_from_slice(&(MAX_PAYLOAD_LEN + 1).to_be_bytes());
86추가: let mut dec = FrameDecoder::new();
87추가: dec.extend(&bytes);
88추가: assert_eq!(
89추가: dec.decode(),
90추가: Err(ProtocolError::PayloadTooLarge(MAX_PAYLOAD_LEN + 1))
91추가: );
92추가: }
93추가:
94추가: #[test]
95추가: fn rejects_unknown_msg_type() {
96추가: let mut bytes = encode(&Frame::new(MsgType::Ping, 0, Vec::new()));
97추가: bytes[3] = 0x99;
98추가: let mut dec = FrameDecoder::new();
99추가: dec.extend(&bytes);
100추가: assert_eq!(dec.decode(), Err(ProtocolError::UnknownMsgType(0x99)));
101추가: }
102추가:
103추가: #[test]
104추가: fn only_auth_messages_allowed_before_auth() {
105추가: assert!(MsgType::AuthHello.allowed_before_auth());
106추가: assert!(MsgType::Ping.allowed_before_auth());
107추가: assert!(!MsgType::TouchEvent.allowed_before_auth());
108추가: assert!(!MsgType::ChannelAttach.allowed_before_auth());
109추가: }