-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.rs
More file actions
1641 lines (1487 loc) · 59.8 KB
/
router.rs
File metadata and controls
1641 lines (1487 loc) · 59.8 KB
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! S3 API router — full API surface translating HTTP to SMB operations.
//!
//! Covers: GetObject (range + conditional), PutObject (conditional-write),
//! CopyObject, DeleteObject, HeadObject, ListObjectsV1/V2, ListBuckets,
//! MultipartUpload (create/upload-part/complete/abort/list-parts/list-uploads),
//! GetBucketLocation, HeadBucket, CreateBucket, DeleteBucket,
//! GetBucketVersioning, GetBucketAcl, PutBucketAcl, GetObjectAcl, PutObjectAcl,
//! GetBucketTagging, PutBucketTagging, DeleteBucketTagging,
//! GetObjectTagging, PutObjectTagging, DeleteObjectTagging,
//! OPTIONS (CORS preflight), and proper S3 error responses.
use bytes::Bytes;
use http::{Method, Request, Response, StatusCode};
use http_body_util::BodyExt;
use hyper::body::Incoming;
use std::io;
use std::sync::Arc;
use super::body::SpiceioBody;
use super::headers::*;
use super::multipart::MultipartStore;
use super::xml::{self, XmlWriter};
use crate::smb::ops::ShareSession;
const S3_XMLNS: &str = "http://s3.amazonaws.com/doc/2006-03-01/";
/// Shared application state passed to the router.
pub struct AppState {
pub share: Arc<ShareSession>,
pub bucket: String,
pub region: String,
pub multipart: MultipartStore,
}
/// Handle an incoming S3 API request.
///
/// Accepts the raw `Incoming` body — GetObject and PutObject stream without
/// buffering the entire payload. Operations that need the full body (multipart,
/// multi-delete, copy) collect it internally.
pub async fn handle_request(req: Request<Incoming>, state: &AppState) -> Response<SpiceioBody> {
let path = req.uri().path().to_owned();
let query = req.uri().query().unwrap_or("").to_owned();
let method = req.method().clone();
let hdrs = req.headers().clone();
let request_id = generate_request_id();
// CORS preflight
if method == Method::OPTIONS {
return cors_preflight(&request_id, &state.region);
}
// Parse bucket and key from path-style: /{bucket}/{key...}
let (req_bucket, key) = parse_path(&path);
// Service-level operations (no bucket)
if req_bucket.is_empty() {
match method {
Method::GET | Method::HEAD => {
return with_common_headers(
list_buckets_response(&state.bucket),
&request_id,
&state.region,
);
}
_ => {
return with_common_headers(
error_response(
StatusCode::METHOD_NOT_ALLOWED,
"MethodNotAllowed",
"Method not allowed",
),
&request_id,
&state.region,
);
}
}
}
// Bucket must match our configured bucket
if req_bucket != state.bucket {
return with_common_headers(
error_response(
StatusCode::NOT_FOUND,
"NoSuchBucket",
"The specified bucket does not exist.",
),
&request_id,
&state.region,
);
}
let share = &state.share;
// ── Bucket-level operations (no key) ────────────────────────────────
if key.is_empty() {
let resp = match method {
Method::GET | Method::HEAD if query.contains("location") => {
handle_get_bucket_location(&state.region)
}
Method::GET if query.contains("versioning") => handle_get_bucket_versioning(),
Method::GET if query.contains("acl") => handle_get_bucket_acl(),
Method::PUT if query.contains("acl") => ok_empty(),
Method::GET if query.contains("tagging") => handle_get_bucket_tagging(),
Method::PUT if query.contains("tagging") => ok_empty(),
Method::DELETE if query.contains("tagging") => ok_no_content(),
Method::GET if query.contains("cors") => handle_get_bucket_cors(),
Method::PUT if query.contains("cors") => ok_empty(),
Method::DELETE if query.contains("cors") => ok_no_content(),
Method::GET if query.contains("lifecycle") => handle_get_bucket_lifecycle(),
Method::GET if query.contains("policy") => handle_get_bucket_policy(),
Method::GET if query.contains("encryption") => handle_get_bucket_encryption(),
Method::GET if query.contains("uploads") => {
handle_list_multipart_uploads(state, &query).await
}
Method::POST if query.contains("delete") => {
let body = collect_body(req).await;
handle_delete_objects(body, share).await
}
Method::GET => handle_list_objects(share, &state.bucket, &query).await,
Method::HEAD => head_bucket_response(&state.region),
Method::PUT => ok_empty(), // CreateBucket — noop
Method::DELETE => ok_no_content(), // DeleteBucket — noop
_ => error_response(
StatusCode::METHOD_NOT_ALLOWED,
"MethodNotAllowed",
"Method not allowed",
),
};
return with_common_headers(resp, &request_id, &state.region);
}
// ── Object-level operations ─────────────────────────────────────────
// Multipart: POST with ?uploads (initiate) or ?uploadId=... (complete)
if method == Method::POST {
let resp = if query.contains("uploads") && !query.contains("uploadId") {
handle_create_multipart_upload(&hdrs, state, key).await
} else if let Some(upload_id) = extract_query_param(&query, "uploadId") {
let body = collect_body(req).await;
handle_complete_multipart_upload(body, state, key, &upload_id).await
} else {
error_response(
StatusCode::BAD_REQUEST,
"InvalidRequest",
"Invalid POST request",
)
};
return with_common_headers(resp, &request_id, &state.region);
}
// Multipart: PUT with ?partNumber=...&uploadId=...
if method == Method::PUT && query.contains("partNumber") && query.contains("uploadId") {
let part_number: u32 = extract_query_param(&query, "partNumber")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let upload_id = extract_query_param(&query, "uploadId").unwrap_or_default();
let resp = handle_upload_part(req, state, key, &upload_id, part_number).await;
return with_common_headers(resp, &request_id, &state.region);
}
// Multipart: GET with ?uploadId=... (list parts)
if method == Method::GET && query.contains("uploadId") {
let upload_id = extract_query_param(&query, "uploadId").unwrap_or_default();
let resp = handle_list_parts(state, key, &upload_id).await;
return with_common_headers(resp, &request_id, &state.region);
}
// Multipart: DELETE with ?uploadId=... (abort)
if method == Method::DELETE && query.contains("uploadId") {
let upload_id = extract_query_param(&query, "uploadId").unwrap_or_default();
let resp = handle_abort_multipart_upload(state, key, &upload_id).await;
return with_common_headers(resp, &request_id, &state.region);
}
// Object ACL
if query.contains("acl") {
let resp = match method {
Method::GET => handle_get_object_acl(),
Method::PUT => ok_empty(),
_ => error_response(StatusCode::METHOD_NOT_ALLOWED, "MethodNotAllowed", ""),
};
return with_common_headers(resp, &request_id, &state.region);
}
// Object tagging
if query.contains("tagging") {
let resp = match method {
Method::GET => handle_get_object_tagging(),
Method::PUT => ok_empty(),
Method::DELETE => ok_no_content(),
_ => error_response(StatusCode::METHOD_NOT_ALLOWED, "MethodNotAllowed", ""),
};
return with_common_headers(resp, &request_id, &state.region);
}
// Object legal-hold, retention, torrent — stubs
if query.contains("legal-hold") || query.contains("retention") || query.contains("torrent") {
let resp = match method {
Method::GET | Method::PUT => ok_empty(),
_ => error_response(StatusCode::NOT_IMPLEMENTED, "NotImplemented", ""),
};
return with_common_headers(resp, &request_id, &state.region);
}
// Object restore — stub
if method == Method::POST && query.contains("restore") {
return with_common_headers(
Response::builder()
.status(StatusCode::ACCEPTED)
.body(SpiceioBody::empty())
.unwrap(),
&request_id,
&state.region,
);
}
// SelectObjectContent — not supported
if method == Method::POST && query.contains("select") {
return with_common_headers(
error_response(
StatusCode::NOT_IMPLEMENTED,
"NotImplemented",
"SelectObjectContent is not supported",
),
&request_id,
&state.region,
);
}
let resp = match method {
Method::GET => handle_get_object(&hdrs, share, key).await,
Method::PUT => {
// CopyObject: PUT with x-amz-copy-source header
if hdrs.contains_key(X_AMZ_COPY_SOURCE) {
handle_copy_object(&hdrs, share, key).await
} else {
handle_put_object(req, &hdrs, share, key).await
}
}
Method::DELETE => handle_delete_object(share, key).await,
Method::HEAD => handle_head_object(&hdrs, share, key).await,
_ => error_response(
StatusCode::METHOD_NOT_ALLOWED,
"MethodNotAllowed",
"Method not allowed",
),
};
with_common_headers(resp, &request_id, &state.region)
}
// ── Path parsing ────────────────────────────────────────────────────────────
fn parse_path(path: &str) -> (&str, &str) {
let trimmed = path.trim_start_matches('/');
if trimmed.is_empty() {
return ("", "");
}
match trimmed.find('/') {
Some(pos) => (&trimmed[..pos], &trimmed[pos + 1..]),
None => (trimmed, ""),
}
}
// ── ListObjects V1/V2 ──────────────────────────────────────────────────────
async fn handle_list_objects(
share: &ShareSession,
bucket: &str,
query: &str,
) -> Response<SpiceioBody> {
let list_type = extract_query_param(query, "list-type").unwrap_or_default();
let prefix = extract_query_param(query, "prefix").unwrap_or_default();
let delimiter = extract_query_param(query, "delimiter");
let max_keys: usize = extract_query_param(query, "max-keys")
.and_then(|s| s.parse().ok())
.unwrap_or(1000);
let marker = extract_query_param(query, "marker").unwrap_or_default();
let start_after = extract_query_param(query, "start-after").unwrap_or_default();
let continuation_token = extract_query_param(query, "continuation-token");
let encoding_type = extract_query_param(query, "encoding-type");
let fetch_owner = extract_query_param(query, "fetch-owner")
.map(|s| s == "true")
.unwrap_or(false);
let result = share.list_objects(&prefix, delimiter.as_deref()).await;
let skip_marker = if list_type == "2" {
continuation_token.as_deref().unwrap_or(&start_after)
} else {
&marker
};
match result {
Ok((mut objects, common_prefixes)) => {
// Apply marker/start-after/continuation-token filtering
if !skip_marker.is_empty() {
objects.retain(|o| o.key.as_str() > skip_marker);
}
let truncated = objects.len() > max_keys;
let display_objects = if truncated {
&objects[..max_keys]
} else {
&objects
};
let next_marker = if truncated {
display_objects.last().map(|o| o.key.clone())
} else {
None
};
let mut w = XmlWriter::new();
w.declaration();
if list_type == "2" {
// ListObjectsV2
w.open_ns("ListBucketResult", S3_XMLNS);
w.element("Name", bucket);
w.element("Prefix", &prefix);
if let Some(d) = &delimiter {
w.element("Delimiter", d);
}
w.element("MaxKeys", &max_keys.to_string());
if let Some(et) = &encoding_type {
w.element("EncodingType", et);
}
w.element("KeyCount", &display_objects.len().to_string());
w.element("IsTruncated", if truncated { "true" } else { "false" });
if let Some(ct) = &continuation_token {
w.element("ContinuationToken", ct);
}
if let Some(ref nm) = next_marker {
w.element("NextContinuationToken", nm);
}
if !start_after.is_empty() {
w.element("StartAfter", &start_after);
}
for obj in display_objects {
w.open("Contents");
w.element("Key", &obj.key);
w.element("LastModified", &xml::epoch_to_iso8601(obj.last_modified));
w.element("ETag", &format!("\"{}\"", obj.etag));
w.element("Size", &obj.size.to_string());
w.element("StorageClass", "STANDARD");
if fetch_owner {
w.open("Owner");
w.element("ID", "spiceio");
w.element("DisplayName", "spiceio");
w.close("Owner");
}
w.close("Contents");
}
} else {
// ListObjectsV1
w.open_ns("ListBucketResult", S3_XMLNS);
w.element("Name", bucket);
w.element("Prefix", &prefix);
if !marker.is_empty() {
w.element("Marker", &marker);
}
if let Some(d) = &delimiter {
w.element("Delimiter", d);
}
w.element("MaxKeys", &max_keys.to_string());
if let Some(et) = &encoding_type {
w.element("EncodingType", et);
}
w.element("IsTruncated", if truncated { "true" } else { "false" });
if let Some(ref nm) = next_marker {
w.element("NextMarker", nm);
}
for obj in display_objects {
w.open("Contents");
w.element("Key", &obj.key);
w.element("LastModified", &xml::epoch_to_iso8601(obj.last_modified));
w.element("ETag", &format!("\"{}\"", obj.etag));
w.element("Size", &obj.size.to_string());
w.open("Owner");
w.element("ID", "spiceio");
w.element("DisplayName", "spiceio");
w.close("Owner");
w.element("StorageClass", "STANDARD");
w.close("Contents");
}
}
for cp in &common_prefixes {
w.open("CommonPrefixes");
w.element("Prefix", cp);
w.close("CommonPrefixes");
}
w.close("ListBucketResult");
xml_response(StatusCode::OK, w.finish())
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let mut w = XmlWriter::new();
w.declaration();
w.open_ns("ListBucketResult", S3_XMLNS);
w.element("Name", bucket);
w.element("Prefix", &prefix);
w.element("MaxKeys", &max_keys.to_string());
w.element("KeyCount", "0");
w.element("IsTruncated", "false");
w.close("ListBucketResult");
xml_response(StatusCode::OK, w.finish())
}
Err(e) => io_to_s3_error(&e),
}
}
// ── GetObject (streaming, with Range + Conditional) ─────────────────────────
/// Compute the SMB-reads→HTTP-writes channel capacity for a streaming
/// GetObject given the SMB-negotiated chunk size.
///
/// Sized to hold one full SMB read pipeline batch (so back-to-back batches
/// can overlap) but capped by an 8 MiB per-request memory budget so a
/// configured `SPICEIO_SMB_MAX_IO` of 1 MiB doesn't blow up to 64 MiB of
/// buffering per concurrent stream.
///
/// Guards against `chunk_size = 0`: `handle.max_chunk` ultimately comes from
/// the SMB server's `max_read_size` in the negotiate response. If a server
/// (or a misconfiguration) yields 0, naive `BUDGET / chunk_size` would
/// divide-by-zero panic and crash the streaming task. We floor at 1 here.
fn stream_channel_capacity(chunk_size: u32) -> usize {
const STREAM_CHANNEL_MAX_BYTES: usize = 8 * 1024 * 1024;
let chunk_size_for_cap = (chunk_size as usize).max(1);
(STREAM_CHANNEL_MAX_BYTES / chunk_size_for_cap).clamp(1, crate::smb::ops::READ_PIPELINE_DEPTH)
}
async fn handle_get_object(
hdrs: &http::HeaderMap,
share: &ShareSession,
key: &str,
) -> Response<SpiceioBody> {
let range_header = get_header(hdrs, "range").map(String::from);
let if_match = get_header(hdrs, IF_MATCH).map(String::from);
let if_none_match = get_header(hdrs, IF_NONE_MATCH).map(String::from);
let if_modified_since = get_header(hdrs, IF_MODIFIED_SINCE).map(String::from);
let if_unmodified_since = get_header(hdrs, IF_UNMODIFIED_SINCE).map(String::from);
// ── Fast path: compound Create+Read+Close for small files ───────
// Tries to read the entire file in one SMB round trip. Falls back to
// streaming for large files or range requests.
let max_read = share.compound_max_read_size();
let no_range = range_header.is_none();
if no_range {
let result = share.get_object_compound(key, max_read).await;
match result {
Ok((meta, data)) if meta.size <= max_read as u64 => {
let etag = format!("\"{}\"", meta.etag);
if let Some(ref im) = if_match
&& !etag_matches(im, &etag)
{
return error_response(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
"At least one of the preconditions you specified did not hold.",
);
}
if let Some(ref inm) = if_none_match
&& etag_matches(inm, &etag)
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
if let Some(ref ims) = if_modified_since
&& let Some(since) = parse_http_date(ims)
&& meta.last_modified <= since
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
if let Some(ref ius) = if_unmodified_since
&& let Some(since) = parse_http_date(ius)
&& meta.last_modified > since
{
return error_response(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
"At least one of the preconditions you specified did not hold.",
);
}
let last_modified = xml::epoch_to_http_date(meta.last_modified);
return Response::builder()
.status(StatusCode::OK)
.header("Content-Type", &meta.content_type)
.header("Content-Length", data.len().to_string())
.header("ETag", &etag)
.header("Last-Modified", last_modified)
.header("Accept-Ranges", "bytes")
.body(SpiceioBody::full(data))
.unwrap();
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return error_response(
StatusCode::NOT_FOUND,
"NoSuchKey",
"The specified key does not exist.",
);
}
Err(e) => return io_to_s3_error(&e),
_ => {} // Large file — fall through to streaming
}
}
// ── Streaming path for large files and range requests ─────────
let handle = match share.open_read(key).await {
Ok(h) => h,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return error_response(
StatusCode::NOT_FOUND,
"NoSuchKey",
"The specified key does not exist.",
);
}
Err(e) => return io_to_s3_error(&e),
};
let meta = &handle.meta;
let etag = format!("\"{}\"", meta.etag);
// Conditional: If-Match
if let Some(ref im) = if_match
&& !etag_matches(im, &etag)
{
let _ = handle.close().await;
return error_response(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
"At least one of the preconditions you specified did not hold.",
);
}
// Conditional: If-None-Match → 304
if let Some(ref inm) = if_none_match
&& etag_matches(inm, &etag)
{
let _ = handle.close().await;
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
// Conditional: If-Modified-Since → 304
if let Some(ref ims) = if_modified_since
&& let Some(since) = parse_http_date(ims)
&& meta.last_modified <= since
{
let _ = handle.close().await;
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
// Conditional: If-Unmodified-Since
if let Some(ref ius) = if_unmodified_since
&& let Some(since) = parse_http_date(ius)
&& meta.last_modified > since
{
let _ = handle.close().await;
return error_response(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
"At least one of the preconditions you specified did not hold.",
);
}
let last_modified = xml::epoch_to_http_date(meta.last_modified);
let content_type = meta.content_type.clone();
let file_size = handle.file_size;
// Determine read range
let (start, end, is_range) = if let Some(ref range_str) = range_header {
if let Some(range) = parse_range(range_str) {
match range.resolve(file_size) {
Some((s, e)) => (s, e, true),
None => {
let _ = handle.close().await;
return error_response(
StatusCode::RANGE_NOT_SATISFIABLE,
"InvalidRange",
"The requested range is not satisfiable",
);
}
}
} else {
(0, file_size.saturating_sub(1), false)
}
} else {
(0, file_size.saturating_sub(1), false)
};
let content_length = end - start + 1;
// Build response with streaming body.
//
// Channel capacity is sized so a full SMB pipeline batch can dump into
// the channel without blocking the producer — that lets the SMB-reading
// task immediately issue the next pipelined round-trip while the
// HTTP-sending task drains the previous batch, overlapping back-to-back
// batches. We also cap by a per-request memory budget: with a configured
// `SPICEIO_SMB_MAX_IO` of 1 MiB and `READ_PIPELINE_DEPTH = 64`, an
// uncapped channel would buffer up to 64 MiB per concurrent GetObject.
// At default 64 KiB chunks the channel stays at the full pipeline depth
// (4 MiB); at 1 MiB chunks it falls to 8 (still room to overlap).
let chunk_size = handle.max_chunk;
// Defense in depth: the SMB client floors any zero values from the
// server's negotiate response, but if that floor ever regresses we'd
// rather return a 500 here than panic the streaming task inside
// `handle.read_pipeline(...)` on `remaining.div_ceil(0)`.
if chunk_size == 0 {
let _ = handle.close().await;
return error_response(
StatusCode::INTERNAL_SERVER_ERROR,
"InternalError",
"SMB server negotiated max_read_size = 0",
);
}
let channel_cap = stream_channel_capacity(chunk_size);
let (body, tx) = SpiceioBody::channel(channel_cap);
// Spawn background task to stream pipelined SMB reads into the channel.
// Sends batches of read requests to fill the network pipe, then pushes
// each chunk to the HTTP response body as it arrives.
tokio::spawn(async move {
let mut offset = start;
let stream_end = end + 1;
'outer: while offset < stream_end {
let remaining = stream_end - offset;
match handle.read_pipeline(offset, chunk_size, remaining).await {
Ok(chunks) if chunks.is_empty() => break,
Ok(chunks) => {
for chunk in chunks {
if chunk.is_empty() {
break 'outer;
}
offset += chunk.len() as u64;
if tx.send(chunk).await.is_err() {
crate::serr!("[spiceio] getobject client disconnected");
break 'outer;
}
}
}
Err(e) => {
crate::serr!("[spiceio] getobject read error: {e}");
break;
}
}
}
let _ = handle.close().await;
});
if is_range {
let content_range = format!("bytes {start}-{end}/{file_size}");
Response::builder()
.status(StatusCode::PARTIAL_CONTENT)
.header("Content-Type", &content_type)
.header("Content-Length", content_length.to_string())
.header("Content-Range", content_range)
.header("ETag", &etag)
.header("Last-Modified", last_modified)
.header("Accept-Ranges", "bytes")
.body(body)
.unwrap()
} else {
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", &content_type)
.header("Content-Length", content_length.to_string())
.header("ETag", &etag)
.header("Last-Modified", last_modified)
.header("Accept-Ranges", "bytes")
.body(body)
.unwrap()
}
}
// ── PutObject (streaming, with conditional-write via If-None-Match) ─────────
async fn handle_put_object(
req: Request<Incoming>,
hdrs: &http::HeaderMap,
share: &ShareSession,
key: &str,
) -> Response<SpiceioBody> {
let if_none_match = get_header(hdrs, IF_NONE_MATCH).map(String::from);
let content_type = get_header(hdrs, "content-type").map(String::from);
// Conditional write: If-None-Match: * means "only if not exists"
if let Some(ref inm) = if_none_match
&& inm.trim() == "*"
{
// Check existence first
if share.head_object(key).await.is_ok() {
return error_response(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
"At least one of the preconditions you specified did not hold.",
);
}
}
// ── Fast path: collect small bodies and use compound write ──────
let content_length: Option<u64> =
get_header(hdrs, "content-length").and_then(|s| s.parse().ok());
let max_write = share.compound_max_write_size() as u64;
if let Some(cl) = content_length
&& cl <= max_write
{
// Collect the (small) body
match BodyExt::collect(req.into_body()).await {
Ok(collected) => {
let data = collected.to_bytes();
match share.put_object(key, &data).await {
Ok(meta) => {
let mut builder = Response::builder()
.status(StatusCode::OK)
.header("ETag", format!("\"{}\"", meta.etag));
if let Some(ct) = content_type {
builder = builder.header("Content-Type", ct);
}
return builder.body(SpiceioBody::empty()).unwrap();
}
Err(e) => return io_to_s3_error(&e),
}
}
Err(e) => {
return io_to_s3_error(&io::Error::other(format!("body read error: {e}")));
}
}
}
// ── Streaming path: buffered WAL write for large or unknown-size bodies ──
let mut wal = match share.open_wal_write(key).await {
Ok(w) => w,
Err(e) => return io_to_s3_error(&e),
};
let mut body = req.into_body();
let mut write_err = None;
while let Some(frame) = body.frame().await {
match frame {
Ok(frame) => {
if let Ok(data) = frame.into_data()
&& !data.is_empty()
&& let Err(e) = wal.write(&data).await
{
write_err = Some(e);
break;
}
}
Err(e) => {
crate::serr!("[spiceio] putobject body read error: {e}");
wal.abort().await;
return io_to_s3_error(&io::Error::other(format!("body read error: {e}")));
}
}
}
if let Some(e) = write_err {
wal.abort().await;
return io_to_s3_error(&e);
}
// Commit: flush remaining buffer, rename WAL temp → final path
let meta = match wal.commit(share).await {
Ok(m) => m,
Err(e) => return io_to_s3_error(&e),
};
let mut builder = Response::builder()
.status(StatusCode::OK)
.header("ETag", format!("\"{}\"", meta.etag));
if let Some(ct) = content_type {
builder = builder.header("Content-Type", ct);
}
builder.body(SpiceioBody::empty()).unwrap()
}
// ── CopyObject ──────────────────────────────────────────────────────────────
async fn handle_copy_object(
hdrs: &http::HeaderMap,
share: &ShareSession,
dest_key: &str,
) -> Response<SpiceioBody> {
let copy_source = match get_header(hdrs, X_AMZ_COPY_SOURCE) {
Some(s) => s.to_string(),
None => {
return error_response(
StatusCode::BAD_REQUEST,
"InvalidArgument",
"Missing x-amz-copy-source",
);
}
};
// Parse source: /bucket/key or bucket/key
let src_key = copy_source.trim_start_matches('/');
let src_key = match src_key.find('/') {
Some(pos) => &src_key[pos + 1..],
None => src_key,
};
let src_key = percent_encoding::percent_decode_str(src_key)
.decode_utf8_lossy()
.into_owned();
// Conditional copy headers
let if_match = get_header(hdrs, X_AMZ_COPY_SOURCE_IF_MATCH).map(String::from);
let if_none_match = get_header(hdrs, X_AMZ_COPY_SOURCE_IF_NONE_MATCH).map(String::from);
let if_modified_since = get_header(hdrs, X_AMZ_COPY_SOURCE_IF_MODIFIED_SINCE).map(String::from);
let if_unmodified_since =
get_header(hdrs, X_AMZ_COPY_SOURCE_IF_UNMODIFIED_SINCE).map(String::from);
// Check source metadata for conditionals
let src_meta = match share.head_object(&src_key).await {
Ok(m) => m,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return error_response(
StatusCode::NOT_FOUND,
"NoSuchKey",
"The specified source key does not exist.",
);
}
Err(e) => return io_to_s3_error(&e),
};
let etag = format!("\"{}\"", src_meta.etag);
if let Some(ref im) = if_match
&& !etag_matches(im, &etag)
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
if let Some(ref inm) = if_none_match
&& etag_matches(inm, &etag)
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
if let Some(ref ims) = if_modified_since
&& let Some(since) = parse_http_date(ims)
&& src_meta.last_modified <= since
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
if let Some(ref ius) = if_unmodified_since
&& let Some(since) = parse_http_date(ius)
&& src_meta.last_modified > since
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
match share.copy_object(&src_key, dest_key).await {
Ok(meta) => {
let mut w = XmlWriter::new();
w.declaration();
w.open("CopyObjectResult");
w.element("LastModified", &xml::epoch_to_iso8601(meta.last_modified));
w.element("ETag", &format!("\"{}\"", meta.etag));
w.close("CopyObjectResult");
xml_response(StatusCode::OK, w.finish())
}
Err(e) => io_to_s3_error(&e),
}
}
// ── DeleteObject ────────────────────────────────────────────────────────────
async fn handle_delete_object(share: &ShareSession, key: &str) -> Response<SpiceioBody> {
match share.delete_object(key).await {
Ok(()) | Err(_) => {
// S3 returns 204 even if not found
Response::builder()
.status(StatusCode::NO_CONTENT)
.body(SpiceioBody::empty())
.unwrap()
}
}
}
// ── HeadObject (with conditional) ───────────────────────────────────────────
async fn handle_head_object(
hdrs: &http::HeaderMap,
share: &ShareSession,
key: &str,
) -> Response<SpiceioBody> {
let if_match = get_header(hdrs, IF_MATCH).map(String::from);
let if_none_match = get_header(hdrs, IF_NONE_MATCH).map(String::from);
let if_modified_since = get_header(hdrs, IF_MODIFIED_SINCE).map(String::from);
let if_unmodified_since = get_header(hdrs, IF_UNMODIFIED_SINCE).map(String::from);
match share.head_object(key).await {
Ok(meta) => {
let etag = format!("\"{}\"", meta.etag);
if let Some(ref im) = if_match
&& !etag_matches(im, &etag)
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
if let Some(ref inm) = if_none_match
&& etag_matches(inm, &etag)
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
if let Some(ref ims) = if_modified_since
&& let Some(since) = parse_http_date(ims)
&& meta.last_modified <= since
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header("ETag", &etag)
.body(SpiceioBody::empty())
.unwrap();
}
if let Some(ref ius) = if_unmodified_since
&& let Some(since) = parse_http_date(ius)
&& meta.last_modified > since
{
return error_response(StatusCode::PRECONDITION_FAILED, "PreconditionFailed", "");
}
let last_modified = xml::epoch_to_http_date(meta.last_modified);
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", &meta.content_type)
.header("Content-Length", meta.size.to_string())
.header("ETag", &etag)
.header("Last-Modified", last_modified)
.header("Accept-Ranges", "bytes")
.body(SpiceioBody::empty())
.unwrap()
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(SpiceioBody::empty())
.unwrap(),
Err(e) => io_to_s3_error(&e),
}
}
// ── Multi-object Delete ─────────────────────────────────────────────────────
async fn handle_delete_objects(body: Bytes, share: &ShareSession) -> Response<SpiceioBody> {
let body_str = String::from_utf8_lossy(&body);
let keys: Vec<String> = xml::extract_sections(&body_str, "<Object>", "</Object>")
.iter()
.filter_map(|section| xml::extract_element(section, "Key"))
.map(|s| s.to_string())
.collect();
let quiet = xml::extract_element(&body_str, "Quiet")
.map(|s| s == "true")
.unwrap_or(false);
let mut w = XmlWriter::new();
w.declaration();
w.open_ns("DeleteResult", S3_XMLNS);
for key in &keys {
match share.delete_object(key).await {
Ok(()) => {
if !quiet {
w.open("Deleted");
w.element("Key", key);
w.close("Deleted");
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if !quiet {
w.open("Deleted");
w.element("Key", key);
w.close("Deleted");
}
}
Err(e) => {