-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathsession.rs
More file actions
2171 lines (1924 loc) · 88.1 KB
/
Copy pathsession.rs
File metadata and controls
2171 lines (1924 loc) · 88.1 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
use core::cell::RefCell;
use core::net::{Ipv4Addr, SocketAddrV4};
use core::num::NonZeroU32;
use core::time::Duration;
use std::borrow::Cow;
use std::rc::Rc;
use anyhow::Context as _;
use base64::Engine as _;
use futures_channel::mpsc;
use futures_util::io::{ReadHalf, WriteHalf};
use futures_util::{AsyncWriteExt as _, FutureExt as _, StreamExt as _, select};
use gloo_net::websocket;
use gloo_net::websocket::futures::WebSocket;
use gloo_timers::future::IntervalStream;
use iron_remote_desktop::{CursorStyle, DesktopSize, Extension, IronErrorKind};
use ironrdp::cliprdr::CliprdrClient;
use ironrdp::cliprdr::backend::ClipboardMessage;
use ironrdp::cliprdr::pdu::{FileContentsFlags, FileContentsRequest, FileContentsResponse, FileDescriptor};
use ironrdp::connector::connection_activation::ConnectionActivationState;
use ironrdp::connector::credssp::KerberosConfig;
use ironrdp::connector::{self, ClientConnector, Credentials};
use ironrdp::displaycontrol::client::DisplayControlClient;
use ironrdp::dvc::DrdynvcClient;
use ironrdp::graphics::image_processing::PixelFormat;
use ironrdp::pdu::input::fast_path::FastPathInputEvent;
use ironrdp::pdu::rdp::capability_sets::client_codecs_capabilities;
use ironrdp::pdu::rdp::client_info::{PerformanceFlags, TimezoneInfo};
use ironrdp::rdpdr::Rdpdr;
use ironrdp::rdpdr::pdu::efs::{DEFAULT_PRINTER_DRIVER_NAME, MICROSOFT_PRINT_TO_PDF_DRIVER_NAME};
use ironrdp::rdpsnd::client::{NoopRdpsndBackend, Rdpsnd};
use ironrdp::session::image::DecodedImage;
use ironrdp::session::{ActiveStage, ActiveStageOutput, GracefulDisconnectReason, fast_path};
use ironrdp_core::WriteBuf;
use ironrdp_futures::{FramedWrite, single_sequence_step_read};
use rgb::AsPixels as _;
use tap::prelude::*;
use tracing::{debug, error, info, trace, warn};
use wasm_bindgen::{JsCast as _, JsValue};
use wasm_bindgen_futures::spawn_local;
use web_sys::HtmlCanvasElement;
use crate::canvas::Canvas;
use crate::clipboard;
use crate::clipboard::{ClipboardData, FileMetadata, WasmClipboard, WasmClipboardBackend, WasmClipboardBackendMessage};
use crate::error::IronError;
use crate::image::extract_partial_image;
use crate::input::InputTransaction;
use crate::network_client::WasmNetworkClient;
use crate::printer::{JsPrinterStreamCallbacks, WasmPrinter, WasmPrinterBackend, wasm_printer_pair};
const DEFAULT_WIDTH: u16 = 1280;
const DEFAULT_HEIGHT: u16 = 720;
#[derive(Clone, Default)]
pub(crate) struct SessionBuilder(Rc<RefCell<SessionBuilderInner>>);
struct SessionBuilderInner {
username: Option<String>,
destination: Option<String>,
server_domain: Option<String>,
password: Option<String>,
proxy_address: Option<String>,
auth_token: Option<String>,
pcb: Option<String>,
kdc_proxy_url: Option<String>,
client_name: String,
desktop_size: DesktopSize,
render_canvas: Option<HtmlCanvasElement>,
set_cursor_style_callback: Option<js_sys::Function>,
set_cursor_style_callback_context: Option<JsValue>,
remote_clipboard_changed_callback: Option<js_sys::Function>,
force_clipboard_update_callback: Option<js_sys::Function>,
// File transfer callbacks
files_available_callback: Option<js_sys::Function>,
file_contents_request_callback: Option<js_sys::Function>,
file_contents_response_callback: Option<js_sys::Function>,
lock_callback: Option<js_sys::Function>,
unlock_callback: Option<js_sys::Function>,
locks_expired_callback: Option<js_sys::Function>,
// Setting printer stream callbacks activates the virtual printer.
invalid_print_job_stream_callbacks: bool,
print_job_stream_callbacks: Option<JsPrinterStreamCallbacks>,
printer_name: Option<String>,
printer_device_id: Option<u32>,
printer_driver_name: Option<String>,
use_display_control: bool,
enable_credssp: bool,
outbound_message_size_limit: Option<usize>,
}
impl Default for SessionBuilderInner {
fn default() -> Self {
Self {
username: None,
destination: None,
server_domain: None,
password: None,
proxy_address: None,
auth_token: None,
pcb: None,
kdc_proxy_url: None,
client_name: "ironrdp-web".to_owned(),
desktop_size: DesktopSize {
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
},
render_canvas: None,
set_cursor_style_callback: None,
set_cursor_style_callback_context: None,
remote_clipboard_changed_callback: None,
force_clipboard_update_callback: None,
files_available_callback: None,
file_contents_request_callback: None,
file_contents_response_callback: None,
lock_callback: None,
unlock_callback: None,
locks_expired_callback: None,
invalid_print_job_stream_callbacks: false,
print_job_stream_callbacks: None,
printer_name: None,
printer_device_id: None,
printer_driver_name: None,
use_display_control: false,
enable_credssp: true,
outbound_message_size_limit: None,
}
}
}
impl iron_remote_desktop::SessionBuilder for SessionBuilder {
type Session = Session;
type Error = IronError;
fn create() -> Self {
Self(Rc::new(RefCell::new(SessionBuilderInner::default())))
}
/// Required
fn username(&self, username: String) -> Self {
self.0.borrow_mut().username = Some(username);
self.clone()
}
/// Required
fn destination(&self, destination: String) -> Self {
self.0.borrow_mut().destination = Some(destination);
self.clone()
}
/// Optional
fn server_domain(&self, server_domain: String) -> Self {
self.0.borrow_mut().server_domain = if server_domain.is_empty() {
None
} else {
Some(server_domain)
};
self.clone()
}
/// Required
fn password(&self, password: String) -> Self {
self.0.borrow_mut().password = Some(password);
self.clone()
}
/// Required
fn proxy_address(&self, address: String) -> Self {
self.0.borrow_mut().proxy_address = Some(address);
self.clone()
}
/// Required
fn auth_token(&self, token: String) -> Self {
self.0.borrow_mut().auth_token = Some(token);
self.clone()
}
/// Optional
fn desktop_size(&self, desktop_size: DesktopSize) -> Self {
self.0.borrow_mut().desktop_size = desktop_size;
self.clone()
}
/// Optional
fn render_canvas(&self, canvas: HtmlCanvasElement) -> Self {
self.0.borrow_mut().render_canvas = Some(canvas);
self.clone()
}
/// Required.
///
/// # Callback signature:
/// ```typescript
/// function callback(
/// cursor_kind: string,
/// cursor_data: string | undefined,
/// hotspot_x: number | undefined,
/// hotspot_y: number | undefined
/// ): void
/// ```
///
/// # Cursor kinds:
/// - `default` (default system cursor); other arguments are `UNDEFINED`
/// - `none` (hide cursor); other arguments are `UNDEFINED`
/// - `url` (custom cursor data URL); `cursor_data` contains the data URL with Base64-encoded
/// cursor bitmap; `hotspot_x` and `hotspot_y` are set to the cursor hotspot coordinates.
fn set_cursor_style_callback(&self, callback: js_sys::Function) -> Self {
self.0.borrow_mut().set_cursor_style_callback = Some(callback);
self.clone()
}
/// Required.
fn set_cursor_style_callback_context(&self, context: JsValue) -> Self {
self.0.borrow_mut().set_cursor_style_callback_context = Some(context);
self.clone()
}
/// Optional
fn remote_clipboard_changed_callback(&self, callback: js_sys::Function) -> Self {
self.0.borrow_mut().remote_clipboard_changed_callback = Some(callback);
self.clone()
}
/// Optional
fn force_clipboard_update_callback(&self, callback: js_sys::Function) -> Self {
self.0.borrow_mut().force_clipboard_update_callback = Some(callback);
self.clone()
}
/// Because the server does not resize the framebuffer in the RDP protocol, this feature is unused in IronRDP.
fn canvas_resized_callback(&self, _callback: js_sys::Function) -> Self {
self.clone()
}
fn extension(&self, ext: Extension) -> Self {
iron_remote_desktop::extension_match! {
match ext;
|pcb: String| { self.0.borrow_mut().pcb = Some(pcb) };
|kdc_proxy_url: String| { self.0.borrow_mut().kdc_proxy_url = Some(kdc_proxy_url) };
|display_control: bool| { self.0.borrow_mut().use_display_control = display_control };
|enable_credssp: bool| { self.0.borrow_mut().enable_credssp = enable_credssp };
|outbound_message_size_limit: f64| {
let limit = if outbound_message_size_limit >= 0.0 && outbound_message_size_limit <= f64::from(u32::MAX) {
#[expect(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)]
{ outbound_message_size_limit as usize }
} else {
warn!(outbound_message_size_limit, "Invalid outbound message size limit; fallback to unlimited");
0 // Fallback to no limit for invalid values.
};
self.0.borrow_mut().outbound_message_size_limit = if limit > 0 { Some(limit) } else { None };
};
// File transfer callbacks - protocol-specific, routed through extension()
// rather than dedicated trait methods to keep iron-remote-desktop protocol-agnostic.
|files_available_callback: JsValue| {
self.0.borrow_mut().files_available_callback = files_available_callback.dyn_into::<js_sys::Function>().ok();
};
|file_contents_request_callback: JsValue| {
self.0.borrow_mut().file_contents_request_callback = file_contents_request_callback.dyn_into::<js_sys::Function>().ok();
};
|file_contents_response_callback: JsValue| {
self.0.borrow_mut().file_contents_response_callback = file_contents_response_callback.dyn_into::<js_sys::Function>().ok();
};
|lock_callback: JsValue| {
self.0.borrow_mut().lock_callback = lock_callback.dyn_into::<js_sys::Function>().ok();
};
|unlock_callback: JsValue| {
self.0.borrow_mut().unlock_callback = unlock_callback.dyn_into::<js_sys::Function>().ok();
};
|locks_expired_callback: JsValue| {
self.0.borrow_mut().locks_expired_callback = locks_expired_callback.dyn_into::<js_sys::Function>().ok();
};
|print_job_stream_callbacks: JsValue| {
let mut inner = self.0.borrow_mut();
match parse_print_job_stream_callbacks(print_job_stream_callbacks) {
Ok(callbacks) => {
inner.invalid_print_job_stream_callbacks = false;
inner.print_job_stream_callbacks = Some(callbacks);
}
Err(error) => {
inner.invalid_print_job_stream_callbacks = true;
inner.print_job_stream_callbacks = None;
warn!(%error, "Invalid print_job_stream_callbacks; printer streaming requires onJobData and onJobComplete functions");
}
}
};
|printer_name: String| {
let mut inner = self.0.borrow_mut();
inner.printer_name = if printer_name.is_empty() { None } else { Some(printer_name) };
};
|printer_device_id: f64| {
let id = if printer_device_id >= 0.0 && printer_device_id <= f64::from(u32::MAX) {
#[expect(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)]
{ printer_device_id as u32 }
} else {
warn!(printer_device_id, "Invalid printer_device_id; falling back to default");
0
};
let mut inner = self.0.borrow_mut();
inner.printer_device_id = if id > 0 { Some(id) } else { None };
};
|printer_driver_name: String| {
let mut inner = self.0.borrow_mut();
inner.printer_driver_name = if printer_driver_name.is_empty() {
None
} else {
Some(printer_driver_name)
};
};
}
self.clone()
}
async fn connect(&self) -> Result<Self::Session, Self::Error> {
let (
username,
destination,
server_domain,
password,
proxy_address,
auth_token,
pcb,
kdc_proxy_url,
client_name,
desktop_size,
render_canvas,
set_cursor_style_callback,
set_cursor_style_callback_context,
remote_clipboard_changed_callback,
force_clipboard_update_callback,
files_available_callback,
file_contents_request_callback,
file_contents_response_callback,
lock_callback,
unlock_callback,
locks_expired_callback,
invalid_print_job_stream_callbacks,
print_job_stream_callbacks,
printer_name,
printer_device_id,
printer_driver_name,
outbound_message_size_limit,
);
{
let inner = self.0.borrow();
username = inner.username.clone().context("username missing")?;
destination = inner.destination.clone().context("destination missing")?;
server_domain = inner.server_domain.clone();
password = inner.password.clone().context("password missing")?;
proxy_address = inner.proxy_address.clone().context("proxy_address missing")?;
auth_token = inner.auth_token.clone().context("auth_token missing")?;
pcb = inner.pcb.clone();
kdc_proxy_url = inner.kdc_proxy_url.clone();
client_name = inner.client_name.clone();
desktop_size = inner.desktop_size;
render_canvas = inner.render_canvas.clone().context("render_canvas missing")?;
set_cursor_style_callback = inner
.set_cursor_style_callback
.clone()
.context("set_cursor_style_callback missing")?;
set_cursor_style_callback_context = inner
.set_cursor_style_callback_context
.clone()
.context("set_cursor_style_callback_context missing")?;
remote_clipboard_changed_callback = inner.remote_clipboard_changed_callback.clone();
force_clipboard_update_callback = inner.force_clipboard_update_callback.clone();
files_available_callback = inner.files_available_callback.clone();
file_contents_request_callback = inner.file_contents_request_callback.clone();
file_contents_response_callback = inner.file_contents_response_callback.clone();
lock_callback = inner.lock_callback.clone();
unlock_callback = inner.unlock_callback.clone();
locks_expired_callback = inner.locks_expired_callback.clone();
invalid_print_job_stream_callbacks = inner.invalid_print_job_stream_callbacks;
print_job_stream_callbacks = inner.print_job_stream_callbacks.clone();
printer_name = inner.printer_name.clone();
printer_device_id = inner.printer_device_id;
printer_driver_name = inner.printer_driver_name.clone();
outbound_message_size_limit = inner.outbound_message_size_limit;
}
info!("Connect to RDP host");
let mut config = build_config(username, password, server_domain, client_name.clone(), desktop_size);
let enable_credssp = self.0.borrow().enable_credssp;
config.enable_credssp = enable_credssp;
let (input_events_tx, input_events_rx) = mpsc::unbounded();
let clipboard = remote_clipboard_changed_callback.clone().map(|callback| {
WasmClipboard::new(
clipboard::WasmClipboardMessageProxy::new(input_events_tx.clone()),
clipboard::JsClipboardCallbacks {
on_remote_clipboard_changed: callback,
on_force_clipboard_update: force_clipboard_update_callback,
on_files_available: files_available_callback,
on_file_contents_request: file_contents_request_callback,
on_file_contents_response: file_contents_response_callback,
on_lock: lock_callback,
on_unlock: unlock_callback,
on_locks_expired: locks_expired_callback,
},
)
});
if invalid_print_job_stream_callbacks {
return Err(IronError::from(anyhow::anyhow!(
"printer redirection requires valid print_job_stream_callbacks"
)));
}
// Build the virtual-printer pair when JS printer callbacks were
// registered via extension(). Backend is Send (holds the mpsc proxy
// only) and goes into the SVC processor below; the front-end
// `WasmPrinter` owns the JS callbacks and lives on `Session`.
let (printer_backend, printer) = match print_job_stream_callbacks {
Some(callbacks) => {
let (backend, printer) = wasm_printer_pair(input_events_tx.clone(), callbacks);
(Some(backend), Some(printer))
}
None => (None, None),
};
// Default to 2 to avoid a potential collision if drive redirection is
// enabled in the same session.
let printer_device_id = printer_device_id.unwrap_or(2);
let printer_name = printer_name.unwrap_or_else(|| "IronRDP Virtual Printer".to_owned());
let printer_driver_name = printer_driver_name.unwrap_or_else(default_printer_driver_name);
let ws = WebSocket::open(&proxy_address).context("couldn't open WebSocket")?;
// NOTE: ideally, when the WebSocket can't be opened, the above call should fail with details on why is that
// (e.g., the proxy hostname could not be resolved, proxy service is not running), but errors are neved
// bubbled up in practice, so instead we poll the WebSocket state until we know its connected (i.e., the
// WebSocket handshake is a success and user data can be exchanged).
loop {
match ws.state() {
websocket::State::Closing | websocket::State::Closed => {
return Err(IronError::from(anyhow::anyhow!(
"failed to connect to {proxy_address} (WebSocket is `{:?}`)",
ws.state()
))
.with_kind(IronErrorKind::ProxyConnect));
}
websocket::State::Connecting => {
trace!("WebSocket is connecting to proxy at {proxy_address}...");
gloo_timers::future::sleep(Duration::from_millis(50)).await;
}
websocket::State::Open => {
debug!("WebSocket connected to {proxy_address} with success");
break;
}
}
}
let use_display_control = self.0.borrow().use_display_control;
let (connection_result, ws) = connect(ConnectParams {
ws,
config,
proxy_auth_token: auth_token,
destination,
pcb,
kdc_proxy_url,
clipboard_backend: clipboard.as_ref().map(|clip| clip.backend()),
printer_backend,
printer_device_id,
printer_name,
printer_driver_name,
computer_name: client_name.clone(),
use_display_control,
})
.await?;
info!("Connected!");
let (rdp_reader, rdp_writer) = futures_util::AsyncReadExt::split(ws);
let (writer_tx, writer_rx) = mpsc::unbounded();
spawn_local(writer_task(writer_rx, rdp_writer, outbound_message_size_limit));
Ok(Session {
desktop_size: connection_result.desktop_size,
input_database: RefCell::new(ironrdp::input::Database::new()),
writer_tx,
input_events_tx,
render_canvas,
set_cursor_style_callback,
set_cursor_style_callback_context,
input_events_rx: RefCell::new(Some(input_events_rx)),
rdp_reader: RefCell::new(Some(rdp_reader)),
connection_result: RefCell::new(Some(connection_result)),
clipboard: RefCell::new(Some(clipboard)),
printer: RefCell::new(Some(printer)),
})
}
}
pub(crate) type FastPathInputEvents = smallvec::SmallVec<[FastPathInputEvent; 2]>;
#[derive(Debug)]
pub(crate) enum RdpInputEvent {
Cliprdr(ClipboardMessage),
ClipboardBackend(WasmClipboardBackendMessage),
/// Printer backend → event loop: a print job finished and its bytes are
/// ready for delivery to JS. See [`crate::printer::PrinterBackendMessage`].
Printer(crate::printer::PrinterBackendMessage),
FastPath(FastPathInputEvents),
Resize {
width: u32,
height: u32,
scale_factor: Option<u32>,
physical_size: Option<(u32, u32)>,
},
TerminateSession,
}
pub(crate) struct SessionTerminationInfo {
reason: GracefulDisconnectReason,
}
impl iron_remote_desktop::SessionTerminationInfo for SessionTerminationInfo {
fn reason(&self) -> String {
self.reason.to_string()
}
}
pub(crate) struct Session {
desktop_size: connector::DesktopSize,
input_database: RefCell<ironrdp::input::Database>,
writer_tx: mpsc::UnboundedSender<Vec<u8>>,
input_events_tx: mpsc::UnboundedSender<RdpInputEvent>,
render_canvas: HtmlCanvasElement,
set_cursor_style_callback: js_sys::Function,
set_cursor_style_callback_context: JsValue,
// Consumed when `run` is called
input_events_rx: RefCell<Option<mpsc::UnboundedReceiver<RdpInputEvent>>>,
connection_result: RefCell<Option<connector::ConnectionResult>>,
rdp_reader: RefCell<Option<ReadHalf<WebSocket>>>,
clipboard: RefCell<Option<Option<WasmClipboard>>>,
printer: RefCell<Option<Option<WasmPrinter>>>,
}
impl Session {
fn h_send_inputs(&self, inputs: smallvec::SmallVec<[FastPathInputEvent; 2]>) -> Result<(), IronError> {
if !inputs.is_empty() {
trace!("Inputs: {inputs:?}");
self.input_events_tx
.unbounded_send(RdpInputEvent::FastPath(inputs))
.context("Send input events to writer task")?;
}
Ok(())
}
fn set_cursor_style(&self, style: CursorStyle) -> Result<(), IronError> {
let (kind, data, hotspot_x, hotspot_y) = match style {
CursorStyle::Default => ("default", None, None, None),
CursorStyle::Hidden => ("hidden", None, None, None),
CursorStyle::Url {
data,
hotspot_x,
hotspot_y,
} => ("url", Some(data), Some(hotspot_x), Some(hotspot_y)),
};
let args = js_sys::Array::from_iter([
JsValue::from_str(kind),
JsValue::from(data),
JsValue::from_f64(hotspot_x.unwrap_or_default().into()),
JsValue::from_f64(hotspot_y.unwrap_or_default().into()),
]);
let _ret = self
.set_cursor_style_callback
.apply(&self.set_cursor_style_callback_context, &args)
.map_err(|e| anyhow::Error::msg(format!("set cursor style callback failed: {e:?}")))?;
Ok(())
}
}
impl iron_remote_desktop::Session for Session {
type SessionTerminationInfo = SessionTerminationInfo;
type InputTransaction = InputTransaction;
type ClipboardData = ClipboardData;
type Error = IronError;
async fn run(&self) -> Result<Self::SessionTerminationInfo, Self::Error> {
let rdp_reader = self
.rdp_reader
.borrow_mut()
.take()
.context("RDP session can be started only once")?;
let mut input_events = self
.input_events_rx
.borrow_mut()
.take()
.context("RDP session can be started only once")?;
let connection_result = self
.connection_result
.borrow_mut()
.take()
.expect("run called only once");
let mut clipboard = self.clipboard.borrow_mut().take().expect("run called only once");
let mut wasm_printer = self.printer.borrow_mut().take().expect("run called only once");
let mut framed = ironrdp_futures::LocalFuturesFramed::new(rdp_reader);
debug!("Initialize canvas");
let desktop_width =
NonZeroU32::new(u32::from(connection_result.desktop_size.width)).context("desktop width is zero")?;
let desktop_height =
NonZeroU32::new(u32::from(connection_result.desktop_size.height)).context("desktop height is zero")?;
let mut gui =
Canvas::new(self.render_canvas.clone(), desktop_width, desktop_height).context("canvas initialization")?;
debug!("Canvas initialized");
info!("Start RDP session");
let mut image = DecodedImage::new(
PixelFormat::RgbA32,
connection_result.desktop_size.width,
connection_result.desktop_size.height,
);
let mut requested_resize = None;
let mut active_stage = ActiveStage::new(connection_result);
// Timer interval for driving clipboard lock timeouts (5 second interval)
let mut cleanup_interval = IntervalStream::new(5_000).fuse();
let disconnect_reason = 'outer: loop {
let outputs = select! {
frame = framed.read_pdu().fuse() => {
let (action, payload) = frame.context("read frame")?;
trace!(?action, frame_length = payload.len(), "Frame received");
active_stage.process(&mut image, action, &payload)?
}
input_events = input_events.next() => {
let event = input_events.context("read next input events")?;
match event {
RdpInputEvent::Cliprdr(message) => {
if let Some(cliprdr) = active_stage.get_svc_processor_mut::<CliprdrClient>() {
if let Some(svc_messages) = match message {
ClipboardMessage::SendInitiateCopy(formats) => Some(
cliprdr.initiate_copy(&formats)
.context("cliprdr initiate copy")?
),
ClipboardMessage::SendFormatData(response) => Some(
cliprdr.submit_format_data(response)
.context("cliprdr submit format data")?
),
ClipboardMessage::SendInitiatePaste(format) => Some(
cliprdr.initiate_paste(format)
.context("cliprdr initiate paste")?
),
ClipboardMessage::SendFileContentsRequest(request) => Some(
cliprdr.request_file_contents(request)
.context("cliprdr request file contents")?
),
ClipboardMessage::SendFileContentsResponse(response) => Some(
cliprdr.submit_file_contents(response)
.context("cliprdr submit file contents")?
),
ClipboardMessage::Error(e) => {
error!(error = %e, "Clipboard backend error");
None
}
} {
let frame = active_stage.process_svc_processor_messages(svc_messages)?;
// Send the messages to the server
vec![ActiveStageOutput::ResponseFrame(frame)]
} else {
// No messages to send to the server
Vec::new()
}
} else {
warn!("Clipboard event received, but Cliprdr is not available");
Vec::new()
}
}
RdpInputEvent::ClipboardBackend(event) => {
use crate::clipboard::WasmClipboardBackendMessage;
// Handle messages that need direct cliprdr access
match event {
WasmClipboardBackendMessage::FileContentsRequestSend { stream_id, index, flags, position, size, clip_data_id } => {
if let Some(cliprdr) = active_stage.get_svc_processor_mut::<CliprdrClient>() {
let request = FileContentsRequest {
stream_id,
index,
flags,
position,
requested_size: size,
data_id: clip_data_id,
};
match cliprdr.request_file_contents(request) {
Ok(svc_messages) => {
let frame = active_stage.process_svc_processor_messages(svc_messages)?;
vec![ActiveStageOutput::ResponseFrame(frame)]
}
Err(e) => {
error!(error = %e, "File contents request failed");
Vec::new()
}
}
} else {
warn!("Request file contents received, but Cliprdr is not available");
Vec::new()
}
}
WasmClipboardBackendMessage::FileContentsResponseSend { stream_id, is_error, data } => {
if let Some(cliprdr) = active_stage.get_svc_processor_mut::<CliprdrClient>() {
let response = if is_error {
FileContentsResponse::new_error(stream_id)
} else {
FileContentsResponse::new_data_response(stream_id, data)
};
match cliprdr.submit_file_contents(response) {
Ok(svc_messages) => {
let frame = active_stage.process_svc_processor_messages(svc_messages)?;
vec![ActiveStageOutput::ResponseFrame(frame)]
}
Err(e) => {
error!(error = %e, "File contents submit failed");
Vec::new()
}
}
} else {
warn!("Submit file contents received, but Cliprdr is not available");
Vec::new()
}
}
WasmClipboardBackendMessage::InitiateFileCopy { files } => {
if let Some(cliprdr) = active_stage.get_svc_processor_mut::<CliprdrClient>() {
// Convert FileMetadata to FileDescriptor using the
// validated conversion that checks name length/emptiness
// and sets proper file attributes.
let file_descriptors: Vec<FileDescriptor> = files
.into_iter()
.filter_map(|f| match f.to_file_descriptor() {
Ok(desc) => Some(desc),
Err(e) => {
warn!(error = format!("{e:#}"), "Skipping file with invalid metadata");
None
}
})
.collect();
match cliprdr.initiate_file_copy(file_descriptors) {
Ok(svc_messages) => {
let frame = active_stage.process_svc_processor_messages(svc_messages)?;
vec![ActiveStageOutput::ResponseFrame(frame)]
}
Err(e) => {
error!(error = %e, "Initiate file copy failed");
Vec::new()
}
}
} else {
warn!("Initiate file copy received, but Cliprdr is not available");
Vec::new()
}
}
// All other messages are forwarded to clipboard backend
other => {
if let Some(clipboard) = &mut clipboard {
clipboard.process_event(other)?;
}
Vec::new()
}
}
}
RdpInputEvent::FastPath(events) => {
active_stage.process_fastpath_input(&mut image, &events)
.context("fast path input events processing")?
}
RdpInputEvent::Resize { width, height, scale_factor, physical_size } => {
debug!(width, height, scale_factor, "Resize event received");
if width == 0 || height == 0 {
warn!("Resize event ignored: width or height is zero");
Vec::new()
} else if let Some(response_frame) = active_stage.encode_resize(width, height, scale_factor, physical_size) {
let width = NonZeroU32::new(width).expect("width is guaranteed to be non-zero due to the prior check");
let height = NonZeroU32::new(height).expect("height is guaranteed to be non-zero due to the prior check");
requested_resize = Some((width, height));
vec![ActiveStageOutput::ResponseFrame(response_frame?)]
} else {
debug!("Resize event ignored");
Vec::new()
}
},
RdpInputEvent::Printer(message) => {
// The printer backend lives inside the Rdpdr SVC
// processor (Send-only); the front-end
// `WasmPrinter` owns the JS callback (!Send) and
// lives here. Just forward the message.
if let Some(ref mut wasm_printer) = wasm_printer {
wasm_printer.process_message(message);
} else {
warn!("Printer event received, but no printer is configured");
}
Vec::new()
}
RdpInputEvent::TerminateSession => {
active_stage.graceful_shutdown()
.context("graceful shutdown")?
}
}
}
_ = cleanup_interval.next() => {
// Drive clipboard lock timeout cleanup
if let Some(cliprdr) = active_stage.get_svc_processor_mut::<CliprdrClient>() {
match cliprdr.drive_timeouts() {
Ok(svc_messages) => {
let frame = active_stage.process_svc_processor_messages(svc_messages)?;
if !frame.is_empty() {
vec![ActiveStageOutput::ResponseFrame(frame)]
} else {
Vec::new()
}
}
Err(e) => {
warn!(error = %e, "Clipboard timeout cleanup failed");
Vec::new()
}
}
} else {
Vec::new()
}
}
};
for out in outputs {
match out {
ActiveStageOutput::ResponseFrame(frame) => {
self.writer_tx
.unbounded_send(frame)
.context("Send frame to writer task")?;
}
ActiveStageOutput::GraphicsUpdate(region) => {
// PERF: some copies and conversion could be optimized
let (region, buffer) = extract_partial_image(&image, region);
gui.draw(&buffer, region).context("draw updated region")?;
}
ActiveStageOutput::PointerDefault => {
self.set_cursor_style(CursorStyle::Default)?;
}
ActiveStageOutput::PointerHidden => {
self.set_cursor_style(CursorStyle::Hidden)?;
}
ActiveStageOutput::PointerPosition { .. } => {
// Not applicable for web.
}
ActiveStageOutput::PointerBitmap(pointer) => {
// Maximum allowed cursor size for browsers is 32x32, because bigger sizes
// will cause the following issues:
// - cursors bigger than 128x128 are not supported in browsers.
// - cursors bigger than 32x32 will default to the system cursor if their
// sprite does not fit in the browser's viewport, introducing an abrupt
// cursor style change when the cursor is moved to the edge of the
// browser window.
//
// Therefore, we need to scale the cursor sprite down to 32x32 if it is
// bigger than that.
const MAX_CURSOR_SIZE: u16 = 32;
// INVARIANT: 0 < scale <= 1.0
// INVARIANT: pointer.width * scale <= MAX_CURSOR_SIZE
// INVARIANT: pointer.height * scale <= MAX_CURSOR_SIZE
let scale = if pointer.width >= pointer.height && pointer.width > MAX_CURSOR_SIZE {
Some(f64::from(MAX_CURSOR_SIZE) / f64::from(pointer.width))
} else if pointer.height > MAX_CURSOR_SIZE {
Some(f64::from(MAX_CURSOR_SIZE) / f64::from(pointer.height))
} else {
None
};
let (png_width, png_height, hotspot_x, hotspot_y, rgba_buffer) = if let Some(scale) = scale {
// Per invariants: Following conversions will never saturate.
let scaled_width = f64_to_u16_saturating_cast(f64::from(pointer.width) * scale);
let scaled_height = f64_to_u16_saturating_cast(f64::from(pointer.height) * scale);
let hotspot_x = f64_to_u16_saturating_cast(f64::from(pointer.hotspot_x) * scale);
let hotspot_y = f64_to_u16_saturating_cast(f64::from(pointer.hotspot_y) * scale);
// Per invariants: scaled_width * scaled_height * 4 <= 32 * 32 * 4 < usize::MAX
#[expect(clippy::arithmetic_side_effects)]
let resized_rgba_buffer_size = usize::from(scaled_width * scaled_height * 4);
let mut rgba_resized = vec![0u8; resized_rgba_buffer_size];
let mut resizer = resize::new(
usize::from(pointer.width),
usize::from(pointer.height),
usize::from(scaled_width),
usize::from(scaled_height),
resize::Pixel::RGBA8P,
resize::Type::Lanczos3,
)
.context("failed to initialize cursor resizer")?;
resizer
.resize(pointer.bitmap_data.as_pixels(), rgba_resized.as_pixels_mut())
.context("failed to resize cursor")?;
(
scaled_width,
scaled_height,
hotspot_x,
hotspot_y,
Cow::Owned(rgba_resized),
)
} else {
(
pointer.width,
pointer.height,
pointer.hotspot_x,
pointer.hotspot_y,
Cow::Borrowed(pointer.bitmap_data.as_slice()),
)
};
// Encode PNG.
let mut png_buffer = Vec::new();
{
let mut encoder =
png::Encoder::new(&mut png_buffer, u32::from(png_width), u32::from(png_height));
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_compression(png::Compression::Fast);
let mut writer = encoder.write_header().context("PNG encoder header write failed")?;
writer
.write_image_data(&rgba_buffer)
.context("failed to encode pointer PNG")?;
}
// Encode PNG into Base64 data URL.
let mut style = "data:image/png;base64,".to_owned();
base64::engine::general_purpose::STANDARD.encode_string(png_buffer, &mut style);
self.set_cursor_style(CursorStyle::Url {
data: style,
hotspot_x,
hotspot_y,
})?;
}
ActiveStageOutput::DeactivateAll(mut box_connection_activation) => {
// Execute the Deactivation-Reactivation Sequence:
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/dfc234ce-481a-4674-9a5d-2a7bafb14432
debug!("Received Server Deactivate All PDU, executing Deactivation-Reactivation Sequence");
// We need to perform resize after receiving the Deactivate All PDU, because there may be frames
// with the previous dimensions arriving between the resize request and this message.
if let Some((width, height)) = requested_resize {
self.render_canvas.set_width(width.get());
self.render_canvas.set_height(height.get());
gui.resize(width, height);
requested_resize = None;
}
let mut buf = WriteBuf::new();
'activation_seq: loop {
let written =
single_sequence_step_read(&mut framed, &mut *box_connection_activation, &mut buf)
.await?;
if written.size().is_some() {
self.writer_tx
.unbounded_send(buf.filled().to_vec())
.context("Send frame to writer task")?;
}
if let ConnectionActivationState::Finalized {