torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Host-opt-in line RPC control plane for a running `Client`.
//!
//! Disabled by default. When enabled, the host must set `rpc-listen` and
//! `rpc-auth-token` (or `TORRENTDHT_RPC_TOKEN`). Binds are loopback-only unless
//! `rpc-allow-non-loopback` is set. `add_torrent` paths are jailed under
//! `download-dir` (or `rpc-torrent-root`).
//!
//! # Methods (after `auth <token>`)
//!
//! - `ping` — liveness
//! - `status` / `list_sessions` — live sessions + on-disk resume scan (`state_dir` aware)
//! - `progress <info-hash-hex>` — live piece/byte counters for one session
//! - `add_torrent <path>` — jailed under torrent root
//! - `add_magnet <uri>`

use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Semaphore;
use zeroize::Zeroizing;

use crate::client::Client;
use crate::config::Config;
use crate::error::{Error, Result};
use crate::torrent::{parse_magnet, TorrentFile};

/// Hard cap on a single RPC request line (including magnet URIs).
pub const MAX_RPC_LINE: usize = 16 * 1024;
/// Concurrent authenticated RPC sessions.
const MAX_RPC_CONNECTIONS: usize = 8;
/// Idle read deadline per line.
const RPC_READ_TIMEOUT: Duration = Duration::from_secs(30);
/// Post-auth requests allowed per connection per second (fixed window).
const RPC_MAX_REQ_PER_SEC: u32 = 30;
/// Chunk size for line reads (avoids 1-byte syscall loops).
const RPC_READ_CHUNK: usize = 512;

/// Validate host RPC settings before binding.
pub fn validate_rpc_config(cfg: &Config) -> Result<()> {
    if !cfg.rpc_enabled {
        return Ok(());
    }
    let listen = cfg.rpc_listen.as_deref().ok_or_else(|| {
        Error::Config("rpc-enabled requires rpc-listen (e.g. \"127.0.0.1:7600\")".into())
    })?;
    let token = rpc_token(cfg).ok_or_else(|| {
        Error::Config(
            "rpc-enabled requires rpc-auth-token or env TORRENTDHT_RPC_TOKEN".into(),
        )
    })?;
    if token.len() < 32 {
        return Err(Error::Config(
            "rpc auth token must be at least 32 characters for commercial use".into(),
        ));
    }
    let addr: SocketAddr = listen
        .parse()
        .map_err(|err| Error::Config(format!("invalid rpc-listen {listen}: {err}")))?;
    if !cfg.rpc_allow_non_loopback && !addr.ip().is_loopback() {
        return Err(Error::Config(format!(
            "rpc-listen {listen} is not loopback; set rpc-allow-non-loopback #true to permit"
        )));
    }
    Ok(())
}

fn rpc_token(cfg: &Config) -> Option<Zeroizing<String>> {
    cfg.rpc_auth_token
        .clone()
        .or_else(|| std::env::var("TORRENTDHT_RPC_TOKEN").ok().map(Zeroizing::new))
}

fn torrent_jail(cfg: &Config) -> PathBuf {
    cfg.rpc_torrent_root
        .clone()
        .unwrap_or_else(|| cfg.download_dir.clone())
}

/// Serve RPC until the listener fails. Caller should spawn only when `rpc_enabled`.
pub async fn serve(client: Arc<Client>) -> Result<()> {
    validate_rpc_config(client.config())?;
    let listen = client
        .config()
        .rpc_listen
        .as_deref()
        .expect("validated");
    let expected_token = rpc_token(client.config()).expect("validated");
    let allow_non_loopback = client.config().rpc_allow_non_loopback;
    let jail = torrent_jail(client.config());

    let listener = TcpListener::bind(listen)
        .await
        .map_err(|err| Error::Session(format!("rpc bind {listen}: {err}")))?;
    tracing::info!(listen, "rpc server listening (auth required)");
    let sessions = Arc::new(Semaphore::new(MAX_RPC_CONNECTIONS));

    loop {
        let (stream, peer) = listener.accept().await.map_err(Error::from)?;
        if !allow_non_loopback && !is_loopback_peer(peer.ip()) {
            tracing::warn!(%peer, "rpc rejected non-loopback peer");
            continue;
        }
        let Ok(permit) = sessions.clone().try_acquire_owned() else {
            tracing::warn!(%peer, "rpc connection limit reached");
            continue;
        };
        let client = Arc::clone(&client);
        let expected_token = expected_token.clone();
        let jail = jail.clone();
        tokio::spawn(async move {
            let _permit = permit;
            if let Err(err) = handle_connection(client, stream, &expected_token, &jail).await {
                tracing::debug!(%err, "rpc connection ended");
            }
        });
    }
}

