sproto 0.1.0

Rust client for the Synology Drive sync protocol
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
use rustls::pki_types::ServerName;
use std::{
	io,
	pin::Pin,
	sync::Arc,
	task::{Context, Poll},
	time::{Duration, Instant},
};
use tokio::{
	io::{AsyncRead, AsyncWrite, BufReader, ReadBuf, ReadHalf, WriteHalf},
	net::TcpStream,
};
use tokio_rustls::TlsConnector;

use crate::{
	error::{self, Error, Result},
	frame,
	pstream::{self, PObject},
};

/// TLS configuration for the channel.
#[derive(Debug, Clone, Copy, Default)]
pub enum TlsMode {
	/// No TLS — plain TCP.
	None,
	/// TLS with certificate verification.
	#[default]
	Verified,
	/// TLS accepting any certificate (for self-signed NAS certs).
	Insecure,
}

// Wrapper to unify plain TCP and TLS streams behind AsyncRead + AsyncWrite.
struct DynStream(Box<dyn DynStreamTrait>);

trait DynStreamTrait: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> DynStreamTrait for T {}

impl AsyncRead for DynStream {
	fn poll_read(
		self: Pin<&mut Self>,
		cx: &mut Context<'_>,
		buf: &mut ReadBuf<'_>,
	) -> Poll<io::Result<()>> {
		Pin::new(&mut *self.get_mut().0).poll_read(cx, buf)
	}
}

impl AsyncWrite for DynStream {
	fn poll_write(
		self: Pin<&mut Self>,
		cx: &mut Context<'_>,
		buf: &[u8],
	) -> Poll<io::Result<usize>> {
		Pin::new(&mut *self.get_mut().0).poll_write(cx, buf)
	}

	fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
		Pin::new(&mut *self.get_mut().0).poll_flush(cx)
	}

	fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
		Pin::new(&mut *self.get_mut().0).poll_shutdown(cx)
	}
}

pub struct Channel {
	writer: WriteHalf<DynStream>,
	pub alive_interval: Option<u64>,
	last_active: std::time::Instant,
	reader: BufReader<ReadHalf<DynStream>>,
}

impl Channel {
	/// Connect to a Synology Drive server.
	/// If TLS is requested, performs the `encrypt_channel` upgrade before the TLS handshake.
	pub async fn connect(
		host: &str,
		port: u16,
		tls: TlsMode,
		tls_config: Option<&Arc<rustls::ClientConfig>>,
	) -> Result<Self> {
		tracing::debug!(host, port, ?tls, "tcp connect");
		let tcp = TcpStream::connect((host, port)).await?;
		tcp.set_nodelay(true)?;

		match tls {
			TlsMode::None => Ok(Self::from_stream(tcp)),
			TlsMode::Verified | TlsMode::Insecure => {
				let (read_half, mut write_half) = tokio::io::split(tcp);
				let mut read_half = BufReader::new(read_half);

				tracing::debug!("sending encrypt_channel");
				let req = pmap! { "_action" => "encrypt_channel" };
				frame::send_message(&mut write_half, frame::SCMD_SSL_UPGRADE, &req).await?;
				let resp = pstream::decode_from(&mut read_half, None).await?;
				error::check_server_error(&resp)?;
				tracing::debug!("encrypt_channel accepted");

				let tcp = read_half.into_inner().unsplit(write_half);

				let config = match tls_config {
					Some(c) => Arc::clone(c),
					None => Arc::new(build_tls_config(tls)?),
				};
				let server_name = ServerName::try_from(host.to_string()).or_else(|_| {
					host.parse::<std::net::IpAddr>()
						.map(|ip| ServerName::IpAddress(ip.into()))
						.map_err(|_| {
							Error::InvalidConfig(format!(
								"'{host}' is not a valid TLS server name or IP address"
							))
						})
				})?;
				let connector = TlsConnector::from(config);
				tracing::debug!("tls handshake");
				let tls_stream = connector.connect(server_name, tcp).await?;
				tracing::debug!("tls complete");

				Ok(Self::from_stream(tls_stream))
			},
		}
	}

