ugos-client 0.14.3

Rust client library for the UGREEN NAS (UGOS) API: authentication, KVM virtual machine management, snapshots, networks, storage, and images
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! KVM virtual machine management API.
//!
//! All methods accept display names or UUIDs. Display names are resolved
//! to UUIDs internally via [`KvmApi::vm_list`].

use crate::client::UgosClient;
use crate::error::{Result, UgosError};
use crate::types::common::ResultWrapper;
use crate::types::kvm::{
    HostInfo, ImageInfo, LogPage, NetworkDetail, NetworkSummary, Overview, Snapshot, StorageInfo,
    StorageUsage, UsbDevice, VmDetail, VmSummary, VncLink,
};

/// KVM management operations on a UGOS NAS.
#[allow(clippy::module_name_repetitions)]
pub trait KvmApi {
    // ── VM ──────────────────────────────────────────────────────────

    /// List all virtual machines.
    fn vm_list(&self) -> impl Future<Output = Result<Vec<VmSummary>>> + Send;
    /// Show detailed VM configuration.
    fn vm_show(&self, name: &str) -> impl Future<Output = Result<VmDetail>> + Send;
    /// Power on a VM.
    fn vm_start(&self, name: &str) -> impl Future<Output = Result<()>> + Send;
    /// Shut down a VM (graceful or forced).
    fn vm_stop(&self, name: &str, force: bool) -> impl Future<Output = Result<()>> + Send;
    /// Reboot a VM (graceful or forced).
    fn vm_reboot(&self, name: &str, force: bool) -> impl Future<Output = Result<()>> + Send;
    /// Delete a VM.
    fn vm_delete(&self, name: &str) -> impl Future<Output = Result<()>> + Send;
    /// Create a new VM from a `VmDetail` spec.
    ///
    /// `storage_uuid` is filled in from `storage_name` when empty. The UUID in
    /// `virtual_machine_name` is ignored by UGOS, which assigns its own; the
    /// assigned one is returned, or an empty string if the new VM cannot be
    /// found in the listing afterwards.
    fn vm_create(&self, spec: &VmDetail) -> impl Future<Output = Result<String>> + Send;
    /// Update an existing VM (must be shut off).
    fn vm_update(&self, spec: &VmDetail) -> impl Future<Output = Result<()>> + Send;
    /// Get host hardware info (CPU cores, memory).
    fn host_info(&self) -> impl Future<Output = Result<HostInfo>> + Send;
    /// Get host load and every VM in one call.
    fn overview(&self) -> impl Future<Output = Result<Overview>> + Send;
    /// Check whether a VM display name is already taken.
    fn vm_name_taken(&self, display_name: &str) -> impl Future<Output = Result<bool>> + Send;
    /// Check whether the host can back a given amount of guest memory.
    fn check_memory(&self, bytes: i64) -> impl Future<Output = Result<MemoryStatus>> + Send;

    // ── Snapshot ────────────────────────────────────────────────────

    /// List snapshots for a VM.
    fn snapshot_list(&self, vm: &str) -> impl Future<Output = Result<Vec<Snapshot>>> + Send;
    /// Create a snapshot. UGOS names it and returns that name.
    fn snapshot_create(&self, vm: &str) -> impl Future<Output = Result<String>> + Send;
    /// Delete a snapshot by its internal name.
    fn snapshot_delete(&self, vm: &str, name: &str) -> impl Future<Output = Result<()>> + Send;
    /// Revert to a snapshot, optionally taking one of the current state first.
    fn snapshot_revert(
        &self,
        vm: &str,
        name: &str,
        snapshot_first: bool,
    ) -> impl Future<Output = Result<()>> + Send;
    /// Set a snapshot's description.
    fn snapshot_describe(
        &self,
        vm: &str,
        name: &str,
        description: &str,
    ) -> impl Future<Output = Result<()>> + Send;

    // ── Network ─────────────────────────────────────────────────────

    /// List KVM networks.
    fn network_list(&self) -> impl Future<Output = Result<Vec<NetworkSummary>>> + Send;
    /// Show network details.
    fn network_show(&self, name: &str) -> impl Future<Output = Result<NetworkDetail>> + Send;
    /// Create a KVM network.
    fn network_create(&self, network: &NetworkDetail) -> impl Future<Output = Result<()>> + Send;
    /// Update a KVM network.
    fn network_update(&self, network: &NetworkDetail) -> impl Future<Output = Result<()>> + Send;
    /// Delete a KVM network.
    fn network_delete(&self, name: &str) -> impl Future<Output = Result<()>> + Send;
    /// Check whether a network name is already taken.
    fn network_name_taken(&self, name: &str) -> impl Future<Output = Result<bool>> + Send;
    /// List the VMs attached to a network.
    fn network_check_usage(&self, name: &str) -> impl Future<Output = Result<Vec<String>>> + Send;

    // ── Storage ─────────────────────────────────────────────────────