fn is_loopback_peer(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => v4.is_loopback(),
        IpAddr::V6(v6) => v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()),
    }
}

struct ConnRateLimit {
    window_start: Instant,
    count: u32,
}

impl ConnRateLimit {
    fn new() -> Self {
        Self {
            window_start: Instant::now(),
            count: 0,
        }
    }

    fn allow(&mut self) -> bool {
        let now = Instant::now();
        if now.duration_since(self.window_start) >= Duration::from_secs(1) {
            self.window_start = now;
            self.count = 0;
        }
        if self.count >= RPC_MAX_REQ_PER_SEC {
            return false;
        }
        self.count = self.count.saturating_add(1);
        true
    }
}

async fn handle_connection(
    client: Arc<Client>,
    stream: TcpStream,
    expected_token: &str,
    jail: &Path,
) -> Result<()> {
    let (mut reader, mut writer) = stream.into_split();
    let mut authed = false;
    let mut line_buf = Vec::with_capacity(256);
    let mut carry = Vec::new();
    let rate = Arc::new(Mutex::new(ConnRateLimit::new()));

    loop {
        line_buf.clear();
        let line = match read_rpc_line(&mut reader, &mut line_buf, &mut carry).await {
            Ok(Some(line)) => line,
            Ok(None) => return Ok(()),
            Err(err) => {
                let body = json_error(&err.to_string());
                let _ = writer.write_all(body.as_bytes()).await;
                let _ = writer.write_all(b"\n").await;
                return Ok(());
            }
        };
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let response = if !authed {
            match auth_line(line, expected_token) {
                Ok(()) => {
                    authed = true;
                    json_ok_auth()
                }
                Err(msg) => {
                    let body = json_error(&msg);
                    writer.write_all(body.as_bytes()).await?;
                    writer.write_all(b"\n").await?;
                    return Ok(());
                }
            }
        } else {
            let allowed = rate
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .allow();
            if !allowed {
                json_error("rate limited")
            } else {
                dispatch(&client, line, jail).await
            }
        };
        writer.write_all(response.as_bytes()).await?;
        writer.write_all(b"\n").await?;
    }
}

async fn read_rpc_line<R: AsyncReadExt + Unpin>(
    reader: &mut R,
    buf: &mut Vec<u8>,
    carry: &mut Vec<u8>,
) -> Result<Option<String>> {
    let read = tokio::time::timeout(RPC_READ_TIMEOUT, async {
        loop {
            if let Some(pos) = carry.iter().position(|&b| b == b'\n') {
                let line_bytes = &carry[..pos];
                for &b in line_bytes {
                    if b == b'\r' {
                        continue;
                    }
                    if buf.len() >= MAX_RPC_LINE {
                        return Err(Error::Session(format!(
                            "rpc line exceeds {MAX_RPC_LINE} bytes"
                        )));
                    }
                    buf.push(b);
                }
                let rest = carry[pos + 1..].to_vec();
                *carry = rest;
                break;
            }

            if buf.len().saturating_add(carry.len()) > MAX_RPC_LINE {
                return Err(Error::Session(format!(
                    "rpc line exceeds {MAX_RPC_LINE} bytes"
                )));
            }

            let mut chunk = [0u8; RPC_READ_CHUNK];
            let n = reader.read(&mut chunk).await?;
            if n == 0 {
                if carry.is_empty() && buf.is_empty() {
                    return Ok::<Option<String>, Error>(None);
                }
                // EOF without newline: treat remaining as a line if present.
                for &b in carry.iter() {
                    if b == b'\r' {
                        continue;
                    }
                    if buf.len() >= MAX_RPC_LINE {
                        return Err(Error::Session(format!(
                            "rpc line exceeds {MAX_RPC_LINE} bytes"
                        )));
                    }
                    buf.push(b);
                }
                carry.clear();
                break;
            }
            carry.extend_from_slice(&chunk[..n]);
        }
        let line = std::str::from_utf8(buf)
            .map_err(|_| Error::Session("rpc line is not valid utf-8".into()))?
            .to_string();
        Ok(Some(line))
    })
    .await
    .map_err(|_| Error::Session("rpc read timed out".into()))??;
    Ok(read)
}

