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
use std::{
    collections::HashMap,
    os::unix::prelude::{MetadataExt, PermissionsExt},
    path::{Path, PathBuf},
    time,
};

use anyhow::{bail, Context};
use bytesize::ByteSize;
use nix::{sys::stat, unistd};
use serde::{de::Error as SerdeError, Deserialize, Deserializer};
use url::Url;

use crate::{common::non_nul_string::NonNulString, runtime::repository::RepositoryId};

/// Runtime configuration
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Directory with unpacked containers.
    pub run_dir: PathBuf,
    /// Directory where rw data of container shall be stored
    pub data_dir: PathBuf,
    /// Directory for logfile
    pub log_dir: PathBuf,
    /// Top level cgroup name
    pub cgroup: NonNulString,
    /// Event loop buffer size
    #[serde(default = "default_event_buffer_size")]
    pub event_buffer_size: usize,
    /// Notification buffer size
    #[serde(default = "default_notification_buffer_size")]
    pub notification_buffer_size: usize,
    /// Loop device timeout
    #[serde(with = "humantime_serde", default = "default_loop_device_timeout")]
    pub loop_device_timeout: time::Duration,
    /// Token validity
    #[serde(with = "humantime_serde", default = "default_token_validity")]
    pub token_validity: time::Duration,
    /// Repositories
    #[serde(default)]
    pub repositories: HashMap<RepositoryId, Repository>,
    /// Debugging options
    pub debug: Option<Debug>,
}

/// Repository type
#[derive(Clone, Debug, Deserialize)]
pub enum RepositoryType {
    /// Directory based
    #[serde(rename = "fs")]
    Fs {
        /// Path to the repository
        dir: PathBuf,
    },
    /// Memory based
    #[serde(rename = "mem")]
    Memory,
}

/// Repository configuration
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Repository {
    /// Repository type: fs or mem.
    pub r#type: RepositoryType,
    /// Optional key for this repository.
    pub key: Option<PathBuf>,
    /// Mount the containers from this repository on runtime start. Default: false.
    #[serde(default)]
    pub mount_on_start: bool,
    /// Maximum number of containers that can be stored in this repository.
    pub capacity_num: Option<u32>,
    /// Maximum total size of all containers in this repository.
    #[serde(default, deserialize_with = "bytesize")]
    pub capacity_size: Option<u64>,
}

/// Container debug settings
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Debug {
    /// Console configuration
    #[serde(deserialize_with = "console")]
    pub console: Url,
    /// Strace options
    pub strace: Option<debug::Strace>,
    /// perf options
    pub perf: Option<debug::Perf>,
}

/// Container debug facilities
pub mod debug {
    use serde::Deserialize;
    use std::path::PathBuf;

    /// strace output configuration
    #[derive(Clone, Debug, Deserialize)]
    #[serde(rename_all(deserialize = "snake_case"))]
    pub enum StraceOutput {
        /// Log to a file in log_dir
        File,
        /// Log the runtimes logging system
        Log,
    }

    /// Strace debug options
    #[derive(Clone, Debug, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Strace {
        /// Log to a file in log_dir
        pub output: StraceOutput,
        /// Path to the strace binary
        pub path: Option<PathBuf>,
        /// Additional strace command line flags options
        pub flags: Option<String>,
        /// Include strace output before final execve
        pub include_runtime: Option<bool>,
    }

    /// perf profiling options
    #[derive(Clone, Debug, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Perf {
        /// Path to the perf binary
        pub path: Option<PathBuf>,
        /// Optional additional flags
        pub flags: Option<String>,
    }
}

impl Config {
    /// Validate the configuration
    pub(crate) fn check(&self) -> anyhow::Result<()> {
        check_rw_directory(&self.run_dir).context("checking run_dir")?;
        check_rw_directory(&self.data_dir).context("checking data_dir")?;
        check_rw_directory(&self.log_dir).context("checking log_dir")?;
        Ok(())
    }
}

/// Checks that the directory exists and that it is readable and writeable
fn check_rw_directory(path: &Path) -> anyhow::Result<()> {
    if !path.exists() {
        bail!("{} does not exist", path.display());
    } else if !is_rw(path) {
        bail!("{} is not read and/or writeable", path.display());
    } else {
        Ok(())
    }
}

/// Return true if path is read and writeable
fn is_rw(path: &Path) -> bool {
    match std::fs::metadata(path) {
        Ok(stat) => {
            let same_uid = stat.uid() == unistd::getuid().as_raw();
            let same_gid = stat.gid() == unistd::getgid().as_raw();
            let mode = stat::Mode::from_bits_truncate(stat.permissions().mode());

            let is_readable = (same_uid && mode.contains(stat::Mode::S_IRUSR))
                || (same_gid && mode.contains(stat::Mode::S_IRGRP))
                || mode.contains(stat::Mode::S_IROTH);
            let is_writable = (same_uid && mode.contains(stat::Mode::S_IWUSR))
                || (same_gid && mode.contains(stat::Mode::S_IWGRP))
                || mode.contains(stat::Mode::S_IWOTH);

            is_readable && is_writable
        }
        Err(_) => false,
    }
}

/// Validate the console url schemes are all "tcp" or "unix"
fn console<'de, D>(deserializer: D) -> Result<Url, D::Error>
where
    D: Deserializer<'de>,
{
    let url = Url::deserialize(deserializer)?;
    if url.scheme() != "tcp" && url.scheme() != "unix" {
        Err(D::Error::custom("console scheme must be tcp or unix"))
    } else {
        Ok(url)
    }
}

/// Parse human readable byte sizes.
fn bytesize<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let size: Option<String> = Option::<String>::deserialize(deserializer)?;
    if let Some(size) = size {
        Ok(Some(
            size.parse::<ByteSize>()
                .map_err(D::Error::custom)
                .map(|s| s.as_u64())?,
        ))
    } else {
        Ok(None)
    }
}

const fn default_loop_device_timeout() -> time::Duration {
    time::Duration::from_secs(10)
}

const fn default_event_buffer_size() -> usize {
    256
}

const fn default_notification_buffer_size() -> usize {
    128
}

const fn default_token_validity() -> time::Duration {
    time::Duration::from_secs(60)
}

#[test]
#[allow(clippy::unwrap_used)]
fn console_url() {
    let config = r#"
run_dir = "target/northstar/run"
data_dir = "target/northstar/data"
log_dir = "target/northstar/logs"
cgroup = "northstar"

[debug]
console = "tcp://localhost:4200"
"#;

    toml::from_str::<Config>(config).unwrap();

    // Invalid url
    let config = r#"
run_dir = "target/northstar/run"
data_dir = "target/northstar/data"
log_dir = "target/northstar/logs"
cgroup = "northstar"

[debug]
console = "http://localhost:4200"
"#;

    assert!(toml::from_str::<Config>(config).is_err());
}

#[test]
#[allow(clippy::unwrap_used)]
fn repository_size() {
    let config = r#"
run_dir = "target/northstar/run"
data_dir = "target/northstar/data"
log_dir = "target/northstar/logs"
cgroup = "northstar"

[repositories.memory]
type = "mem"
key = "examples/northstar.pub"
capacity_num = 10
capacity_size = "100MB"
"#;
    toml::from_str::<Config>(config).unwrap();
}