    /// List storage volumes available to KVM, including how many VMs each holds.
    fn storage_list(&self) -> impl Future<Output = Result<Vec<StorageInfo>>> + Send;
    /// Check which VMs use a storage volume.
    fn storage_check_usage(
        &self,
        name: &str,
        uuid: &str,
    ) -> impl Future<Output = Result<Vec<String>>> + Send;
    /// Add a storage volume to KVM.
    fn storage_add(&self, name: &str, uuid: &str) -> impl Future<Output = Result<()>> + Send;
    /// Remove a storage volume from KVM.
    fn storage_delete(&self, name: &str, uuid: &str) -> impl Future<Output = Result<()>> + Send;
    /// List volume usage, broken down per VM.
    fn storage_usage_list(&self) -> impl Future<Output = Result<Vec<StorageUsage>>> + Send;

    // ── Image ───────────────────────────────────────────────────────

    /// List ISO/disk images.
    fn image_list(&self) -> impl Future<Output = Result<Vec<ImageInfo>>> + Send;
    /// Delete an image.
    fn image_delete(
        &self,
        file_name: &str,
        image_name: &str,
    ) -> impl Future<Output = Result<()>> + Send;
    /// Check which VMs use an image.
    fn image_check_usage(&self, name: &str) -> impl Future<Output = Result<Vec<String>>> + Send;
    /// Check if an image name is available.
    fn image_check_name(&self, name: &str) -> impl Future<Output = Result<bool>> + Send;

    /// Upload an ISO image, sending it in chunks.
    ///
    /// `progress` is called after each chunk with `(finished, total)`. Returns
    /// the file name the image was stored under.
    fn image_upload(
        &self,
        path: &std::path::Path,
        iso_name: &str,
        progress: &(dyn Fn(usize, usize) + Send + Sync),
    ) -> impl Future<Output = Result<String>> + Send;

    // `kvm/image/RenameImage` exists but is deliberately not wrapped: it
    // answers `successful` to every body tried so far and renames nothing.
    // The web UI never calls it either, so the field names are unknown.

    /// Download an ISO from a URL into a temporary file and upload it.
    ///
    /// `progress` reports both phases: while downloading it is called with
    /// `(bytes so far, 0)`, while uploading with `(finished chunk, total
    /// chunks)`. A total of `0` therefore marks the download phase.
    fn image_upload_url(
        &self,
        url: &str,
        iso_name: &str,
        progress: &(dyn Fn(usize, usize) + Send + Sync),
    ) -> impl Future<Output = Result<String>> + Send;

    /// Register an image that already sits on the NAS, without uploading it.
    fn image_register(
        &self,
        path: &str,
        image_name: &str,
        file_name: &str,
    ) -> impl Future<Output = Result<()>> + Send;

    // ── USB / PCI ───────────────────────────────────────────────────

    /// List USB devices for a VM.
    fn usb_list(&self, vm: &str) -> impl Future<Output = Result<Vec<UsbDevice>>> + Send;
    /// List PCI devices available for passthrough.
    fn passthrough_devices(&self) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send;

    // ── VNC ─────────────────────────────────────────────────────────

    /// List VNC links for a VM.
    fn vnc_list(&self, vm: &str) -> impl Future<Output = Result<Vec<VncLink>>> + Send;
    /// Generate a noVNC link for a VM.
    fn vnc_generate(
        &self,
        vm: &str,
        source_url: &str,
    ) -> impl Future<Output = Result<String>> + Send;

    // ── Logs ────────────────────────────────────────────────────────

    /// Search KVM logs.
    fn log_search(&self, page: u32, page_size: u32)
    -> impl Future<Output = Result<LogPage>> + Send;
    /// Get all operator usernames from logs.
    fn log_operators(&self) -> impl Future<Output = Result<Vec<String>>> + Send;

    // ── Session ─────────────────────────────────────────────────────

    /// Send a heartbeat to keep the session alive.
    fn heartbeat(&self) -> impl Future<Output = Result<()>> + Send;

    // ── OVA ─────────────────────────────────────────────────────────

    /// Export a VM as an OVA file.
    fn ova_export(
        &self,
        vm: &str,
        storage_name: &str,
        storage_uuid: &str,
        ova_path: &str,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Parse an OVA file and return the VM configuration it contains.
    fn ova_parse(&self, ova_path: &str) -> impl Future<Output = Result<VmDetail>> + Send;
}

/// How a requested amount of guest memory relates to the host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryStatus {
    /// The host can back it comfortably.
    Fits,
    /// Above what is currently free; UGOS warns but allows it.
    Tight,
    /// More than the host has at all.
    TooMuch,
}

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct MemoryCheck {
    #[serde(default)]
    memory_status: i64,
}

/// Turn a failed create into something a human can act on.
///
/// UGOS answers `3000, Fail to create virtual machine` whatever the cause, so
/// the validators the web UI uses on its form are asked afterwards.
async fn explain_create_failure(
    client: &UgosClient,
    spec: &VmDetail,
    original: UgosError,
) -> UgosError {
    let name = &spec.virtual_machine_display_name;
    if client.vm_name_taken(name).await.unwrap_or(false) {
        return UgosError::OperationFailed(format!("a VM named '{name}' already exists"));
    }
    // memory is KiB in the spec, bytes in the check.
    if matches!(
        client.check_memory(spec.memory.value * 1024).await,
        Ok(MemoryStatus::TooMuch)
    ) {
        return UgosError::OperationFailed(format!(
            "{} MiB of memory is more than this NAS has",
            spec.memory.value / 1024
        ));
    }
    original
}