fn auth_line(line: &str, expected: &str) -> std::result::Result<(), String> {
    let mut parts = line.split_whitespace();
    let method = parts.next().unwrap_or("");
    if !method.eq_ignore_ascii_case("auth") {
        return Err("authenticate first with: auth <token>".into());
    }
    let Some(token) = parts.next() else {
        return Err("auth requires a token".into());
    };
    if !token_eq_constant_time(token.as_bytes(), expected.as_bytes()) {
        return Err("auth failed".into());
    }
    if parts.next().is_some() {
        return Err("auth takes a single token".into());
    }
    Ok(())
}

/// Compare tokens without leaking length via an early return on the secret.
///
/// Both sides are hashed first so the constant-time step always runs over a
/// fixed 32-byte digest regardless of provided/expected string lengths.
fn token_eq_constant_time(provided: &[u8], expected: &[u8]) -> bool {
    use sha2::{Digest, Sha256};
    let a = Sha256::digest(provided);
    let b = Sha256::digest(expected);
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

async fn dispatch(client: &Arc<Client>, line: &str, jail: &Path) -> String {
    let mut parts = line.split_whitespace();
    let Some(method) = parts.next() else {
        return json_error("empty request");
    };
    match method {
        "status" | "list_sessions" => json_status(client).await,
        "progress" => {
            let Some(hex) = parts.next() else {
                return json_error("progress requires an info-hash hex");
            };
            json_progress(client, hex).await
        }
        "add_torrent" => {
            let Some(path) = parts.next() else {
                return json_error("add_torrent requires a path");
            };
            json_add_torrent(client, path, jail).await
        }
        "add_magnet" => {
            let Some(uri) = parts.next() else {
                return json_error("add_magnet requires a magnet URI");
            };
            // Magnet URIs may contain spaces if poorly quoted; rejoin remainder.
            let rest = if parts.clone().next().is_some() {
                let start = line.find(uri).unwrap_or(0);
                line[start..].to_string()
            } else {
                uri.to_string()
            };
            if rest.len() > MAX_RPC_LINE {
                return json_error("magnet URI too long");
            }
            json_add_magnet(client, &rest).await
        }
        "stop" => {
            let Some(hex) = parts.next() else {
                return json_error("stop requires an info-hash hex");
            };
            json_stop(client, hex).await
        }
        "remove" => {
            let Some(hex) = parts.next() else {
                return json_error("remove requires an info-hash hex");
            };
            json_remove(client, hex).await
        }
        "ping" => "{\"ok\":true,\"pong\":true}".into(),
        other => json_error(&format!("unknown method: {other}")),
    }
}

async fn json_status(client: &Arc<Client>) -> String {
    let sessions = client.sessions().await;
    let mut rows = String::new();
    for (idx, session) in sessions.iter().enumerate() {
        if idx > 0 {
            rows.push(',');
        }
        let progress = session.current_progress().await;
        let scrape = session
            .scrape_stats()
            .map(|s| {
                format!(
                    "{{\"complete\":{},\"incomplete\":{},\"downloaded\":{}}}",
                    s.complete, s.incomplete, s.downloaded
                )
            })
            .unwrap_or_else(|| "null".into());
        let layout = session.layout();
        rows.push_str(&format!(
            "{{\"name\":{},\"info_hash\":{},\"pieces_complete\":{},\"piece_count\":{},\
\"bytes_downloaded\":{},\"content_path\":{},\"state_path\":{},\"checkpoint_path\":{},\"scrape\":{}}}",
            json_str(&session.info().name),
            json_str(&session.info_hash().to_hex()),
            progress.pieces_complete,
            progress.piece_count,
            progress.bytes_downloaded,
            json_str(&layout.content_root.display().to_string()),
            json_str(&layout.state_root.display().to_string()),
            json_str(&session.checkpoint_path().display().to_string()),
            scrape,
        ));
    }

    let on_disk = match crate::ops::scan_download_dir(client.config()).await {
        Ok(disk_rows) => {
            let mut out = String::new();
            for (idx, row) in disk_rows.iter().enumerate() {
                if idx > 0 {
                    out.push(',');
                }
                out.push_str(&format!(
                    "{{\"info_hash\":{},\"pieces_complete\":{},\"bytes_downloaded\":{},\
\"has_checkpoint\":{},\"content_path\":{},\"state_path\":{}}}",
                    json_str(&row.info_hash_hex),
                    row.pieces_complete,
                    row.bytes_downloaded,
                    if row.has_checkpoint { "true" } else { "false" },
                    json_str(&row.path.display().to_string()),
                    json_str(&row.state_path.display().to_string()),
                ));
            }
            out
        }
        Err(err) => {
            tracing::debug!(%err, "rpc status on-disk scan skipped");
            String::new()
        }
    };

    let cfg = client.config();
    let state_dir = cfg
        .state_dir
        .as_ref()
        .map(|p| json_str(&p.display().to_string()))
        .unwrap_or_else(|| "null".into());
    format!(
        "{{\"ok\":true,\"listen_port\":{},\"download_dir\":{},\"state_dir\":{},\
\"sessions\":[{}],\"on_disk\":[{}]}}",
        cfg.listen_port,
        json_str(&cfg.download_dir.display().to_string()),
        state_dir,
        rows,
        on_disk,
    )
}

async fn json_progress(client: &Arc<Client>, info_hash_hex: &str) -> String {
    let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
        return json_error("invalid info-hash hex");
    };
    let Some(session) = client.session(hash).await else {
        return json_error("session not found");
    };
    let progress = session.current_progress().await;
    format!(
        "{{\"ok\":true,\"info_hash\":{},\"pieces_complete\":{},\"piece_count\":{},\"bytes_downloaded\":{}}}",
        json_str(&session.info_hash().to_hex()),
        progress.pieces_complete,
        progress.piece_count,
        progress.bytes_downloaded,
    )
}