	pub(crate) fn from_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
		stream: S,
	) -> Self {
		let dyn_stream = DynStream(Box::new(stream));
		let (read_half, write_half) = tokio::io::split(dyn_stream);
		Self {
			writer: write_half,
			alive_interval: None,
			last_active: Instant::now(),
			reader: BufReader::new(read_half),
		}
	}

	pub async fn send(&mut self, scmd: u8, obj: &PObject) -> Result<()> {
		self.last_active = Instant::now();
		frame::send_message(&mut self.writer, scmd, obj).await
	}

	/// Receive a server response, skipping keep-alives.
	///
	/// If the response uses `@proto.body-continue` framing, all continuation
	/// frames are consumed and their array fields merged into the first frame
	/// before returning.
	pub async fn recv(&mut self) -> Result<PObject> {
		let mut obj = self.recv_single().await?;

		// Reassemble body-continue frames: the server splits large arrays
		// across multiple PObject frames, each with @proto.body-continue = true
		// except the final frame which has body-continue = false.
		while has_body_continue(&obj) {
			let cont = self.recv_single().await?;
			let more = has_body_continue(&cont);
			merge_continuation(&mut obj, cont);
			if !more {
				break;
			}
		}

		self.last_active = Instant::now();
		Ok(obj)
	}

	/// Receive a single `PObject` frame, skipping keep-alives.
	async fn recv_single(&mut self) -> Result<PObject> {
		loop {
			let obj = pstream::decode_from(&mut self.reader, None).await?;
			if !pstream::is_keep_alive(&obj) {
				return Ok(obj);
			}
		}
	}

	/// Returns true if this channel has been idle longer than its `alive_interval`.
	#[must_use]
	pub fn is_expired(&self) -> bool {
		self.alive_interval
			.is_some_and(|secs| self.last_active.elapsed() >= Duration::from_secs(secs))
	}

	pub async fn request(&mut self, scmd: u8, obj: &PObject) -> Result<PObject> {
		self.send(scmd, obj).await?;
		let response = self.recv().await?;
		error::check_server_error(&response)?;
		Ok(response)
	}

	/// Receive a download response, streaming any inline file data to `dest`.
	///
	/// The returned `PObject` contains the complete response including any
	/// post-binary metadata (file hash, size, etc.).
	pub async fn recv_download<W: AsyncWrite + Unpin + Send>(
		&mut self,
		dest: &mut W,
	) -> Result<PObject> {
		let obj = loop {
			let obj = pstream::decode_from(&mut self.reader, Some(dest)).await?;
			if !pstream::is_keep_alive(&obj) {
				break obj;
			}
		};
		error::check_server_error(&obj)?;
		self.last_active = Instant::now();
		Ok(obj)
	}
}

/// A writer that lazily creates the underlying writer on first write.
///
/// Useful for download responses where we don't want to create the destination
/// file until we know the server is actually sending binary data.
pub struct LazyWriter<F, W> {
	make: Option<F>,
	inner: Option<W>,
}

impl<F, W> LazyWriter<F, W>
where
	F: FnOnce() -> io::Result<W>,
{
	pub const fn new(make: F) -> Self {
		Self {
			inner: None,
			make: Some(make),
		}
	}

	fn ensure_inner(&mut self) -> io::Result<&mut W> {
		if self.inner.is_none() {
			let make = self
				.make
				.take()
				.ok_or_else(|| io::Error::other("writer creation already failed"))?;
			self.inner = Some(make()?);
		}

		Ok(self.inner.as_mut().unwrap())
	}
}