/// Explain a refused power-on where the code alone says nothing.
async fn explain_start_failure(client: &UgosClient, vm: &str, original: UgosError) -> UgosError {
    let Ok(detail) = client.vm_show(vm).await else {
        return original;
    };
    match client.check_memory(detail.memory.value * 1024).await {
        Ok(MemoryStatus::TooMuch) => UgosError::OperationFailed(format!(
            "{} needs {} MiB, more than this NAS has",
            vm,
            detail.memory.value / 1024
        )),
        Ok(MemoryStatus::Tight) => UgosError::OperationFailed(format!(
            "{original}. {} needs {} MiB, more than is free right now",
            vm,
            detail.memory.value / 1024
        )),
        _ => original,
    }
}

/// Chunk size the web UI uses for image uploads.
const CHUNK_SIZE: u64 = 10 * 1024 * 1024;

/// Find a free image file name, appending `-2`, `-3`, … when taken.
async fn unique_file_name(client: &UgosClient, wanted: &str) -> Result<String> {
    let images: ResultWrapper<Vec<ImageInfo>> = client.get("kvm/image/ShowImageList").await?;
    let taken: Vec<&str> = images.result.iter().map(|i| i.file_name.as_str()).collect();
    if !taken.contains(&wanted) {
        return Ok(wanted.to_owned());
    }
    let (stem, ext) = wanted.rsplit_once('.').unwrap_or((wanted, ""));
    for n in 2..1000 {
        let candidate = if ext.is_empty() {
            format!("{stem}-{n}")
        } else {
            format!("{stem}-{n}.{ext}")
        };
        if !taken.contains(&candidate.as_str()) {
            return Ok(candidate);
        }
    }
    Err(UgosError::Encryption(format!(
        "no free file name for '{wanted}'"
    )))
}

fn ensure_nonempty(size: u64) -> Result<()> {
    if size == 0 {
        return Err(UgosError::Encryption("file is empty".to_owned()));
    }
    Ok(())
}

/// Response of `GenerateSnapshot`, which names the snapshot itself.
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct SnapshotCreated {
    #[serde(default)]
    snapshot_display_name: String,
}

/// Look up a snapshot's display name, which the delete endpoint wants
/// alongside the internal name.
async fn snapshot_display_name(client: &UgosClient, vm: &str, name: &str) -> Result<String> {
    let (uuid, _) = resolve_vm(client, vm).await?;
    let snaps: ResultWrapper<Vec<Snapshot>> = client
        .get_with_params("kvm/manager/ShowListSnapshot", &[("name", uuid.as_str())])
        .await?;
    snaps
        .result
        .iter()
        .find(|s| s.name == name || s.display_name == name)
        .map(|s| s.display_name.clone())
        .ok_or_else(|| UgosError::NotFound {
            kind: "snapshot",
            name: name.to_owned(),
        })
}

// ── Name resolution ─────────────────────────────────────────────────

/// Fill in `storage_uuid` from `storage_name` when the caller left it empty.
///
/// `CreateVirtualMachine` rejects a body without `storageUUID`, and the name
/// is the only part a human can reasonably supply.
async fn resolve_storage_uuid(client: &UgosClient, spec: &mut VmDetail) -> Result<()> {
    if !spec.storage_uuid.is_empty() {
        return Ok(());
    }
    let volumes: ResultWrapper<Vec<StorageInfo>> =
        client.get("kvm/storage/ShowStorageList").await?;
    let volume = volumes
        .result
        .iter()
        .find(|v| v.name == spec.storage_name || v.label == spec.storage_name)
        .ok_or_else(|| UgosError::NotFound {
            kind: "storage volume",
            name: spec.storage_name.clone(),
        })?;
    spec.storage_uuid.clone_from(&volume.uuid);
    volume.name.clone_into(&mut spec.storage_name);
    Ok(())
}

async fn resolve_vm(client: &UgosClient, name: &str) -> Result<(String, String)> {
    let vms: ResultWrapper<Vec<VmSummary>> = client.get("kvm/manager/ShowLocalVirtualList").await?;
    let vm = vms
        .result
        .iter()
        .find(|v| v.vir_name == name || v.vir_display_name.eq_ignore_ascii_case(name))
        .ok_or_else(|| UgosError::NotFound {
            kind: "VM",
            name: name.to_owned(),
        })?;
    Ok((vm.vir_name.clone(), vm.vir_display_name.clone()))
}

// ── Implementation ──────────────────────────────────────────────────

impl KvmApi for UgosClient {
    // ── VM ──────────────────────────────────────────────────────────