async fn json_add_torrent(client: &Arc<Client>, path: &str, jail: &Path) -> String {
    let relative = match jail_relative_path(jail, path) {
        Ok(p) => p,
        Err(err) => return json_error(&err),
    };
    let jail = jail.to_path_buf();
    let relative_clone = relative.clone();
    let max = crate::security::MAX_TORRENT_FILE_BYTES;
    let data = match tokio::task::spawn_blocking(move || {
        crate::security::read_bytes_under_root_capped(&jail, &relative_clone, max)
    })
    .await
    {
        Ok(Ok(data)) => data,
        Ok(Err(err)) => return json_error(&format!("read {}: {err}", relative.display())),
        Err(err) => return json_error(&format!("read join: {err}")),
    };
    match TorrentFile::parse(&data) {
        Ok(torrent) => match client.add_torrent(torrent).await {
            Ok(session) => format!(
                "{{\"ok\":true,\"info_hash\":{},\"name\":{}}}",
                json_str(&session.info_hash().to_hex()),
                json_str(&session.info().name),
            ),
            Err(err) => json_error(&err.to_string()),
        },
        Err(err) => json_error(&err.to_string()),
    }
}

/// Resolve an RPC path to a jail-relative sanitized path (no canonicalize/TOCTOU).
fn jail_relative_path(jail: &Path, requested: &str) -> std::result::Result<PathBuf, String> {
    if !jail.is_dir() {
        return Err(format!(
            "rpc torrent root is missing or not a directory: {}",
            jail.display()
        ));
    }
    let candidate = Path::new(requested);
    let relative = if candidate.is_absolute() {
        candidate.strip_prefix(jail).map_err(|_| {
            format!(
                "path {} is outside rpc torrent root {}",
                candidate.display(),
                jail.display()
            )
        })?
    } else {
        candidate
    };
    crate::security::sanitize_torrent_relative_path(relative).map_err(|err| err.to_string())
}

