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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use crate::clipboard;
use crate::config::Config;
use crate::focus;
use crate::paste;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio::time::timeout;
const AUTH_TIMEOUT_SECS: u64 = 10;
const IDLE_TIMEOUT_SECS: u64 = 30;
const MAX_PAYLOAD_SIZE: usize = 10 * 1024; // 10 KB
const MAX_AUTH_ATTEMPTS: u32 = 3;
const BAN_DURATION_SECS: u64 = 30;
pub async fn handle(
stream: TcpStream,
addr: SocketAddr,
config: Arc<Config>,
banned: Arc<Mutex<HashMap<SocketAddr, Instant>>>,
) -> anyhow::Result<()> {
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
let mut auth_attempts: u32 = 0;
// ── Auth phase ──────────────────────────────────────────────────────────
tracing::info!("[{}] waiting for authentication", addr);
loop {
line.clear();
match timeout(
Duration::from_secs(AUTH_TIMEOUT_SECS),
reader.read_line(&mut line),
)
.await
{
Ok(Ok(0)) => {
tracing::info!("[{}] connection closed before auth", addr);
return Ok(());
}
Ok(Ok(_)) => {}
Ok(Err(e)) => {
tracing::warn!("[{}] read error during auth: {}", addr, e);
return Err(e.into());
}
Err(_) => {
tracing::warn!("[{}] auth timeout", addr);
return Ok(());
}
}
let msg: serde_json::Value = match serde_json::from_str(line.trim()) {
Ok(v) => v,
Err(_) => continue,
};
match msg.get("type").and_then(|v| v.as_str()) {
Some("auth") => {
let pin = msg
.get("pin")
.and_then(|v| v.as_str())
.unwrap_or("");
if config.auth.pin.is_empty() || pin == config.auth.pin {
send_json(&mut writer, &serde_json::json!({"type": "auth_ok"})).await?;
tracing::info!("[{}] authenticated", addr);
break;
}
auth_attempts += 1;
if auth_attempts >= MAX_AUTH_ATTEMPTS {
send_json(
&mut writer,
&serde_json::json!({
"type": "auth_fail",
"message": "认证失败次数过多,请30秒后重试"
}),
)
.await?;
tracing::warn!("[{}] banned after {} failed auth attempts", addr, auth_attempts);
banned
.lock()
.await
.insert(addr, Instant::now() + Duration::from_secs(BAN_DURATION_SECS));
return Ok(());
}
send_json(
&mut writer,
&serde_json::json!({
"type": "auth_fail",
"message": format!("PIN码错误 (剩余尝试次数: {})", MAX_AUTH_ATTEMPTS - auth_attempts)
}),
)
.await?;
}
_ => {
// Not an auth message — remind client to authenticate
send_json(
&mut writer,
&serde_json::json!({
"type": "auth_fail",
"message": "请先认证"
}),
)
.await?;
}
}
}
// ── Message loop (authenticated) ─────────────────────────────────────────
loop {
line.clear();
match timeout(
Duration::from_secs(IDLE_TIMEOUT_SECS),
reader.read_line(&mut line),
)
.await
{
Ok(Ok(0)) => {
tracing::info!("[{}] connection closed", addr);
return Ok(());
}
Ok(Ok(_)) => {}
Ok(Err(e)) => {
tracing::warn!("[{}] read error: {}", addr, e);
return Err(e.into());
}
Err(_) => {
tracing::info!("[{}] idle timeout", addr);
return Ok(());
}
}
let msg: serde_json::Value = match serde_json::from_str(line.trim()) {
Ok(v) => v,
Err(e) => {
tracing::debug!("[{}] invalid JSON: {}", addr, e);
continue;
}
};
let msg_type = msg.get("type").and_then(|v| v.as_str()).unwrap_or("");
match msg_type {
"send" => {
let payload = msg
.get("payload")
.and_then(|v| v.as_str())
.unwrap_or("");
let id = msg.get("id").and_then(|v| v.as_str()).unwrap_or("");
// Validate payload
if payload.is_empty() {
send_json(
&mut writer,
&serde_json::json!({
"type": "nack",
"id": id,
"status": "empty",
"message": "不能发送空文本"
}),
)
.await?;
continue;
}
if payload.len() > MAX_PAYLOAD_SIZE {
send_json(
&mut writer,
&serde_json::json!({
"type": "nack",
"id": id,
"status": "too_large",
"message": format!("文本过长 (最大 {} 字节)", MAX_PAYLOAD_SIZE)
}),
)
.await?;
continue;
}
tracing::info!("[{}] received payload ({} bytes)", addr, payload.len());
// Step 1: Write to clipboard
if let Err(e) = clipboard::set_text(payload) {
tracing::error!("[{}] clipboard write failed: {}", addr, e);
send_json(
&mut writer,
&serde_json::json!({
"type": "nack",
"id": id,
"status": "clipboard_error",
"message": "写入剪贴板失败"
}),
)
.await?;
continue;
}
// Step 2: Check focus and optionally paste
let response = match focus::is_focused_input() {
Some(true) => {
match paste::simulate_paste() {
Ok(()) => {
tracing::info!("[{}] pasted into focused input", addr);
serde_json::json!({
"type": "ack",
"id": id,
"status": "pasted"
})
}
Err(e) => {
tracing::warn!("[{}] paste simulation failed: {}", addr, e);
serde_json::json!({
"type": "ack",
"id": id,
"status": "clipboard_only"
})
}
}
}
Some(false) => {
tracing::info!("[{}] focus is not an input — clipboard only", addr);
serde_json::json!({
"type": "ack",
"id": id,
"status": "clipboard_only"
})
}
None => {
tracing::info!("[{}] no focused input detected", addr);
serde_json::json!({
"type": "nack",
"id": id,
"status": "no_focus",
"message": "当前没有聚焦的输入框"
})
}
};
send_json(&mut writer, &response).await?;
}
"ping" => {
send_json(&mut writer, &serde_json::json!({"type": "pong"})).await?;
}
_ => {
tracing::debug!("[{}] unknown message type: {}", addr, msg_type);
}
}
}
}
/// Serialize a value to JSON, append a newline, and write to the stream.
async fn send_json(
writer: &mut (impl AsyncWriteExt + Unpin),
value: &serde_json::Value,
) -> anyhow::Result<()> {
let mut data = serde_json::to_vec(value)?;
data.push(b'\n');
writer.write_all(&data).await?;
Ok(())
}