    async fn vm_list(&self) -> Result<Vec<VmSummary>> {
        let resp: ResultWrapper<Vec<VmSummary>> =
            self.get("kvm/manager/ShowLocalVirtualList").await?;
        Ok(resp.result)
    }

    async fn vm_show(&self, name: &str) -> Result<VmDetail> {
        let (uuid, _) = resolve_vm(self, name).await?;
        self.get_with_params("kvm/manager/ShowLocalVirtualMachine", &[("name", &uuid)])
            .await
    }

    async fn vm_start(&self, name: &str) -> Result<()> {
        let (uuid, display) = resolve_vm(self, name).await?;
        let started: Result<ResultWrapper<String>> = self
            .get_with_params(
                "kvm/manager/PowerOn",
                &[
                    ("name", uuid.as_str()),
                    ("virtualMachineDisplayName", display.as_str()),
                ],
            )
            .await;
        if let Err(e) = started {
            return Err(explain_start_failure(self, name, e).await);
        }
        Ok(())
    }

    async fn vm_stop(&self, name: &str, force: bool) -> Result<()> {
        let (uuid, display) = resolve_vm(self, name).await?;
        let endpoint = if force {
            "kvm/manager/ForcedShutdown"
        } else {
            "kvm/manager/Shutdown"
        };
        let _: ResultWrapper<String> = self
            .get_with_params(
                endpoint,
                &[
                    ("name", uuid.as_str()),
                    ("virtualMachineDisplayName", display.as_str()),
                ],
            )
            .await?;
        Ok(())
    }

    async fn vm_reboot(&self, name: &str, force: bool) -> Result<()> {
        let (uuid, display) = resolve_vm(self, name).await?;
        if force {
            let _: ResultWrapper<String> = self
                .get_with_params(
                    "kvm/manager/ForcedRestart",
                    &[
                        ("name", uuid.as_str()),
                        ("virtualMachineDisplayName", display.as_str()),
                    ],
                )
                .await?;
        } else {
            let _: ResultWrapper<String> = self
                .get_with_params("kvm/manager/Reboot", &[("name", uuid.as_str())])
                .await?;
        }
        Ok(())
    }

    async fn vm_delete(&self, name: &str) -> Result<()> {
        let (uuid, display) = resolve_vm(self, name).await?;
        let _: ResultWrapper<String> = self
            .get_with_params(
                "kvm/manager/DeleteVirtualMachine",
                &[
                    ("name", uuid.as_str()),
                    ("virtualMachineDisplayName", display.as_str()),
                ],
            )
            .await?;
        Ok(())
    }

    async fn vm_create(&self, spec: &VmDetail) -> Result<String> {
        let mut spec = spec.clone();
        resolve_storage_uuid(self, &mut spec).await?;
        let created: Result<ResultWrapper<String>> =
            self.post("kvm/manager/CreateVirtualMachine", &spec).await;
        if let Err(e) = created {
            return Err(explain_create_failure(self, &spec, e).await);
        }

        // UGOS assigns the UUID itself and ignores whatever the body carried,
        // so the only way to learn it is to look the VM up again.
        let vms: ResultWrapper<Vec<VmSummary>> =
            self.get("kvm/manager/ShowLocalVirtualList").await?;
        Ok(vms
            .result
            .iter()
            .filter(|v| v.vir_display_name == spec.virtual_machine_display_name)
            .max_by_key(|v| v.create_time)
            .map(|v| v.vir_name.clone())
            .unwrap_or_default())
    }

    async fn vm_update(&self, spec: &VmDetail) -> Result<()> {
        let mut spec = spec.clone();
        resolve_storage_uuid(self, &mut spec).await?;
        let _: ResultWrapper<String> = self.post("kvm/manager/UpdateVirtualMachine", &spec).await?;
        Ok(())
    }

    async fn host_info(&self) -> Result<HostInfo> {
        self.get("kvm/manager/ShowNativeInfo").await
    }

    async fn overview(&self) -> Result<Overview> {
        self.get("kvm/manager/ShowOverview").await
    }

    async fn vm_name_taken(&self, display_name: &str) -> Result<bool> {
        // `result: true` means the name is in use, not that it is free.
        let body = serde_json::json!({"name": "", "virtualMachineDisplayName": display_name});
        let resp: ResultWrapper<bool> = self.post("kvm/manager/CheckVirName", &body).await?;
        Ok(resp.result)
    }

    async fn check_memory(&self, bytes: i64) -> Result<MemoryStatus> {
        let resp: MemoryCheck = self
            .get_with_params(
                "kvm/manager/CheckResource",
                &[("memory", &bytes.to_string())],
            )
            .await?;
        Ok(match resp.memory_status {
            0 => MemoryStatus::Fits,
            1 => MemoryStatus::Tight,
            _ => MemoryStatus::TooMuch,
        })
    }

    // ── Snapshot ────────────────────────────────────────────────────