impl<F, W> AsyncWrite for LazyWriter<F, W>
where
	W: AsyncWrite + Unpin,
	F: FnOnce() -> io::Result<W> + Unpin,
{
	fn poll_write(
		self: Pin<&mut Self>,
		cx: &mut Context<'_>,
		buf: &[u8],
	) -> Poll<io::Result<usize>> {
		let this = self.get_mut();
		let inner = match this.ensure_inner() {
			Ok(w) => w,
			Err(e) => return Poll::Ready(Err(e)),
		};
		Pin::new(inner).poll_write(cx, buf)
	}

	fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
		let this = self.get_mut();

		this.inner
			.as_mut()
			.map_or(Poll::Ready(Ok(())), |inner| Pin::new(inner).poll_flush(cx))
	}

	fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
		let this = self.get_mut();

		this.inner.as_mut().map_or(Poll::Ready(Ok(())), |inner| {
			Pin::new(inner).poll_shutdown(cx)
		})
	}
}

/// Check if a response has `@proto.body-continue` set to a truthy value.
fn has_body_continue(obj: &PObject) -> bool {
	obj.get("@proto")
		.and_then(|p| p.get("body-continue"))
		.and_then(PObject::as_int)
		.is_some_and(|v| v != 0)
}

/// Merge array fields from a continuation frame into the base response.
///
/// For each array key in `cont`, appends its elements to the matching array
/// in `base`, or inserts the array if `base` doesn't have that key yet.
/// Non-array fields and `@proto` are skipped (the base frame's metadata is
/// authoritative).
fn merge_continuation(base: &mut PObject, cont: PObject) {
	let PObject::Map(cont_map) = cont else { return };
	let Some(base_map) = base.as_map_mut() else {
		return;
	};

	for (key, cont_val) in cont_map {
		if key == "@proto" {
			continue;
		}
		let PObject::Array(cont_items) = cont_val else {
			continue;
		};
		match base_map.get_mut(&key) {
			Some(PObject::Array(base_items)) => {
				base_items.extend(cont_items);
			},
			_ => {
				base_map.insert(key, PObject::Array(cont_items));
			},
		}
	}
}

pub fn build_tls_config(tls: TlsMode) -> Result<rustls::ClientConfig> {
	let builder = rustls::ClientConfig::builder_with_provider(Arc::new(
		rustls::crypto::ring::default_provider(),
	))
	.with_safe_default_protocol_versions()
	.map_err(Error::Tls)?;

	match tls {
		TlsMode::Insecure => Ok(builder
			.dangerous()
			.with_custom_certificate_verifier(Arc::new(NoVerifier))
			.with_no_client_auth()),
		TlsMode::Verified => {
			let certs = rustls_native_certs::load_native_certs();
			if certs.certs.is_empty() {
				let err_msg = if certs.errors.is_empty() {
					"no CA certificates found in system trust store".into()
				} else {
					format!(
						"failed to load CA certificates: {}",
						certs
							.errors
							.iter()
							.map(ToString::to_string)
							.collect::<Vec<_>>()
							.join("; ")
					)
				};
				return Err(Error::InvalidConfig(err_msg));
			}
			let mut root_store = rustls::RootCertStore::empty();
			for cert in certs.certs {
				root_store.add(cert).ok();
			}
			Ok(builder
				.with_root_certificates(root_store)
				.with_no_client_auth())
		},
		TlsMode::None => unreachable!(),
	}
}

/// No-op TLS certificate verifier for self-signed NAS certs.
#[derive(Debug)]
struct NoVerifier;

static NO_VERIFY_SCHEMES: std::sync::LazyLock<Vec<rustls::SignatureScheme>> =
	std::sync::LazyLock::new(|| {
		rustls::crypto::ring::default_provider()
			.signature_verification_algorithms
			.supported_schemes()
	});

impl rustls::client::danger::ServerCertVerifier for NoVerifier {
	fn verify_server_cert(
		&self,
		_end_entity: &rustls::pki_types::CertificateDer<'_>,
		_intermediates: &[rustls::pki_types::CertificateDer<'_>],
		_server_name: &ServerName<'_>,
		_ocsp_response: &[u8],
		_now: rustls::pki_types::UnixTime,
	) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
		Ok(rustls::client::danger::ServerCertVerified::assertion())
	}

