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
use crate::{
api::{self, codec::Framed, VERSION},
common::container::Container,
runtime::{
events::{CGroupEvent, ContainerEvent, Event, EventTx},
exit_status::ExitStatus,
repository::RepositoryId,
runtime::NotificationTx,
token::Token,
},
};
use anyhow::{bail, Context, Result};
use api::model;
use async_stream::stream;
use bytes::{Buf, Bytes};
use futures::{
future::join_all,
stream::{self, FuturesUnordered},
Future, StreamExt,
};
use listener::Listener;
use log::{debug, info, trace, warn};
use semver::Comparator;
use std::{cmp::min, fmt, path::Path, unreachable};
use tokio::{
io::{self, AsyncRead, AsyncReadExt, AsyncWrite},
pin, select,
sync::{broadcast, mpsc, oneshot},
task, time,
};
use tokio_util::{either::Either, io::ReaderStream, sync::CancellationToken};
use url::Url;
pub use crate::npk::manifest::console::{Configuration, Permission, Permissions};
mod listener;
mod throttle;
const DEFAULT_REQUESTS_PER_SECOND: usize = 1024;
const DEFAULT_MAX_REQUEST_SIZE: usize = 1024 * 1024;
const DEFAULT_MAX_INSTALL_STREAM_SIZE: u64 = 256 * 1_000_000;
const DEFAULT_NPK_STREAM_TIMEOUT: u64 = 5;
#[derive(Debug)]
pub(crate) enum Request {
Request(model::Request),
Install(RepositoryId, mpsc::Receiver<Bytes>),
}
pub(crate) struct Console {
event_tx: EventTx,
notification_tx: NotificationTx,
stop: CancellationToken,
tasks: Vec<task::JoinHandle<()>>,
}
impl Console {
pub(super) fn new(event_tx: EventTx, notification_tx: NotificationTx) -> Console {
Self {
event_tx,
notification_tx,
stop: CancellationToken::new(),
tasks: Vec::new(),
}
}
pub(super) async fn listen(
&mut self,
url: &Url,
configuration: &Configuration,
token_validity: time::Duration,
) -> Result<()> {
let event_tx = self.event_tx.clone();
let notification_tx = self.notification_tx.clone();
let configuration = configuration.clone();
let stop = self.stop.clone();
debug!(
"Starting console on {} with permissions \"{}\"",
url, configuration.permissions
);
let task = match Listener::new(url)
.await
.context("failed to start console listener")?
{
Listener::Tcp(listener) => task::spawn(async move {
serve(
|| listener.accept(),
event_tx,
notification_tx,
stop,
configuration,
token_validity,
)
.await
}),
Listener::Unix(listener) => task::spawn(async move {
serve(
|| listener.accept(),
event_tx,
notification_tx,
stop,
configuration,
token_validity,
)
.await
}),
};
self.tasks.push(task);
Ok(())
}
pub(super) async fn shutdown(self) -> Result<()> {
self.stop.cancel();
join_all(self.tasks).await;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn connection<T: AsyncRead + AsyncWrite + Unpin>(
stream: T,
peer: Peer,
stop: CancellationToken,
container: Option<Container>,
configuration: Configuration,
token_validity: time::Duration,
event_tx: EventTx,
mut notification_rx: broadcast::Receiver<(Container, ContainerEvent)>,
timeout: Option<time::Duration>,
) -> Result<()> {
let permissions = &configuration.permissions;
if let Some(container) = &container {
debug!(
"Container {} connected with permissions {}",
container, permissions
);
} else {
debug!("Client {} connected with permissions {}", peer, permissions);
}
let max_request_size = configuration
.max_request_size
.unwrap_or(DEFAULT_MAX_REQUEST_SIZE);
let stream = api::codec::framed_with_max_length(stream, max_request_size);
let max_requests_per_sec = configuration
.max_requests_per_sec
.unwrap_or(DEFAULT_REQUESTS_PER_SECOND);
let mut stream =
throttle::Throttle::new(stream, max_requests_per_sec, time::Duration::from_secs(1));
let connect = stream.next();
let timeout = timeout.unwrap_or_else(|| time::Duration::from_secs(u64::MAX));
let connect = time::timeout(timeout, connect);
let (protocol_version, notifications) = match connect.await {
Ok(Some(Ok(m))) => match m {
model::Message::Connect {
connect:
model::Connect {
version,
subscribe_notifications,
},
} => (version, subscribe_notifications),
_ => {
warn!("{}: Received {:?} instead of Connect", peer, m);
return Ok(());
}
},
Ok(Some(Err(e))) => {
warn!("{}: Connection error: {}", peer, e);
return Ok(());
}
Ok(None) => {
info!("{}: Connection closed before connect", peer);
return Ok(());
}
Err(_) => {
info!("{}: Connection timed out", peer);
return Ok(());
}
};
let version_request = semver::VersionReq {
comparators: vec![Comparator {
op: semver::Op::GreaterEq,
major: VERSION.major,
minor: Some(VERSION.minor),
patch: None,
pre: semver::Prerelease::default(),
}],
};
let protocol_version = &protocol_version;
if !version_request.matches(&(protocol_version.into())) {
warn!(
"{}: Client connected with insufficent protocol version {}. Expected {}. Disconnecting...",
peer, protocol_version, VERSION
);
let connect_nack = model::ConnectNack::InvalidProtocolVersion { version: VERSION };
let message = model::Message::ConnectNack { connect_nack };
stream.send(message).await.ok();
return Ok(());
}
if notifications && !permissions.contains(&Permission::Notifications) {
warn!(
"{}: Requested notifications without notification permission. Disconnecting...",
peer
);
let connect_nack = model::ConnectNack::PermissionDenied;
let message = model::Message::ConnectNack { connect_nack };
stream.send(message).await.ok();
return Ok(());
}
let connect_ack = model::ConnectAck {
configuration: configuration.clone(),
};
let message = model::Message::ConnectAck { connect_ack };
if let Err(e) = stream.send(message).await {
warn!("{}: Connection error: {}", peer, e);
return Ok(());
}
let notifications = if notifications {
debug!("Client {} subscribed to notifications", peer);
let stream = stream! { loop { yield notification_rx.recv().await; } };
Either::Left(stream)
} else {
drop(notification_rx);
Either::Right(stream::pending())
};
pin!(notifications);
loop {
select! {
_ = stop.cancelled() => {
info!("{}: Closing connection", peer);
break;
}
notification = notifications.next() => {
let notification = match notification {
Some(Ok((container, event))) => (container, event).into(),
Some(Err(broadcast::error::RecvError::Closed)) => break,
Some(Err(broadcast::error::RecvError::Lagged(_))) => {
warn!("Client connection lagged notifications. Closing");
break;
}
None => break,
};
if let Err(e) = stream
.send(api::model::Message::Notification {notification })
.await
{
warn!("{}: Connection error: {}", peer, e);
break;
}
}
item = stream.next() => {
match item {
Some(Ok(model::Message::Request { request })) => {
trace!("{}: --> {:?}", peer, request);
let response = match process_request(&peer, &mut stream, &stop, &configuration, &event_tx, token_validity, request).await {
Ok(response) => response,
Err(e) => {
warn!("Failed to process request: {}", e);
break;
}
};
trace!("{}: <-- {:?}", peer, response);
if let Err(e) = stream.send(response).await {
warn!("{}: Connection error: {}", peer, e);
break;
}
}
Some(Ok(message)) => {
warn!("{}: Unexpected message: {:?}. Disconnecting...", peer, message);
break;
}
Some(Err(e)) => {
warn!("{}: Connection error: {:?}. Disconnecting...", peer, e);
break;
}
None => break,
}
}
}
}
info!("{}: Connection closed", peer);
Ok(())
}
}
async fn process_request<S>(
peer: &Peer,
stream: &mut Framed<S>,
stop: &CancellationToken,
configuration: &Configuration,
event_loop: &EventTx,
token_validity: time::Duration,
request: model::Request,
) -> Result<model::Message>
where
S: AsyncRead + Unpin,
{
let required_permission = match &request {
model::Request::Ident { .. } => Permission::Ident,
model::Request::Inspect { .. } => Permission::Inspect,
model::Request::Install { .. } => Permission::Install,
model::Request::Kill { .. } => Permission::Kill,
model::Request::List => Permission::List,
model::Request::Mount { .. } => Permission::Mount,
model::Request::Repositories => Permission::Repositories,
model::Request::Shutdown => Permission::Shutdown,
model::Request::Start {
arguments,
environment,
..
} if arguments.is_empty() && environment.is_empty() => Permission::Start,
model::Request::Start { .. } => Permission::StartWithArgsAndEnv,
model::Request::TokenCreate { .. } => Permission::TokenCreate,
model::Request::TokenVerify { .. } => Permission::TokenVerification,
model::Request::Umount { .. } => Permission::Umount,
model::Request::Uninstall { .. } => Permission::Uninstall,
};
let permissions = &configuration.permissions;
if !permissions.contains(&required_permission) {
return Ok(model::Message::Response {
response: model::Response::PermissionDenied(request),
});
}
let (reply_tx, reply_rx) = oneshot::channel();
match request {
model::Request::Ident => {
let ident = match peer {
#[allow(clippy::unwrap_used)]
Peer::Extern(_) => Container::try_from("extern:0.0.0").unwrap(),
Peer::Container(container) => container.clone(),
};
let response = api::model::Response::Ident(ident);
reply_tx.send(response).ok();
}
model::Request::Install {
repository,
mut size,
} => {
debug!(
"{}: Received installation request with size {}",
peer,
bytesize::ByteSize::b(size)
);
let max_install_stream_size = configuration
.max_npk_install_size
.unwrap_or(DEFAULT_MAX_INSTALL_STREAM_SIZE);
if size > max_install_stream_size {
bail!("npk size too large");
}
info!("{}: Using repository \"{}\"", peer, repository);
let (tx, rx) = mpsc::channel(10);
let request = Request::Install(repository, rx);
trace!(" {:?} -> event loop", request);
let event = Event::Console(request, reply_tx);
event_loop.send(event).await?;
if !stream.read_buffer().is_empty() {
let available = stream.read_buffer().len();
let read_max = min(size as usize, available);
let buffer = stream.read_buffer_mut().copy_to_bytes(read_max);
size -= buffer.len() as u64;
tx.send(buffer).await.ok();
}
let mut take = ReaderStream::with_capacity(stream.get_mut().take(size), 1024 * 1024);
let timeout = time::Duration::from_secs(
configuration
.npk_stream_timeout
.unwrap_or(DEFAULT_NPK_STREAM_TIMEOUT),
);
while let Some(buf) = time::timeout(timeout, take.next())
.await
.context("npk stream timeout")?
{
let buf = buf.context("npk steam")?;
tx.send(buf).await.ok();
}
}
model::Request::TokenCreate { target, shared } => {
let user = match peer {
Peer::Extern(_) => "extern",
Peer::Container(container) => container.name().as_ref(),
};
info!(
"Creating token for user \"{}\" and target \"{}\" with shared \"{}\"",
user,
target,
hex::encode(&shared)
);
let token: Vec<u8> = Token::new(token_validity, user, target, shared).into();
let token = api::model::Token::from(token);
let response = api::model::Response::Token(token);
reply_tx.send(response).ok();
}
model::Request::TokenVerify {
token,
user,
shared,
} => {
let target = match peer {
Peer::Extern(_) => "extern",
Peer::Container(container) => container.name().as_ref(),
};
info!(
"Verifiying token for user \"{}\" and target \"{}\" with shared \"{}\"",
user,
target,
hex::encode(&shared)
);
let token = Token::from((token_validity, token.as_ref().to_vec()));
let result = token.verify(user, target, &shared).into();
let response = api::model::Response::TokenVerification(result);
reply_tx.send(response).ok();
}
request => {
let message = Request::Request(request);
trace!(" {:?} -> event loop", message);
let event = Event::Console(message, reply_tx);
event_loop.send(event).await?;
}
}
(select! {
reply = reply_rx => reply.context("failed to receive reply"),
_ = stop.cancelled() => bail!("shutdown"), })
.map(|response| {
trace!(" {:?} <- event loop", response);
response
})
.map(|response| model::Message::Response { response })
}
async fn serve<AcceptFun, AcceptFuture, Stream, Addr>(
accept: AcceptFun,
event_tx: EventTx,
notification_tx: broadcast::Sender<(Container, ContainerEvent)>,
stop: CancellationToken,
configuration: Configuration,
token_validity: time::Duration,
) where
AcceptFun: Fn() -> AcceptFuture,
AcceptFuture: Future<Output = Result<(Stream, Addr), io::Error>>,
Stream: AsyncWrite + AsyncRead + Unpin + Send + 'static,
Addr: Into<Peer>,
{
let mut connections = FuturesUnordered::new();
loop {
select! {
_ = connections.next(), if !connections.is_empty() => (), connection = accept(), if !event_tx.is_closed() && !stop.is_cancelled() => {
match connection {
Ok((stream, client)) => {
connections.push(
task::spawn(Console::connection(
stream,
client.into(),
stop.clone(),
None,
configuration.clone(),
token_validity,
event_tx.clone(),
notification_tx.subscribe(),
Some(time::Duration::from_secs(10)),
)));
}
Err(e) => {
warn!("Error listening: {:?}", e);
break;
}
}
}
_ = stop.cancelled() => {
if !connections.is_empty() {
debug!("Waiting for open connections");
while connections.next().await.is_some() {};
}
break;
}
}
}
debug!("Closed listener");
}
pub enum Peer {
Extern(Url),
Container(Container),
}
impl From<std::net::SocketAddr> for Peer {
fn from(socket: std::net::SocketAddr) -> Self {
match socket.ip() {
std::net::IpAddr::V4(ip) => Url::parse(&format!("tcp://{}:{}", ip, socket.port()))
.map(Peer::Extern)
.expect("internal error"),
std::net::IpAddr::V6(ip) => Url::parse(&format!("tcp://[{}]:{}", ip, socket.port()))
.map(Peer::Extern)
.expect("internal error"),
}
}
}
impl From<tokio::net::unix::SocketAddr> for Peer {
fn from(socket: tokio::net::unix::SocketAddr) -> Self {
let path = socket
.as_pathname()
.unwrap_or_else(|| Path::new("unnamed"))
.display();
Url::parse(&format!("unix://{path}"))
.map(Peer::Extern)
.expect("invalid url")
}
}
impl fmt::Display for Peer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Peer::Extern(url) => write!(f, "Remote({url})"),
Peer::Container(container) => write!(f, "Container({container})"),
}
}
}
impl From<ExitStatus> for model::ExitStatus {
fn from(e: ExitStatus) -> Self {
match e {
ExitStatus::Exit(code) => api::model::ExitStatus::Exit { code },
ExitStatus::Signalled(signal) => api::model::ExitStatus::Signalled {
signal: signal as u32,
},
}
}
}
impl From<(Container, ContainerEvent)> for model::Notification {
fn from(p: (Container, ContainerEvent)) -> model::Notification {
let container = p.0.clone();
match p.1 {
ContainerEvent::Started => api::model::Notification::Started(container),
ContainerEvent::Exit(status) => {
api::model::Notification::Exit(container, status.into())
}
ContainerEvent::Installed => api::model::Notification::Install(container),
ContainerEvent::Uninstalled => api::model::Notification::Uninstall(container),
ContainerEvent::CGroup(event) => match event {
CGroupEvent::Memory(memory) => api::model::Notification::CGroup(
container,
api::model::CgroupNotification::Memory(api::model::MemoryNotification {
low: memory.low,
high: memory.high,
max: memory.max,
oom: memory.oom,
oom_kill: memory.oom_kill,
}),
),
},
}
}
}