    async fn snapshot_list(&self, vm: &str) -> Result<Vec<Snapshot>> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let resp: ResultWrapper<Vec<Snapshot>> = self
            .get_with_params("kvm/manager/ShowListSnapshot", &[("name", uuid.as_str())])
            .await?;
        Ok(resp.result)
    }

    async fn snapshot_create(&self, vm: &str) -> Result<String> {
        // `name` is the VM's UUID here, not a snapshot name: UGOS picks the
        // snapshot name itself and reports it back.
        let (uuid, display) = resolve_vm(self, vm).await?;
        let resp: SnapshotCreated = self
            .get_with_params(
                "kvm/manager/GenerateSnapshot",
                &[
                    ("name", uuid.as_str()),
                    ("virtualMachineDisplayName", display.as_str()),
                ],
            )
            .await?;
        Ok(resp.snapshot_display_name)
    }

    async fn snapshot_delete(&self, vm: &str, name: &str) -> Result<()> {
        // Both parameters describe the snapshot; the display name comes from
        // the listing.
        let display = snapshot_display_name(self, vm, name).await?;
        let _: ResultWrapper<String> = self
            .get_with_params(
                "kvm/manager/DeleteSnapshot",
                &[
                    ("name", name),
                    ("virtualMachineDisplayName", display.as_str()),
                ],
            )
            .await?;
        Ok(())
    }

    async fn snapshot_revert(&self, vm: &str, name: &str, snapshot_first: bool) -> Result<()> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let _: ResultWrapper<String> = self
            .get_with_params(
                "kvm/manager/RevertSnapshot",
                &[
                    ("virtualMachineName", uuid.as_str()),
                    ("snapshotName", name),
                    (
                        "createSnapshot",
                        if snapshot_first { "true" } else { "false" },
                    ),
                ],
            )
            .await?;
        Ok(())
    }

    async fn snapshot_describe(&self, vm: &str, name: &str, description: &str) -> Result<()> {
        let _ = snapshot_display_name(self, vm, name).await?;
        let body = serde_json::json!({"name": name, "description": description});
        let _: ResultWrapper<String> = self.post("kvm/manager/EditSnapshot", &body).await?;
        Ok(())
    }

    // ── Network ─────────────────────────────────────────────────────

    async fn network_list(&self) -> Result<Vec<NetworkSummary>> {
        let resp: ResultWrapper<Vec<NetworkSummary>> =
            self.get("kvm/network/ShowNetworkList").await?;
        Ok(resp.result)
    }

    async fn network_show(&self, name: &str) -> Result<NetworkDetail> {
        let resp: ResultWrapper<NetworkDetail> = self
            .get_with_params("kvm/network/GetNetworkByName", &[("name", name)])
            .await?;
        Ok(resp.result)
    }

    async fn network_create(&self, network: &NetworkDetail) -> Result<()> {
        let created: Result<ResultWrapper<String>> =
            self.post("kvm/network/CreateNetwork", network).await;
        if let Err(e) = created {
            if self
                .network_name_taken(&network.network_name)
                .await
                .unwrap_or(false)
            {
                return Err(UgosError::OperationFailed(format!(
                    "a network named '{}' already exists",
                    network.network_name
                )));
            }
            return Err(e);
        }
        Ok(())
    }

    async fn network_update(&self, network: &NetworkDetail) -> Result<()> {
        let _: ResultWrapper<String> = self.post("kvm/network/UpdateNetwork", network).await?;
        Ok(())
    }

    async fn network_name_taken(&self, name: &str) -> Result<bool> {
        let body = serde_json::json!({"name": name});
        let resp: ResultWrapper<bool> = self.post("kvm/network/CheckName", &body).await?;
        Ok(resp.result)
    }

    async fn network_check_usage(&self, name: &str) -> Result<Vec<String>> {
        let resp: ResultWrapper<Vec<String>> = self
            .get_with_params("kvm/network/CheckNetwork", &[("name", name)])
            .await?;
        Ok(resp.result)
    }

    async fn network_delete(&self, name: &str) -> Result<()> {
        let deleted: Result<ResultWrapper<String>> = self
            .get_with_params("kvm/network/DeleteNetwork", &[("name", name)])
            .await;
        if let Err(e) = deleted {
            if let Ok(vms) = self.network_check_usage(name).await
                && !vms.is_empty()
            {
                return Err(UgosError::OperationFailed(format!(
                    "network '{name}' is still attached to: {}",
                    vms.join(", ")
                )));
            }
            return Err(e);
        }
        Ok(())
    }

    // ── Storage ─────────────────────────────────────────────────────

    async fn storage_list(&self) -> Result<Vec<StorageInfo>> {
        // ShowLocalStorageList over ShowStorageList: same volumes and fields,
        // plus virCount.
        let resp: ResultWrapper<Vec<StorageInfo>> =
            self.get("kvm/storage/ShowLocalStorageList").await?;
        Ok(resp.result)
    }

    async fn storage_check_usage(&self, name: &str, uuid: &str) -> Result<Vec<String>> {
        let resp: ResultWrapper<Vec<String>> = self
            .get_with_params(
                "kvm/storage/CheckStorage",
                &[("name", name), ("uuid", uuid)],
            )
            .await?;
        Ok(resp.result)
    }

    async fn storage_add(&self, name: &str, uuid: &str) -> Result<()> {
        let body = serde_json::json!({"storageName": name, "storageUUID": uuid});
        let _: ResultWrapper<String> = self.post("kvm/storage/AddStorage", &body).await?;
        Ok(())
    }

    async fn storage_delete(&self, name: &str, uuid: &str) -> Result<()> {
        let _: ResultWrapper<String> = self
            .get_with_params(
                "kvm/storage/DeleteStorage",
                &[("name", name), ("uuid", uuid)],
            )
            .await?;
        Ok(())
    }

    async fn storage_usage_list(&self) -> Result<Vec<StorageUsage>> {
        let resp: ResultWrapper<Vec<StorageUsage>> =
            self.get("kvm/storage/ShowLocalStorageUsageList").await?;
        Ok(resp.result)
    }

    // ── Image ───────────────────────────────────────────────────────

    async fn image_list(&self) -> Result<Vec<ImageInfo>> {
        let resp: ResultWrapper<Vec<ImageInfo>> = self.get("kvm/image/ShowImageList").await?;
        Ok(resp.result)
    }

    async fn image_delete(&self, file_name: &str, image_name: &str) -> Result<()> {
        let _: ResultWrapper<String> = self
            .get_with_params(
                "kvm/image/DeleteImage",
                &[("fileName", file_name), ("imageName", image_name)],
            )
            .await?;
        Ok(())
    }

    async fn image_check_usage(&self, name: &str) -> Result<Vec<String>> {
        let resp: ResultWrapper<Vec<String>> = self
            .get_with_params("kvm/image/CheckImageUsage", &[("name", name)])
            .await?;
        Ok(resp.result)
    }

    async fn image_check_name(&self, name: &str) -> Result<bool> {
        let resp: ResultWrapper<bool> = self
            .get_with_params("kvm/image/CheckImageName", &[("name", name)])
            .await?;
        Ok(resp.result)
    }

    async fn image_upload(
        &self,
        path: &std::path::Path,
        iso_name: &str,
        progress: &(dyn Fn(usize, usize) + Send + Sync),
    ) -> Result<String> {
        use std::io::Read;

        let wanted = path.file_name().map_or_else(
            || format!("{iso_name}.iso"),
            |n| n.to_string_lossy().into_owned(),
        );
        // UGOS answers 9999 when the file name is taken, which is why the web
        // UI uses random names. A suffix keeps the name readable instead.
        let file_name = unique_file_name(self, &wanted).await?;

        let mut file = std::fs::File::open(path)
            .map_err(|e| UgosError::io(format!("opening '{}'", path.display()), e))?;
        let size = file
            .metadata()
            .map_err(|e| UgosError::io("reading file size", e))?
            .len();
        ensure_nonempty(size)?;

        // The web UI splits uploads into 10 MiB parts and numbers them from 0.
        let total = usize::try_from(size.div_ceil(CHUNK_SIZE))
            .map_err(|_| UgosError::Encryption("file too large to chunk".to_owned()))?;
        let chunk_len = usize::try_from(CHUNK_SIZE)
            .map_err(|_| UgosError::Encryption("chunk size unsupported here".to_owned()))?;
        let mut buf = vec![0u8; chunk_len];

        for index in 0..total {
            let mut filled = 0;
            while filled < buf.len() {
                let n = file
                    .read(&mut buf[filled..])
                    .map_err(|e| UgosError::io(format!("reading chunk {index}"), e))?;
                if n == 0 {
                    break;
                }
                filled += n;
            }

            let part = reqwest::multipart::Part::bytes(buf[..filled].to_vec())
                .file_name("blob")
                .mime_str("application/octet-stream")
                .map_err(|e| UgosError::Encryption(format!("building chunk: {e}")))?;
            let form = reqwest::multipart::Form::new()
                .text("isoName", iso_name.to_owned())
                .text("fileName", file_name.clone())
                .text("size", size.to_string())
                .text("chunks", total.to_string())
                .text("chunk", index.to_string())
                .part("file", part);

            let _: ResultWrapper<String> = self.post_multipart("kvm/image/UploadUpk", form).await?;
            progress(index + 1, total);
        }

        Ok(file_name)
    }

    async fn image_upload_url(
        &self,
        url: &str,
        iso_name: &str,
        progress: &(dyn Fn(usize, usize) + Send + Sync),
    ) -> Result<String> {
        use std::io::Write;

        let file_name = safe_download_name(url, iso_name);
        let (scratch, temp) = create_scratch_file(&file_name)?;

        // A separate client: the authenticated one carries NAS cookies and
        // trusts invalid certificates, neither of which belongs on a download
        // from an arbitrary host.
        let plain = reqwest::Client::builder()
            .build()
            .map_err(|e| UgosError::Encryption(format!("HTTP client build: {e}")))?;
        let mut resp = plain.get(url).send().await?.error_for_status()?;

        let mut out = std::fs::File::create(&temp)
            .map_err(|e| UgosError::io(format!("creating '{}'", temp.display()), e))?;
        let mut downloaded = 0usize;
        while let Some(chunk) = resp.chunk().await? {
            out.write_all(&chunk)
                .map_err(|e| UgosError::io("writing download", e))?;
            downloaded += chunk.len();
            progress(downloaded, 0);
        }
        drop(out);

        let result = self.image_upload(&temp, iso_name, progress).await;
        let _ = std::fs::remove_file(&temp);
        let _ = std::fs::remove_dir(&scratch);
        result
    }

    async fn image_register(&self, path: &str, image_name: &str, file_name: &str) -> Result<()> {
        let body = serde_json::json!({
            "path": path,
            "imageName": image_name,
            "fileName": file_name,
        });
        let _: ResultWrapper<String> = self.post("kvm/image/UploadPath", &body).await?;
        Ok(())
    }

    // ── USB / PCI ───────────────────────────────────────────────────

    async fn passthrough_devices(&self) -> Result<Vec<serde_json::Value>> {
        let resp: ResultWrapper<Vec<serde_json::Value>> =
            self.get("kvm/passthrough/devices").await?;
        Ok(resp.result)
    }

    async fn usb_list(&self, vm: &str) -> Result<Vec<UsbDevice>> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let resp: ResultWrapper<Vec<UsbDevice>> = self
            .get_with_params("kvm/usb/USBList", &[("vmName", uuid.as_str())])
            .await?;
        Ok(resp.result)
    }

    // ── VNC ─────────────────────────────────────────────────────────

    async fn vnc_list(&self, vm: &str) -> Result<Vec<VncLink>> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let resp: ResultWrapper<Vec<VncLink>> = self
            .get_with_params("kvm/vnc/ListAllLink", &[("virName", uuid.as_str())])
            .await?;
        Ok(resp.result)
    }

    async fn vnc_generate(&self, vm: &str, source_url: &str) -> Result<String> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let body = serde_json::json!({"virName": uuid, "type": 0, "sourceUrl": source_url});
        let resp: ResultWrapper<String> = self.post("kvm/vnc/GenerateNoVNClink", &body).await?;
        Ok(resp.result)
    }

    // ── Logs ────────────────────────────────────────────────────────

    async fn log_search(&self, page: u32, page_size: u32) -> Result<LogPage> {
        let body = serde_json::json!({
            "pageNum": page,
            "pageSize": page_size,
            "operator": "",
            "startTime": "",
            "endTime": "",
            "createTimeSort": "desc",
            "operatorSort": ""
        });
        self.post("kvm/logs/PageSearchLogs", &body).await
    }

    async fn log_operators(&self) -> Result<Vec<String>> {
        let resp: ResultWrapper<Vec<String>> = self.get("kvm/logs/GetAllOperator").await?;
        Ok(resp.result)
    }

    // ── Session ─────────────────────────────────────────────────────

    async fn heartbeat(&self) -> Result<()> {
        let _: serde_json::Value = self.get("verify/heartbeat").await?;
        Ok(())
    }

    // ── OVA ─────────────────────────────────────────────────────────

    async fn ova_export(
        &self,
        vm: &str,
        storage_name: &str,
        storage_uuid: &str,
        ova_path: &str,
    ) -> Result<()> {
        let (uuid, _) = resolve_vm(self, vm).await?;
        let body = serde_json::json!({
            "virtualName": uuid,
            "storageName": storage_name,
            "storageUUID": storage_uuid,
            "ovaPath": ova_path,
        });
        let _: ResultWrapper<String> = self.post("kvm/manager/ExportOVA", &body).await?;
        Ok(())
    }

    async fn ova_parse(&self, ova_path: &str) -> Result<VmDetail> {
        let body = serde_json::json!({"ovaPath": ova_path});
        self.post("kvm/manager/ParseOvaFile", &body).await
    }
}