	fn verify_tls12_signature(
		&self,
		_message: &[u8],
		_cert: &rustls::pki_types::CertificateDer<'_>,
		_dss: &rustls::DigitallySignedStruct,
	) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
		Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
	}

	fn verify_tls13_signature(
		&self,
		_message: &[u8],
		_cert: &rustls::pki_types::CertificateDer<'_>,
		_dss: &rustls::DigitallySignedStruct,
	) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
		Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
	}

	fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
		NO_VERIFY_SCHEMES.clone()
	}
}

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

	/// Build wire bytes for a download response with embedded binary data.
	fn build_download_response(file_data: &[u8]) -> Vec<u8> {
		let mut buf = Vec::new();

		// Outer map start
		buf.push(0x42);

		// "type" => "response"
		pstream::encode(&PObject::Str("type".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Str("response".into()), &mut buf).unwrap();

		// "sync_id" => 100
		pstream::encode(&PObject::Str("sync_id".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Integer(100), &mut buf).unwrap();

		// "file" => { "data" => <binary>, "hash" => "abc123", "size" => N }
		pstream::encode(&PObject::Str("file".into()), &mut buf).unwrap();
		buf.push(0x42); // inner map start

		pstream::encode(&PObject::Str("data".into()), &mut buf).unwrap();
		// Binary tag + u64 BE length + raw data
		buf.push(0x30);
		buf.extend_from_slice(&(file_data.len() as u64).to_be_bytes());
		buf.extend_from_slice(file_data);

		pstream::encode(&PObject::Str("hash".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Str("abc123".into()), &mut buf).unwrap();

		pstream::encode(&PObject::Str("size".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Integer(file_data.len() as u64), &mut buf).unwrap();

		buf.push(0x40); // inner map end
		buf.push(0x40); // outer map end

		buf
	}

	#[tokio::test]
	async fn recv_download_streams_binary_data() {
		let file_data = b"hello this is file content for testing";
		let response_bytes = build_download_response(file_data);

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&response_bytes).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let mut dest = Vec::new();
		let obj = ch.recv_download(&mut dest).await.unwrap();

		assert_eq!(dest, file_data);
		assert_eq!(obj.get("sync_id").and_then(PObject::as_int), Some(100));
		// Post-binary fields are preserved
		let file = obj.get("file").unwrap();
		assert_eq!(file.get("hash").and_then(PObject::as_str), Some("abc123"));
		assert_eq!(
			file.get("size").and_then(PObject::as_int),
			Some(file_data.len() as u64)
		);
	}

	#[tokio::test]
	async fn recv_download_skips_keepalives() {
		let file_data = b"the real file data after keepalives";

		let mut stream_bytes = Vec::new();
		let ka = pmap! { "type" => "keep_alive" };
		pstream::encode(&ka, &mut stream_bytes).unwrap();
		pstream::encode(&ka, &mut stream_bytes).unwrap();
		stream_bytes.extend_from_slice(&build_download_response(file_data));

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&stream_bytes).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let mut dest = Vec::new();
		let obj = ch.recv_download(&mut dest).await.unwrap();

		assert_eq!(dest, file_data);
		assert_eq!(obj.get("sync_id").and_then(PObject::as_int), Some(100));
	}

	#[tokio::test]
	async fn recv_download_no_binary_data() {
		let response = pmap! {
			"type" => "response",
			"sync_id" => 100u64,
			"file" => pmap! {
				"refer" => true,
				"hash" => "abc123",
			},
		};
		let mut response_bytes = Vec::new();
		pstream::encode(&response, &mut response_bytes).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&response_bytes).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let mut dest = Vec::new();
		let obj = ch.recv_download(&mut dest).await.unwrap();

		assert!(dest.is_empty());
		assert_eq!(obj.get("sync_id").and_then(PObject::as_int), Some(100));
	}

	/// Build a download response using `BinaryEx` (0x43) instead of `Binary` (0x30).
	/// `BinaryEx` wraps the data in an extra map: `{ "binary": <0x30 data>, "send_hash": "..." }`
	fn build_binary_ex_download_response(file_data: &[u8]) -> Vec<u8> {
		let mut buf = Vec::new();

		buf.push(0x42); // outer map

		pstream::encode(&PObject::Str("sync_id".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Integer(200), &mut buf).unwrap();

		pstream::encode(&PObject::Str("file".into()), &mut buf).unwrap();
		buf.push(0x42); // file map

		pstream::encode(&PObject::Str("data".into()), &mut buf).unwrap();
		// BinaryEx: 0x43 { "binary": 0x30 <len> <data>, "send_hash": "abc" } 0x40
		buf.push(0x43);
		pstream::encode(&PObject::Str("binary".into()), &mut buf).unwrap();
		buf.push(0x30);
		buf.extend_from_slice(&(file_data.len() as u64).to_be_bytes());
		buf.extend_from_slice(file_data);
		pstream::encode(&PObject::Str("send_hash".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Str("deadbeef".into()), &mut buf).unwrap();
		buf.push(0x40); // end binary_ex

		pstream::encode(&PObject::Str("hash".into()), &mut buf).unwrap();
		pstream::encode(&PObject::Str("filehash".into()), &mut buf).unwrap();

		buf.push(0x40); // end file map
		buf.push(0x40); // end outer map

		buf
	}

	#[tokio::test]
	async fn recv_download_binary_ex_drains_correctly() {
		let file_data = b"binary_ex file content";
		let mut stream = build_binary_ex_download_response(file_data);

		// Append a second PObject right after the download response.
		// If the drain depth is wrong, this will be corrupted or unreadable.
		let followup = pmap! { "type" => "followup", "value" => 42u64 };
		pstream::encode(&followup, &mut stream).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&stream).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);

		// First: download with BinaryEx
		let mut dest = Vec::new();
		let obj = ch.recv_download(&mut dest).await.unwrap();
		assert_eq!(dest, file_data);
		assert_eq!(obj.get("sync_id").and_then(PObject::as_int), Some(200));
		// Post-binary fields are preserved
		let file = obj.get("file").unwrap();
		assert_eq!(file.get("hash").and_then(PObject::as_str), Some("filehash"));
		// BinaryEx send_hash is captured even though it appears after "binary" on the wire
		match file.get("data").unwrap() {
			PObject::BinaryEx { send_hash, .. } => assert_eq!(send_hash, "deadbeef"),
			other => panic!("expected BinaryEx, got {other:?}"),
		}

		// Second: read the followup message on the same channel.
		// This fails if BinaryEx left a trailing TAG_END unread.
		let next = pstream::decode_from(&mut ch.reader, None).await.unwrap();
		assert_eq!(next.get("type").and_then(PObject::as_str), Some("followup"));
		assert_eq!(next.get("value").and_then(PObject::as_int), Some(42));
	}

	#[tokio::test]
	async fn recv_download_binary_drains_correctly() {
		let file_data = b"plain binary content";
		let mut stream = build_download_response(file_data);

		// Append a followup message
		let followup = pmap! { "type" => "followup", "value" => 99u64 };
		pstream::encode(&followup, &mut stream).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&stream).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);

		let mut dest = Vec::new();
		let obj = ch.recv_download(&mut dest).await.unwrap();
		assert_eq!(dest, file_data);
		assert_eq!(obj.get("sync_id").and_then(PObject::as_int), Some(100));

		// Channel should be clean — followup readable
		let next = pstream::decode_from(&mut ch.reader, None).await.unwrap();
		assert_eq!(next.get("type").and_then(PObject::as_str), Some("followup"));
		assert_eq!(next.get("value").and_then(PObject::as_int), Some(99));
	}

	#[tokio::test]
	async fn recv_reassembles_body_continue_frames() {
		// Frame 1: header with body-continue=true and first batch of items
		let frame1 = pmap! {
			"@proto" => pmap! {
				"type" => "header",
				"body-continue" => true,
			},
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "file1.txt" },
				pmap! { "name" => "file2.txt" },
			]),
		};
		// Frame 2: continuation with body-continue=true
		let frame2 = pmap! {
			"@proto" => pmap! {
				"type" => "header",
				"body-continue" => true,
			},
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "file3.txt" },
			]),
		};
		// Frame 3: final with body-continue=false
		let frame3 = pmap! {
			"@proto" => pmap! {
				"type" => "header",
				"body-continue" => false,
			},
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "file4.txt" },
			]),
		};

		let mut wire = Vec::new();
		pstream::encode(&frame1, &mut wire).unwrap();
		pstream::encode(&frame2, &mut wire).unwrap();
		pstream::encode(&frame3, &mut wire).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&wire).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let result = ch.recv().await.unwrap();

		let node_list = result.get("node_list").and_then(PObject::as_array).unwrap();
		assert_eq!(node_list.len(), 4);
		assert_eq!(
			node_list[0].get("name").and_then(PObject::as_str),
			Some("file1.txt")
		);
		assert_eq!(
			node_list[1].get("name").and_then(PObject::as_str),
			Some("file2.txt")
		);
		assert_eq!(
			node_list[2].get("name").and_then(PObject::as_str),
			Some("file3.txt")
		);
		assert_eq!(
			node_list[3].get("name").and_then(PObject::as_str),
			Some("file4.txt")
		);
	}

	#[tokio::test]
	async fn recv_returns_single_frame_without_body_continue() {
		let frame = pmap! {
			"@proto" => pmap! {
				"type" => "header",
				"body-continue" => false,
			},
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "only.txt" },
			]),
		};

		let mut wire = Vec::new();
		pstream::encode(&frame, &mut wire).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&wire).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let result = ch.recv().await.unwrap();

		let node_list = result.get("node_list").and_then(PObject::as_array).unwrap();
		assert_eq!(node_list.len(), 1);
		assert_eq!(
			node_list[0].get("name").and_then(PObject::as_str),
			Some("only.txt")
		);
	}

	#[tokio::test]
	async fn recv_merges_arrays_absent_from_header_frame() {
		// Header frame has body-continue but no node_list.
		let header = pmap! {
			"@proto" => pmap! {
				"type" => "header",
				"body-continue" => true,
			},
			"action" => "list_sync_to_device",
		};
		// Continuation introduces node_list for the first time.
		let body1 = pmap! {
			"@proto" => pmap! { "body-continue" => true },
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "a.txt" },
			]),
		};
		let body2 = pmap! {
			"@proto" => pmap! { "body-continue" => false },
			"node_list" => PObject::Array(vec![
				pmap! { "name" => "b.txt" },
			]),
		};

		let mut wire = Vec::new();
		pstream::encode(&header, &mut wire).unwrap();
		pstream::encode(&body1, &mut wire).unwrap();
		pstream::encode(&body2, &mut wire).unwrap();

		let (client, mut server) = tokio::io::duplex(65536);
		tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			server.write_all(&wire).await.unwrap();
			server.shutdown().await.unwrap();
		});

		let mut ch = Channel::from_stream(client);
		let result = ch.recv().await.unwrap();

		let node_list = result.get("node_list").and_then(PObject::as_array).unwrap();
		assert_eq!(node_list.len(), 2);
		assert_eq!(
			node_list[0].get("name").and_then(PObject::as_str),
			Some("a.txt")
		);
		assert_eq!(
			node_list[1].get("name").and_then(PObject::as_str),
			Some("b.txt")
		);
		// Header-only fields should still be present.
		assert_eq!(
			result.get("action").and_then(PObject::as_str),
			Some("list_sync_to_device")
		);
	}
}