async fn json_add_magnet(client: &Arc<Client>, uri: &str) -> String {
    match parse_magnet(uri) {
        Ok(magnet) => match client.add_magnet(magnet).await {
            Ok(session) => format!(
                "{{\"ok\":true,\"info_hash\":{},\"name\":{}}}",
                json_str(&session.info_hash().to_hex()),
                json_str(&session.info().name),
            ),
            Err(err) => json_error(&err.to_string()),
        },
        Err(err) => json_error(&err.to_string()),
    }
}

async fn json_stop(client: &Arc<Client>, info_hash_hex: &str) -> String {
    let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
        return json_error("invalid info-hash hex");
    };
    if client.stop_torrent(hash).await {
        format!(
            "{{\"ok\":true,\"stopped\":true,\"info_hash\":{}}}",
            json_str(&hash.to_hex())
        )
    } else {
        json_error("session not found")
    }
}

async fn json_remove(client: &Arc<Client>, info_hash_hex: &str) -> String {
    let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
        return json_error("invalid info-hash hex");
    };
    if client.session(hash).await.is_none() {
        return json_error("session not found");
    }
    client.remove_torrent(hash).await;
    format!(
        "{{\"ok\":true,\"removed\":true,\"info_hash\":{}}}",
        json_str(&hash.to_hex())
    )
}

fn json_ok_auth() -> String {
    "{\"ok\":true,\"authenticated\":true}".into()
}

fn json_str(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len() + 2);
    escaped.push('"');
    for ch in value.chars() {
        match ch {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            c if c.is_control() => {
                use std::fmt::Write;
                let _ = write!(escaped, "\\u{:04x}", u32::from(c));
            }
            c => escaped.push(c),
        }
    }
    escaped.push('"');
    escaped
}

fn json_error(message: &str) -> String {
    format!("{{\"ok\":false,\"error\":{}}}", json_str(message))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_rpc_without_token_or_listen() {
        let cfg = Config {
            rpc_enabled: true,
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_err());
        let cfg = Config {
            rpc_enabled: true,
            rpc_listen: Some("127.0.0.1:7600".into()),
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_err());
        let cfg = Config {
            rpc_enabled: true,
            rpc_listen: Some("127.0.0.1:7600".into()),
            rpc_auth_token: Some(Zeroizing::new("secret".into())),
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_err());
        let cfg = Config {
            rpc_enabled: true,
            rpc_listen: Some("127.0.0.1:7600".into()),
            rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_ok());
    }

    #[test]
    fn rejects_non_loopback_unless_allowed() {
        let cfg = Config {
            rpc_enabled: true,
            rpc_listen: Some("0.0.0.0:7600".into()),
            rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_err());
        let cfg = Config {
            rpc_enabled: true,
            rpc_listen: Some("0.0.0.0:7600".into()),
            rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
            rpc_allow_non_loopback: true,
            ..Config::default()
        };
        assert!(validate_rpc_config(&cfg).is_ok());
    }

    #[test]
    fn auth_constant_time_rejects_mismatch() {
        assert!(auth_line("auth secret", "secret").is_ok());
        assert!(auth_line("auth wrong", "secret").is_err());
        assert!(auth_line("auth secre", "secret").is_err());
        assert!(auth_line("auth secrett", "secret").is_err());
        assert!(auth_line("status", "secret").is_err());
    }

    #[tokio::test]
    async fn rejects_oversized_rpc_line() {
        let mut data = vec![b'a'; MAX_RPC_LINE + 1];
        data.push(b'\n');
        let mut cursor = std::io::Cursor::new(data);
        let mut buf = Vec::new();
        let mut carry = Vec::new();
        let err = read_rpc_line(&mut cursor, &mut buf, &mut carry)
            .await
            .expect_err("cap");
        assert!(err.to_string().contains("exceeds"));
    }

    #[tokio::test]
    async fn reads_line_in_chunks() {
        let data = b"ping\nstatus\n";
        let mut cursor = std::io::Cursor::new(data.as_slice());
        let mut buf = Vec::new();
        let mut carry = Vec::new();
        let line = read_rpc_line(&mut cursor, &mut buf, &mut carry)
            .await
            .expect("read")
            .expect("line");
        assert_eq!(line, "ping");
        buf.clear();
        let line = read_rpc_line(&mut cursor, &mut buf, &mut carry)
            .await
            .expect("read")
            .expect("line");
        assert_eq!(line, "status");
    }
}