/// Derive a safe local file name for a download.
///
/// The name comes from a URL, so it must not be trusted as a path: a
/// segment of `..`, an absolute path, or an embedded separator would place
/// the download somewhere unintended. Anything that is not a plain file name
/// falls back to the caller's chosen ISO name.
fn safe_download_name(url: &str, iso_name: &str) -> String {
    let fallback = || format!("{iso_name}.iso");
    let candidate = url
        .rsplit('/')
        .next()
        .map(|n| n.split(['?', '#']).next().unwrap_or(n))
        .unwrap_or_default();

    let rejected = candidate.is_empty()
        || candidate == "."
        || candidate == ".."
        || candidate.contains('/')
        || candidate.contains('\\')
        || candidate.contains('\0');

    if rejected {
        return fallback();
    }
    // A leading dot would create a hidden file; harmless, but not what the
    // caller asked for either.
    if candidate.starts_with('.') {
        return fallback();
    }
    candidate.to_owned()
}

/// Create a private directory under the temp dir and a fresh file inside it.
///
/// A download must not land on a predictable path in a world-writable
/// directory: on a shared machine another user can place a symlink there in
/// advance and have the write follow it. The directory name therefore
/// includes the process id and a monotonic component, it is created with
/// `create_dir` so an existing one is an error rather than reuse, and the
/// file itself is opened with `create_new` so an existing entry — symlink
/// included — fails instead of being written through.
///
/// Returns the directory and the file path; the caller removes both.
/// Create a directory that is private from the moment it exists.
///
/// `create_dir` followed by a `chmod` leaves a window in which the directory
/// carries the umask default, and the chmod can fail without anyone noticing.
/// The mode belongs in the creating call.
fn new_private_dir(path: &std::path::Path) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        std::fs::DirBuilder::new().mode(0o700).create(path)
    }
    #[cfg(not(unix))]
    {
        std::fs::DirBuilder::new().create(path)
    }
}

