-
Notifications
You must be signed in to change notification settings - Fork 29.9k
/
control_server.rs
1187 lines (1064 loc) · 32.8 KB
/
control_server.rs
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use crate::async_pipe::get_socket_rw_stream;
use crate::constants::{CONTROL_PORT, PRODUCT_NAME_LONG};
use crate::log;
use crate::msgpack_rpc::{new_msgpack_rpc, start_msgpack_rpc, MsgPackCodec, MsgPackSerializer};
use crate::rpc::{MaybeSync, RpcBuilder, RpcCaller, RpcDispatcher};
use crate::self_update::SelfUpdate;
use crate::state::LauncherPaths;
use crate::tunnels::protocol::{HttpRequestParams, METHOD_CHALLENGE_ISSUE};
use crate::tunnels::socket_signal::CloseReason;
use crate::update_service::{Platform, Release, TargetKind, UpdateService};
use crate::util::errors::{
wrap, AnyError, CodeError, MismatchedLaunchModeError, NoAttachedServerError,
};
use crate::util::http::{
DelegatedHttpRequest, DelegatedSimpleHttp, FallbackSimpleHttp, ReqwestSimpleHttp,
};
use crate::util::io::SilentCopyProgress;
use crate::util::is_integrated_cli;
use crate::util::os::os_release;
use crate::util::sync::{new_barrier, Barrier, BarrierOpener};
use futures::stream::FuturesUnordered;
use futures::FutureExt;
use opentelemetry::trace::SpanKind;
use opentelemetry::KeyValue;
use std::collections::HashMap;
use std::process::Stdio;
use tokio::pin;
use tokio::process::{ChildStderr, ChildStdin};
use tokio_util::codec::Decoder;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, DuplexStream};
use tokio::sync::{mpsc, Mutex};
use super::challenge::{create_challenge, sign_challenge, verify_challenge};
use super::code_server::{
download_cli_into_cache, AnyCodeServer, CodeServerArgs, ServerBuilder, ServerParamsRaw,
SocketCodeServer,
};
use super::dev_tunnels::ActiveTunnel;
use super::paths::prune_stopped_servers;
use super::port_forwarder::{PortForwarding, PortForwardingProcessor};
use super::protocol::{
AcquireCliParams, CallServerHttpParams, CallServerHttpResult, ChallengeIssueParams,
ChallengeIssueResponse, ChallengeVerifyParams, ClientRequestMethod, EmptyObject, ForwardParams,
ForwardResult, FsStatRequest, FsStatResponse, GetEnvResponse, GetHostnameResponse,
HttpBodyParams, HttpHeadersParams, ServeParams, ServerLog, ServerMessageParams, SpawnParams,
SpawnResult, ToClientRequest, UnforwardParams, UpdateParams, UpdateResult, VersionResponse,
METHOD_CHALLENGE_VERIFY,
};
use super::server_bridge::ServerBridge;
use super::server_multiplexer::ServerMultiplexer;
use super::shutdown_signal::ShutdownSignal;
use super::socket_signal::{
ClientMessageDecoder, ServerMessageDestination, ServerMessageSink, SocketSignal,
};
type HttpRequestsMap = Arc<std::sync::Mutex<HashMap<u32, DelegatedHttpRequest>>>;
type CodeServerCell = Arc<Mutex<Option<SocketCodeServer>>>;
struct HandlerContext {
/// Log handle for the server
log: log::Logger,
/// Whether the server update during the handler session.
did_update: Arc<AtomicBool>,
/// Whether authentication is still required on the socket.
auth_state: Arc<std::sync::Mutex<AuthState>>,
/// A loopback channel to talk to the socket server task.
socket_tx: mpsc::Sender<SocketSignal>,
/// Configured launcher paths.
launcher_paths: LauncherPaths,
/// Connected VS Code Server
code_server: CodeServerCell,
/// Potentially many "websocket" connections to client
server_bridges: ServerMultiplexer,
// the cli arguments used to start the code server
code_server_args: CodeServerArgs,
/// port forwarding functionality
port_forwarding: Option<PortForwarding>,
/// install platform for the VS Code server
platform: Platform,
/// http client to make download/update requests
http: Arc<FallbackSimpleHttp>,
/// requests being served by the client
http_requests: HttpRequestsMap,
}
/// Handler auth state.
enum AuthState {
/// Auth is required, we're waiting for the client to send its challenge optionally bearing a token.
WaitingForChallenge(Option<String>),
/// A challenge has been issued. Waiting for a verification.
ChallengeIssued(String),
/// Auth is no longer required.
Authenticated,
}
static MESSAGE_ID_COUNTER: AtomicU32 = AtomicU32::new(0);
// Gets a next incrementing number that can be used in logs
pub fn next_message_id() -> u32 {
MESSAGE_ID_COUNTER.fetch_add(1, Ordering::SeqCst)
}
impl HandlerContext {
async fn dispose(&self) {
self.server_bridges.dispose().await;
info!(self.log, "Disposed of connection to running server.");
}
}
enum ServerSignal {
/// Signalled when the server has been updated and we want to respawn.
/// We'd generally need to stop and then restart the launcher, but the
/// program might be managed by a supervisor like systemd. Instead, we
/// will stop the TCP listener and spawn the launcher again as a subprocess
/// with the same arguments we used.
Respawn,
}
pub enum Next {
/// Whether the server should be respawned in a new binary (see ServerSignal.Respawn).
Respawn,
/// Whether the tunnel should be restarted
Restart,
/// Whether the process should exit
Exit,
}
pub struct ServerTermination {
pub next: Next,
pub tunnel: ActiveTunnel,
}
// Runs the launcher server. Exits on a ctrl+c or when requested by a user.
// Note that client connections may not be closed when this returns; use
// `close_all_clients()` on the ServerTermination to make this happen.
pub async fn serve(
log: &log::Logger,
mut tunnel: ActiveTunnel,
launcher_paths: &LauncherPaths,
code_server_args: &CodeServerArgs,
platform: Platform,
mut shutdown_rx: Barrier<ShutdownSignal>,
) -> Result<ServerTermination, AnyError> {
let mut port = tunnel.add_port_direct(CONTROL_PORT).await?;
let mut forwarding = PortForwardingProcessor::new();
let (tx, mut rx) = mpsc::channel::<ServerSignal>(4);
let (exit_barrier, signal_exit) = new_barrier();
loop {
tokio::select! {
Ok(reason) = shutdown_rx.wait() => {
info!(log, "Shutting down: {}", reason);
drop(signal_exit);
return Ok(ServerTermination {
next: match reason {
ShutdownSignal::RpcRestartRequested => Next::Restart,
_ => Next::Exit,
},
tunnel,
});
},
c = rx.recv() => {
if let Some(ServerSignal::Respawn) = c {
drop(signal_exit);
return Ok(ServerTermination {
next: Next::Respawn,
tunnel,
});
}
},
Some(w) = forwarding.recv() => {
forwarding.process(w, &mut tunnel).await;
},
l = port.recv() => {
let socket = match l {
Some(p) => p,
None => {
warning!(log, "ssh tunnel disposed, tearing down");
return Ok(ServerTermination {
next: Next::Restart,
tunnel,
});
}
};
let own_log = log.prefixed(&log::new_rpc_prefix());
let own_tx = tx.clone();
let own_paths = launcher_paths.clone();
let own_exit = exit_barrier.clone();
let own_code_server_args = code_server_args.clone();
let own_forwarding = forwarding.handle();
tokio::spawn(async move {
use opentelemetry::trace::{FutureExt, TraceContextExt};
let span = own_log.span("server.socket").with_kind(SpanKind::Consumer).start(own_log.tracer());
let cx = opentelemetry::Context::current_with_span(span);
let serve_at = Instant::now();
debug!(own_log, "Serving new connection");
let (writehalf, readhalf) = socket.into_split();
let stats = process_socket(readhalf, writehalf, own_tx, Some(own_forwarding), ServeStreamParams {
log: own_log,
launcher_paths: own_paths,
code_server_args: own_code_server_args,
platform,
exit_barrier: own_exit,
requires_auth: AuthRequired::None,
}).with_context(cx.clone()).await;
cx.span().add_event(
"socket.bandwidth",
vec![
KeyValue::new("tx", stats.tx as f64),
KeyValue::new("rx", stats.rx as f64),
KeyValue::new("duration_ms", serve_at.elapsed().as_millis() as f64),
],
);
cx.span().end();
});
}
}
}
}
#[derive(Clone)]
pub enum AuthRequired {
None,
VSDA,
VSDAWithToken(String),
}
#[derive(Clone)]
pub struct ServeStreamParams {
pub log: log::Logger,
pub launcher_paths: LauncherPaths,
pub code_server_args: CodeServerArgs,
pub platform: Platform,
pub requires_auth: AuthRequired,
pub exit_barrier: Barrier<ShutdownSignal>,
}
pub async fn serve_stream(
readhalf: impl AsyncRead + Send + Unpin + 'static,
writehalf: impl AsyncWrite + Unpin,
params: ServeStreamParams,
) -> SocketStats {
// Currently the only server signal is respawn, that doesn't have much meaning
// when serving a stream, so make an ignored channel.
let (server_rx, server_tx) = mpsc::channel(1);
drop(server_tx);
process_socket(readhalf, writehalf, server_rx, None, params).await
}
pub struct SocketStats {
rx: usize,
tx: usize,
}
#[allow(clippy::too_many_arguments)]
fn make_socket_rpc(
log: log::Logger,
socket_tx: mpsc::Sender<SocketSignal>,
http_delegated: DelegatedSimpleHttp,
launcher_paths: LauncherPaths,
code_server_args: CodeServerArgs,
port_forwarding: Option<PortForwarding>,
requires_auth: AuthRequired,
platform: Platform,
) -> RpcDispatcher<MsgPackSerializer, HandlerContext> {
let http_requests = Arc::new(std::sync::Mutex::new(HashMap::new()));
let server_bridges = ServerMultiplexer::new();
let mut rpc = RpcBuilder::new(MsgPackSerializer {}).methods(HandlerContext {
did_update: Arc::new(AtomicBool::new(false)),
auth_state: Arc::new(std::sync::Mutex::new(match requires_auth {
AuthRequired::VSDAWithToken(t) => AuthState::WaitingForChallenge(Some(t)),
AuthRequired::VSDA => AuthState::WaitingForChallenge(None),
AuthRequired::None => AuthState::Authenticated,
})),
socket_tx,
log: log.clone(),
launcher_paths,
code_server_args,
code_server: Arc::new(Mutex::new(None)),
server_bridges,
port_forwarding,
platform,
http: Arc::new(FallbackSimpleHttp::new(
ReqwestSimpleHttp::new(),
http_delegated,
)),
http_requests,
});
rpc.register_sync("ping", |_: EmptyObject, _| Ok(EmptyObject {}));
rpc.register_sync("gethostname", |_: EmptyObject, _| handle_get_hostname());
rpc.register_sync("fs_stat", |p: FsStatRequest, c| {
ensure_auth(&c.auth_state)?;
handle_stat(p.path)
});
rpc.register_sync("get_env", |_: EmptyObject, c| {
ensure_auth(&c.auth_state)?;
handle_get_env()
});
rpc.register_sync(METHOD_CHALLENGE_ISSUE, |p: ChallengeIssueParams, c| {
handle_challenge_issue(p, &c.auth_state)
});
rpc.register_sync(METHOD_CHALLENGE_VERIFY, |p: ChallengeVerifyParams, c| {
handle_challenge_verify(p.response, &c.auth_state)
});
rpc.register_async("serve", move |params: ServeParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_serve(c, params).await
});
rpc.register_async("update", |p: UpdateParams, c| async move {
handle_update(&c.http, &c.log, &c.did_update, &p).await
});
rpc.register_sync("servermsg", |m: ServerMessageParams, c| {
if let Err(e) = handle_server_message(&c.log, &c.server_bridges, m) {
warning!(c.log, "error handling call: {:?}", e);
}
Ok(EmptyObject {})
});
rpc.register_sync("prune", |_: EmptyObject, c| handle_prune(&c.launcher_paths));
rpc.register_async("callserverhttp", |p: CallServerHttpParams, c| async move {
let code_server = c.code_server.lock().await.clone();
handle_call_server_http(code_server, p).await
});
rpc.register_async("forward", |p: ForwardParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_forward(&c.log, &c.port_forwarding, p).await
});
rpc.register_async("unforward", |p: UnforwardParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_unforward(&c.log, &c.port_forwarding, p).await
});
rpc.register_async("acquire_cli", |p: AcquireCliParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_acquire_cli(&c.launcher_paths, &c.http, &c.log, p).await
});
rpc.register_duplex("spawn", 3, |mut streams, p: SpawnParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_spawn(
&c.log,
p,
Some(streams.remove(0)),
Some(streams.remove(0)),
Some(streams.remove(0)),
)
.await
});
rpc.register_duplex(
"spawn_cli",
3,
|mut streams, p: SpawnParams, c| async move {
ensure_auth(&c.auth_state)?;
handle_spawn_cli(
&c.log,
p,
streams.remove(0),
streams.remove(0),
streams.remove(0),
)
.await
},
);
rpc.register_sync("httpheaders", |p: HttpHeadersParams, c| {
if let Some(req) = c.http_requests.lock().unwrap().get(&p.req_id) {
req.initial_response(p.status_code, p.headers);
}
Ok(EmptyObject {})
});
rpc.register_sync("httpbody", move |p: HttpBodyParams, c| {
let mut reqs = c.http_requests.lock().unwrap();
if let Some(req) = reqs.get(&p.req_id) {
if !p.segment.is_empty() {
req.body(p.segment);
}
if p.complete {
reqs.remove(&p.req_id);
}
}
Ok(EmptyObject {})
});
rpc.register_sync(
"version",
|_: EmptyObject, _| Ok(VersionResponse::default()),
);
rpc.build(log)
}
fn ensure_auth(is_authed: &Arc<std::sync::Mutex<AuthState>>) -> Result<(), AnyError> {
if let AuthState::Authenticated = &*is_authed.lock().unwrap() {
Ok(())
} else {
Err(CodeError::ServerAuthRequired.into())
}
}
#[allow(clippy::too_many_arguments)] // necessary here
async fn process_socket(
readhalf: impl AsyncRead + Send + Unpin + 'static,
mut writehalf: impl AsyncWrite + Unpin,
server_tx: mpsc::Sender<ServerSignal>,
port_forwarding: Option<PortForwarding>,
params: ServeStreamParams,
) -> SocketStats {
let ServeStreamParams {
mut exit_barrier,
log,
launcher_paths,
code_server_args,
platform,
requires_auth,
} = params;
let (http_delegated, mut http_rx) = DelegatedSimpleHttp::new(log.clone());
let (socket_tx, mut socket_rx) = mpsc::channel(4);
let rx_counter = Arc::new(AtomicUsize::new(0));
let http_requests = Arc::new(std::sync::Mutex::new(HashMap::new()));
let already_authed = matches!(requires_auth, AuthRequired::None);
let rpc = make_socket_rpc(
log.clone(),
socket_tx.clone(),
http_delegated,
launcher_paths,
code_server_args,
port_forwarding,
requires_auth,
platform,
);
{
let log = log.clone();
let rx_counter = rx_counter.clone();
let socket_tx = socket_tx.clone();
let exit_barrier = exit_barrier.clone();
tokio::spawn(async move {
if already_authed {
send_version(&socket_tx).await;
}
if let Err(e) =
handle_socket_read(&log, readhalf, exit_barrier, &socket_tx, rx_counter, &rpc).await
{
debug!(log, "closing socket reader: {}", e);
socket_tx
.send(SocketSignal::CloseWith(CloseReason(format!("{}", e))))
.await
.ok();
}
let ctx = rpc.context();
// The connection is now closed, asked to respawn if needed
if ctx.did_update.load(Ordering::SeqCst) {
server_tx.send(ServerSignal::Respawn).await.ok();
}
ctx.dispose().await;
let _ = socket_tx
.send(SocketSignal::CloseWith(CloseReason("eof".to_string())))
.await;
});
}
let mut tx_counter = 0;
loop {
tokio::select! {
_ = exit_barrier.wait() => {
writehalf.shutdown().await.ok();
break;
},
Some(r) = http_rx.recv() => {
let id = next_message_id();
let serialized = rmp_serde::to_vec_named(&ToClientRequest {
id: None,
params: ClientRequestMethod::makehttpreq(HttpRequestParams {
url: &r.url,
method: r.method,
req_id: id,
}),
})
.unwrap();
http_requests.lock().unwrap().insert(id, r);
tx_counter += serialized.len();
if let Err(e) = writehalf.write_all(&serialized).await {
debug!(log, "Closing connection: {}", e);
break;
}
}
recv = socket_rx.recv() => match recv {
None => break,
Some(message) => match message {
SocketSignal::Send(bytes) => {
tx_counter += bytes.len();
if let Err(e) = writehalf.write_all(&bytes).await {
debug!(log, "Closing connection: {}", e);
break;
}
}
SocketSignal::CloseWith(reason) => {
debug!(log, "Closing connection: {}", reason.0);
break;
}
}
}
}
}
SocketStats {
tx: tx_counter,
rx: rx_counter.load(Ordering::Acquire),
}
}
async fn send_version(tx: &mpsc::Sender<SocketSignal>) {
tx.send(SocketSignal::from_message(&ToClientRequest {
id: None,
params: ClientRequestMethod::version(VersionResponse::default()),
}))
.await
.ok();
}
async fn handle_socket_read(
_log: &log::Logger,
readhalf: impl AsyncRead + Unpin,
mut closer: Barrier<ShutdownSignal>,
socket_tx: &mpsc::Sender<SocketSignal>,
rx_counter: Arc<AtomicUsize>,
rpc: &RpcDispatcher<MsgPackSerializer, HandlerContext>,
) -> Result<(), std::io::Error> {
let mut readhalf = BufReader::new(readhalf);
let mut decoder = MsgPackCodec::new();
let mut decoder_buf = bytes::BytesMut::new();
loop {
let read_len = tokio::select! {
r = readhalf.read_buf(&mut decoder_buf) => r,
_ = closer.wait() => Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "eof")),
}?;
if read_len == 0 {
return Ok(());
}
rx_counter.fetch_add(read_len, Ordering::Relaxed);
while let Some(frame) = decoder.decode(&mut decoder_buf)? {
match rpc.dispatch_with_partial(&frame.vec, frame.obj) {
MaybeSync::Sync(Some(v)) => {
if socket_tx.send(SocketSignal::Send(v)).await.is_err() {
return Ok(());
}
}
MaybeSync::Sync(None) => continue,
MaybeSync::Future(fut) => {
let socket_tx = socket_tx.clone();
tokio::spawn(async move {
if let Some(v) = fut.await {
socket_tx.send(SocketSignal::Send(v)).await.ok();
}
});
}
MaybeSync::Stream((stream, fut)) => {
if let Some(stream) = stream {
rpc.register_stream(socket_tx.clone(), stream).await;
}
let socket_tx = socket_tx.clone();
tokio::spawn(async move {
if let Some(v) = fut.await {
socket_tx.send(SocketSignal::Send(v)).await.ok();
}
});
}
}
}
}
}
#[derive(Clone)]
struct ServerOutputSink {
tx: mpsc::Sender<SocketSignal>,
}
impl log::LogSink for ServerOutputSink {
fn write_log(&self, level: log::Level, _prefix: &str, message: &str) {
let s = SocketSignal::from_message(&ToClientRequest {
id: None,
params: ClientRequestMethod::serverlog(ServerLog {
line: message,
level: level.to_u8(),
}),
});
self.tx.try_send(s).ok();
}
fn write_result(&self, _message: &str) {}
}
async fn handle_serve(
c: Arc<HandlerContext>,
params: ServeParams,
) -> Result<EmptyObject, AnyError> {
// fill params.extensions into code_server_args.install_extensions
let mut csa = c.code_server_args.clone();
csa.connection_token = params.connection_token.or(csa.connection_token);
csa.install_extensions.extend(params.extensions.into_iter());
let params_raw = ServerParamsRaw {
commit_id: params.commit_id,
quality: params.quality,
code_server_args: csa,
headless: true,
platform: c.platform,
};
let resolved = if params.use_local_download {
params_raw
.resolve(&c.log, Arc::new(c.http.delegated()))
.await
} else {
params_raw.resolve(&c.log, c.http.clone()).await
}?;
let mut server_ref = c.code_server.lock().await;
let server = match &*server_ref {
Some(o) => o.clone(),
None => {
let install_log = c.log.tee(ServerOutputSink {
tx: c.socket_tx.clone(),
});
macro_rules! do_setup {
($sb:expr) => {
match $sb.get_running().await? {
Some(AnyCodeServer::Socket(s)) => s,
Some(_) => return Err(AnyError::from(MismatchedLaunchModeError())),
None => {
$sb.setup().await?;
$sb.listen_on_default_socket().await?
}
}
};
}
let server = if params.use_local_download {
let sb = ServerBuilder::new(
&install_log,
&resolved,
&c.launcher_paths,
Arc::new(c.http.delegated()),
);
do_setup!(sb)
} else {
let sb =
ServerBuilder::new(&install_log, &resolved, &c.launcher_paths, c.http.clone());
do_setup!(sb)
};
server_ref.replace(server.clone());
server
}
};
attach_server_bridge(
&c.log,
server,
c.socket_tx.clone(),
c.server_bridges.clone(),
params.socket_id,
params.compress,
)
.await?;
Ok(EmptyObject {})
}
async fn attach_server_bridge(
log: &log::Logger,
code_server: SocketCodeServer,
socket_tx: mpsc::Sender<SocketSignal>,
multiplexer: ServerMultiplexer,
socket_id: u16,
compress: bool,
) -> Result<u16, AnyError> {
let (server_messages, decoder) = if compress {
(
ServerMessageSink::new_compressed(
multiplexer.clone(),
socket_id,
ServerMessageDestination::Channel(socket_tx),
),
ClientMessageDecoder::new_compressed(),
)
} else {
(
ServerMessageSink::new_plain(
multiplexer.clone(),
socket_id,
ServerMessageDestination::Channel(socket_tx),
),
ClientMessageDecoder::new_plain(),
)
};
let attached_fut = ServerBridge::new(&code_server.socket, server_messages, decoder).await;
match attached_fut {
Ok(a) => {
multiplexer.register(socket_id, a);
trace!(log, "Attached to server");
Ok(socket_id)
}
Err(e) => Err(e),
}
}
/// Handle an incoming server message. This is synchronous and uses a 'write loop'
/// to ensure message order is preserved exactly, which is necessary for compression.
fn handle_server_message(
log: &log::Logger,
multiplexer: &ServerMultiplexer,
params: ServerMessageParams,
) -> Result<EmptyObject, AnyError> {
if multiplexer.write_message(log, params.i, params.body) {
Ok(EmptyObject {})
} else {
Err(AnyError::from(NoAttachedServerError()))
}
}
fn handle_prune(paths: &LauncherPaths) -> Result<Vec<String>, AnyError> {
prune_stopped_servers(paths).map(|v| {
v.iter()
.map(|p| p.server_dir.display().to_string())
.collect()
})
}
async fn handle_update(
http: &Arc<FallbackSimpleHttp>,
log: &log::Logger,
did_update: &AtomicBool,
params: &UpdateParams,
) -> Result<UpdateResult, AnyError> {
if matches!(is_integrated_cli(), Ok(true)) || did_update.load(Ordering::SeqCst) {
return Ok(UpdateResult {
up_to_date: true,
did_update: false,
});
}
let update_service = UpdateService::new(log.clone(), http.clone());
let updater = SelfUpdate::new(&update_service)?;
let latest_release = updater.get_current_release().await?;
let up_to_date = updater.is_up_to_date_with(&latest_release);
if !params.do_update || up_to_date {
return Ok(UpdateResult {
up_to_date,
did_update: false,
});
}
if did_update
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
return Ok(UpdateResult {
up_to_date: true,
did_update: true, // well, another thread did, but same difference...
});
}
info!(log, "Updating CLI to {}", latest_release);
updater
.do_update(&latest_release, SilentCopyProgress())
.await?;
Ok(UpdateResult {
up_to_date: true,
did_update: true,
})
}
fn handle_get_hostname() -> Result<GetHostnameResponse, AnyError> {
Ok(GetHostnameResponse {
value: gethostname::gethostname().to_string_lossy().into_owned(),
})
}
fn handle_stat(path: String) -> Result<FsStatResponse, AnyError> {
Ok(std::fs::metadata(path)
.map(|m| FsStatResponse {
exists: true,
size: Some(m.len()),
kind: Some(match m.file_type() {
t if t.is_dir() => "dir",
t if t.is_file() => "file",
t if t.is_symlink() => "link",
_ => "unknown",
}),
})
.unwrap_or_default())
}
fn handle_get_env() -> Result<GetEnvResponse, AnyError> {
Ok(GetEnvResponse {
env: std::env::vars().collect(),
os_release: os_release().unwrap_or_else(|_| "unknown".to_string()),
#[cfg(windows)]
os_platform: "win32",
#[cfg(target_os = "linux")]
os_platform: "linux",
#[cfg(target_os = "macos")]
os_platform: "darwin",
})
}
fn handle_challenge_issue(
params: ChallengeIssueParams,
auth_state: &Arc<std::sync::Mutex<AuthState>>,
) -> Result<ChallengeIssueResponse, AnyError> {
let challenge = create_challenge();
let mut auth_state = auth_state.lock().unwrap();
if let AuthState::WaitingForChallenge(Some(s)) = &*auth_state {
println!("looking for token {}, got {:?}", s, params.token);
match ¶ms.token {
Some(t) if s != t => return Err(CodeError::AuthChallengeBadToken.into()),
None => return Err(CodeError::AuthChallengeBadToken.into()),
_ => {}
}
}
*auth_state = AuthState::ChallengeIssued(challenge.clone());
Ok(ChallengeIssueResponse { challenge })
}
fn handle_challenge_verify(
response: String,
auth_state: &Arc<std::sync::Mutex<AuthState>>,
) -> Result<EmptyObject, AnyError> {
let mut auth_state = auth_state.lock().unwrap();
match &*auth_state {
AuthState::Authenticated => Ok(EmptyObject {}),
AuthState::WaitingForChallenge(_) => Err(CodeError::AuthChallengeNotIssued.into()),
AuthState::ChallengeIssued(c) => match verify_challenge(c, &response) {
false => Err(CodeError::AuthChallengeNotIssued.into()),
true => {
*auth_state = AuthState::Authenticated;
Ok(EmptyObject {})
}
},
}
}
async fn handle_forward(
log: &log::Logger,
port_forwarding: &Option<PortForwarding>,
params: ForwardParams,
) -> Result<ForwardResult, AnyError> {
let port_forwarding = port_forwarding
.as_ref()
.ok_or(CodeError::PortForwardingNotAvailable)?;
info!(log, "Forwarding port {}", params.port);
let uri = port_forwarding.forward(params.port).await?;
Ok(ForwardResult { uri })
}
async fn handle_unforward(
log: &log::Logger,
port_forwarding: &Option<PortForwarding>,
params: UnforwardParams,
) -> Result<EmptyObject, AnyError> {
let port_forwarding = port_forwarding
.as_ref()
.ok_or(CodeError::PortForwardingNotAvailable)?;
info!(log, "Unforwarding port {}", params.port);
port_forwarding.unforward(params.port).await?;
Ok(EmptyObject {})
}
async fn handle_call_server_http(
code_server: Option<SocketCodeServer>,
params: CallServerHttpParams,
) -> Result<CallServerHttpResult, AnyError> {
use hyper::{body, client::conn::Builder, Body, Request};
// We use Hyper directly here since reqwest doesn't support sockets/pipes.
// See https://github.com/seanmonstar/reqwest/issues/39
let socket = match &code_server {
Some(cs) => &cs.socket,
None => return Err(AnyError::from(NoAttachedServerError())),
};
let rw = get_socket_rw_stream(socket).await?;
let (mut request_sender, connection) = Builder::new()
.handshake(rw)
.await
.map_err(|e| wrap(e, "error establishing connection"))?;
// start the connection processing; it's shut down when the sender is dropped
tokio::spawn(connection);
let mut request_builder = Request::builder()
.method::<&str>(params.method.as_ref())
.uri(format!("http://127.0.0.1{}", params.path))
.header("Host", "127.0.0.1");
for (k, v) in params.headers {
request_builder = request_builder.header(k, v);
}
let request = request_builder
.body(Body::from(params.body.unwrap_or_default()))
.map_err(|e| wrap(e, "invalid request"))?;
let response = request_sender
.send_request(request)
.await
.map_err(|e| wrap(e, "error sending request"))?;
Ok(CallServerHttpResult {
status: response.status().as_u16(),
headers: response
.headers()
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
.collect(),
body: body::to_bytes(response)
.await
.map_err(|e| wrap(e, "error reading response body"))?
.to_vec(),
})
}
async fn handle_acquire_cli(
paths: &LauncherPaths,
http: &Arc<FallbackSimpleHttp>,
log: &log::Logger,
params: AcquireCliParams,
) -> Result<SpawnResult, AnyError> {
let update_service = UpdateService::new(log.clone(), http.clone());
let release = match params.commit_id {
Some(commit) => Release {
name: format!("{} CLI", PRODUCT_NAME_LONG),
commit,
platform: params.platform,
quality: params.quality,
target: TargetKind::Cli,
},
None => {
update_service
.get_latest_commit(params.platform, TargetKind::Cli, params.quality)
.await?
}
};
let cli = download_cli_into_cache(&paths.cli_cache, &release, &update_service).await?;
let file = tokio::fs::File::open(cli)
.await
.map_err(|e| wrap(e, "error opening cli file"))?;
handle_spawn::<_, DuplexStream>(log, params.spawn, Some(file), None, None).await
}
async fn handle_spawn<Stdin, StdoutAndErr>(
log: &log::Logger,
params: SpawnParams,
stdin: Option<Stdin>,
stdout: Option<StdoutAndErr>,
stderr: Option<StdoutAndErr>,
) -> Result<SpawnResult, AnyError>
where
Stdin: AsyncRead + Unpin + Send + 'static,
StdoutAndErr: AsyncWrite + Unpin + Send + 'static,
{
debug!(
log,