fn create_scratch_file(file_name: &str) -> Result<(std::path::PathBuf, std::path::PathBuf)> {
    use std::sync::atomic::{AtomicU64, Ordering};
    // The clock alone is not enough: two calls can land in the same tick, and
    // create_dir then fails on the second. A counter makes the name unique
    // within the process, and the retry covers the rest.
    static SEQUENCE: AtomicU64 = AtomicU64::new(0);

    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());

    let mut last = None;
    let mut dir = std::path::PathBuf::new();
    for _ in 0..16 {
        let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let candidate =
            std::env::temp_dir().join(format!("ugos-cli-{}-{stamp}-{seq}", std::process::id()));
        match new_private_dir(&candidate) {
            Ok(()) => {
                dir = candidate;
                last = None;
                break;
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                last = Some(e);
            }
            Err(e) => {
                return Err(UgosError::Encryption(format!(
                    "creating '{}': {e}",
                    candidate.display()
                )));
            }
        }
    }
    if let Some(e) = last {
        return Err(UgosError::Encryption(format!(
            "no free scratch directory under '{}': {e}",
            std::env::temp_dir().display()
        )));
    }

    let path = dir.join(file_name);
    // Prove the path is fresh before anything is written to it. The handle
    // is dropped straight away; the caller opens the file for the download.
    let probe = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .map_err(|e| UgosError::io(format!("creating '{}'", path.display()), e))?;
    drop(probe);

    Ok((dir, path))
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod scratch_tests {
    use super::create_scratch_file;

    #[test]
    fn creates_the_file_and_hands_back_both_paths() {
        let (dir, file) = create_scratch_file("debian.iso").unwrap();
        assert!(dir.is_dir(), "directory missing");
        assert!(file.is_file(), "file missing");
        assert_eq!(
            file.file_name().and_then(|n| n.to_str()),
            Some("debian.iso")
        );
        assert_eq!(file.parent(), Some(dir.as_path()));
        let _ = std::fs::remove_file(&file);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn two_calls_never_share_a_directory() {
        let (d1, f1) = create_scratch_file("same.iso").unwrap();
        let (d2, f2) = create_scratch_file("same.iso").unwrap();
        assert_ne!(d1, d2, "scratch directories collided");
        assert_ne!(f1, f2);
        for (d, f) in [(d1, f1), (d2, f2)] {
            let _ = std::fs::remove_file(&f);
            let _ = std::fs::remove_dir(&d);
        }
    }

    #[cfg(unix)]
    #[test]
    fn the_directory_is_private_to_the_user() {
        use std::os::unix::fs::PermissionsExt;
        let (dir, file) = create_scratch_file("x.iso").unwrap();
        let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "group or other can reach the download");
        let _ = std::fs::remove_file(&file);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn refuses_a_path_that_already_exists() {
        // Stands in for the symlink an attacker would plant: create_new must
        // fail rather than write through anything already at the path.
        let (dir, file) = create_scratch_file("taken.iso").unwrap();
        let second = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&file);
        assert!(second.is_err(), "an existing path was reopened");
        let _ = std::fs::remove_file(&file);
        let _ = std::fs::remove_dir(&dir);
    }
}

#[cfg(test)]
mod download_name_tests {
    use super::safe_download_name;

    #[test]
    fn takes_the_last_path_segment() {
        assert_eq!(
            safe_download_name("https://example.org/iso/debian.iso", "fallback"),
            "debian.iso"
        );
    }

    #[test]
    fn strips_a_query_string() {
        assert_eq!(
            safe_download_name("https://example.org/debian.iso?token=x", "fallback"),
            "debian.iso"
        );
    }

    #[test]
    fn rejects_traversal_segments() {
        assert_eq!(safe_download_name("https://example.org/..", "fb"), "fb.iso");
        assert_eq!(safe_download_name("https://example.org/.", "fb"), "fb.iso");
    }

    #[test]
    fn rejects_an_empty_segment() {
        assert_eq!(safe_download_name("https://example.org/", "fb"), "fb.iso");
    }

    #[test]
    fn rejects_hidden_names() {
        assert_eq!(
            safe_download_name("https://example.org/.bashrc", "fb"),
            "fb.iso"
        );
    }

    #[test]
    fn rejects_embedded_separators() {
        // Percent-decoding is not applied, but a raw separator must not pass.
        assert_eq!(
            safe_download_name("https://example.org/a\\b.iso", "fb"),
            "fb.iso"
        );
    }
}