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
/// code to tickle various supervisors to enable the `zeronsd supervise` command.
/// this code is hard to read but fundamentally launchd and systemd are controlled through a
/// library called `tinytemplate` and of course serde.
use std::path::{Path, PathBuf};

use anyhow::anyhow;
use regex::Regex;
use serde::Serialize;
use tinytemplate::TinyTemplate;
use trust_dns_resolver::Name;

#[cfg(target_os = "linux")]
use std::os::unix::fs::PermissionsExt;

use crate::{
    cli::{StartArgs, UnsuperviseArgs},
    init::ConfigFormat,
};

#[cfg(target_os = "windows")]
const SUPERVISE_SYSTEM_DIR: &str = "";
#[cfg(target_os = "windows")]
const SERVICE_TEMPLATE: &str = "";
#[cfg(target_os = "windows")]
const OS_RELEASE_FILE: &str = "";
#[cfg(target_os = "windows")]
const ALPINE_INIT_DIR: &str = "";

#[cfg(target_os = "linux")]
const SUPERVISE_SYSTEM_DIR: &str = "/lib/systemd/system";
#[cfg(target_os = "linux")]
const OS_RELEASE_FILE: &str = "/etc/os-release";

#[cfg(target_os = "linux")]
const SYSTEMD_TEMPLATE: &str = r#"
[Unit]
Description=zeronsd for network {network}
Requires=zerotier-one.service
After=zerotier-one.service

[Service]
Type=simple
ExecStart={binpath} start -t {token} {{ if config }}-c {config} {{endif}}{{ if config_type_supplied }}--config-type {config_type} {{endif}}{{ if wildcard_names }}-w {{endif}}{{ if authtoken }}-s {authtoken} {{endif}}{{ if hosts_file }}-f {hosts_file} {{ endif }}{{ if domain }}-d {domain} {{ endif }}{network}
TimeoutStopSec=30
Restart=always

[Install]
WantedBy=default.target
"#;

#[cfg(target_os = "linux")]
const ALPINE_INIT_DIR: &str = "/etc/init.d";
#[cfg(target_os = "linux")]
const ALPINE_TEMPLATE: &str = r#"
#!/sbin/openrc-run

depend() \{
    need zerotier-one
    use network dns logger netmount
}

description="zeronsd for network {network}"
command="{binpath}"
command_args="start -t {token} {{ if config }}-c {config} {{endif}}{{ if config_type_supplied }}--config-type {config_type} {{endif}}{{ if wildcard_names }}-w {{endif}}{{ if authtoken }}-s {authtoken} {{endif}}{{ if hosts_file }}-f {hosts_file} {{ endif }}{{ if domain }}-d {domain} {{ endif }}{network}"
command_background="yes"
pidfile="/run/$RC_SVCNAME.pid"
"#;

#[cfg(target_os = "macos")]
const OS_RELEASE_FILE: &str = "";
#[cfg(target_os = "macos")]
const ALPINE_INIT_DIR: &str = "";
#[cfg(target_os = "macos")]
const SUPERVISE_SYSTEM_DIR: &str = "/Library/LaunchDaemons/";
#[cfg(target_os = "macos")]
const SERVICE_TEMPLATE: &str = r#"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key> <string>com.zerotier.nsd.{network}</string>

    <key>ProgramArguments</key>
    <array>
      <string>{binpath}</string>
      <string>start</string>
      <string>-t</string>
      <string>{token}</string>
      {{ if wildcard_names }}
      <string>-w</string>
      {{endif}}
      {{ if authtoken }}
      <string>-s</string>
      <string>{authtoken}</string>
      {{endif}}
      {{ if hosts_file }}
      <string>-f</string>
      <string>{hosts_file}</string>
      {{ endif }}
      {{ if domain }}
      <string>-d</string>
      <string>{domain}</string>
      {{ endif }}
      {{ if config }}
      <string>-c</string>
      <string>{config}</string>
      {{ endif }}
      {{ if config_type_supplied }}
      <string>--config-type</string>
      <string>{config_type}</string>
      {{ endif }}
      <string>{network}</string>
    </array>

    <key>UserName</key> <string>root</string>

    <key>RunAtLoad</key> <true/>

    <key>KeepAlive</key> <true/>

    <key>StandardErrorPath</key> <string>/var/log/zerotier/nsd/{network}.err</string>
    <key>StandardOutPath</key> <string>/var/log/zerotier/nsd/{network}.log</string>

  </dict>
    </plist>
"#;

#[derive(Serialize)]
pub struct Properties {
    pub binpath: String,
    pub domain: Option<String>,
    pub network: String,
    pub hosts_file: Option<PathBuf>,
    pub authtoken: Option<PathBuf>,
    pub token: PathBuf,
    pub config: Option<PathBuf>,
    pub config_type: ConfigFormat,
    pub config_type_supplied: bool,
    pub wildcard_names: bool,
    pub distro: Option<String>,
}

impl From<StartArgs> for Properties {
    fn from(args: StartArgs) -> Self {
        let launcher: crate::init::Launcher = args.clone().into();

        // FIXME rewrite this to use a struct init later
        Self::new(
            launcher.domain.as_deref(),
            &launcher.network_id.unwrap(),
            launcher.hosts.as_deref(),
            launcher.secret.as_deref(),
            launcher.token.as_deref(),
            launcher.wildcard,
            args.config.as_deref(),
            args.config_type,
        )
        .unwrap()
    }
}

impl From<UnsuperviseArgs> for Properties {
    fn from(args: UnsuperviseArgs) -> Self {
        Self::new(
            None,
            &args.network_id,
            None,
            None,
            None,
            false,
            None,
            ConfigFormat::YAML,
        )
        .unwrap()
    }
}

impl Default for Properties {
    fn default() -> Self {
        Self {
            wildcard_names: false,
            binpath: "zeronsd".to_string(),
            domain: None,
            network: String::new(),
            hosts_file: None,
            authtoken: None,
            config: None,
            config_type: ConfigFormat::YAML,
            config_type_supplied: false,
            token: PathBuf::new(),
            distro: None,
        }
    }
}

impl<'a> Properties {
    pub fn new(
        domain: Option<&'_ str>,
        network: &'_ str,
        hosts_file: Option<&'_ Path>,
        authtoken: Option<&'_ Path>,
        token: Option<&'_ Path>,
        wildcard_names: bool,
        config: Option<&'_ Path>,
        config_type: ConfigFormat,
    ) -> Result<Self, anyhow::Error> {
        let distro = if cfg!(target_os = "linux") {
            if let Ok(release) = std::fs::read_to_string(OS_RELEASE_FILE) {
                let id_regex = Regex::new(r#"\nID=(.+)\n"#)?;
                if let Some(caps) = id_regex.captures(&release) {
                    if let Some(distro) = caps.get(1) {
                        Some(distro.clone().as_str().to_string())
                    } else {
                        None
                    }
                } else {
                    return Err(anyhow!("Could not determine Linux distribution; you'll need to configure supervision manually. Sorry!"));
                }
            } else {
                return Err(anyhow!("Could not determine Linux distribution; you'll need to configure supervision manually. Sorry!"));
            }
        } else {
            None
        };

        Ok(Self {
            distro,
            wildcard_names,
            binpath: String::from(std::env::current_exe()?.to_string_lossy()),
            // make this garbage a macro later
            domain: match domain {
                Some(domain) => Some(String::from(domain)),
                None => None,
            },
            network: network.into(),
            hosts_file: match hosts_file {
                Some(hosts_file) => Some(hosts_file.to_owned()),
                None => None,
            },
            authtoken: match authtoken {
                Some(authtoken) => Some(authtoken.to_owned()),
                None => None,
            },
            token: token.unwrap_or(Path::new("")).to_owned(),
            config_type: config_type.clone(),
            config_type_supplied: config_type != ConfigFormat::YAML,
            config: match config {
                Some(config) => Some(config.to_owned()),
                None => None,
            },
        })
    }

    pub fn validate(&mut self) -> Result<(), anyhow::Error> {
        self.config = match self.config.clone() {
            Some(config) => match config.canonicalize() {
                Ok(res) => Some(res),
                Err(e) => return Err(anyhow!("Could not find token file: {}", e)),
            },
            None => None,
        };

        self.token = match self.token.canonicalize() {
            Ok(res) => res,
            Err(e) => return Err(anyhow!("Could not find token file: {}", e)),
        };

        let tstat = match std::fs::metadata(self.token.clone()) {
            Ok(ts) => ts,
            Err(e) => {
                return Err(anyhow!(
                    "Could not stat token file {}: {}",
                    self.token.display(),
                    e
                ))
            }
        };

        if !tstat.is_file() {
            return Err(anyhow!("Token file {} is not a file", self.token.display()));
        }

        if self.network.len() != 16 {
            return Err(anyhow!("Network ID must be 16 characters"));
        }

        if let Some(hosts_file) = self.hosts_file.clone() {
            let hstat = match std::fs::metadata(hosts_file.clone()) {
                Ok(hs) => hs,
                Err(e) => {
                    return Err(anyhow!(
                        "Could not stat hosts file {}: {}",
                        hosts_file.display(),
                        e
                    ))
                }
            };

            if !hstat.is_file() {
                return Err(anyhow!("Hosts file {} is not a file", hosts_file.display()));
            }

            self.hosts_file = Some(hosts_file.canonicalize()?);
        }

        if let Some(domain) = self.domain.clone() {
            if domain.trim().len() == 0 {
                return Err(anyhow!("Domain name cannot be empty"));
            }

            if let Err(e) = Name::parse(&domain, None) {
                return Err(anyhow!("Domain name is invalid: {}", e));
            }
        }

        if let Some(authtoken) = self.authtoken.clone() {
            let hstat = match std::fs::metadata(authtoken.clone()) {
                Ok(hs) => hs,
                Err(e) => {
                    return Err(anyhow!(
                        "Could not stat authtoken file {}: {}",
                        authtoken.display(),
                        e
                    ))
                }
            };

            if !hstat.is_file() {
                return Err(anyhow!(
                    "authtoken file {} is not a file",
                    authtoken.display()
                ));
            }

            self.authtoken = Some(authtoken.canonicalize()?);
        }

        Ok(())
    }

    pub fn supervise_template(&self) -> Result<String, anyhow::Error> {
        let template = self.get_service_template();

        let mut t = TinyTemplate::new();
        t.add_template("supervise", template)?;
        match t.render("supervise", self) {
            Ok(x) => Ok(x),
            Err(e) => Err(anyhow!(e)),
        }
    }

    #[cfg(target_os = "linux")]
    fn get_service_template(&self) -> &str {
        match self.distro.as_deref() {
            Some("alpine") => ALPINE_TEMPLATE.trim(),
            _ => SYSTEMD_TEMPLATE,
        }
    }

    #[cfg(target_os = "windows")]
    fn get_service_template(&self) -> &str {
        return SERVICE_TEMPLATE;
    }

    #[cfg(target_os = "macos")]
    fn get_service_template(&self) -> &str {
        return SERVICE_TEMPLATE;
    }

    #[cfg(target_os = "windows")]
    fn service_name(&self) -> String {
        return String::new();
    }

    #[cfg(target_os = "linux")]
    fn service_name(&self) -> String {
        match self.distro.as_deref() {
            Some("alpine") => format!("zeronsd-{}", self.network),
            _ => format!("zeronsd-{}.service", self.network),
        }
    }

    #[cfg(target_os = "macos")]
    fn service_name(&self) -> String {
        format!("com.zerotier.nsd.{}.plist", self.network)
    }

    fn service_path(&self) -> PathBuf {
        let dir = match self.distro.as_deref() {
            Some("alpine") => ALPINE_INIT_DIR,
            _ => SUPERVISE_SYSTEM_DIR,
        };
        PathBuf::from(dir).join(self.service_name())
    }

    pub fn install_supervisor(&mut self) -> Result<(), anyhow::Error> {
        self.validate()?;

        if cfg!(target_os = "linux") {
            #[cfg(target_os = "linux")]
            let executable = self.distro.as_deref() == Some("alpine");

            let template = self.supervise_template()?;
            let service_path = self.service_path();

            match std::fs::write(service_path.clone(), template) {
                Ok(_) => {}
                Err(e) => {
                    return Err(anyhow!(
                        "Could not write the template {}; are you root? ({})",
                        service_path
                            .to_str()
                            .expect("Could not coerce service path to string"),
                        e,
                    ))
                }
            };

            #[cfg(target_os = "linux")]
            if executable {
                let mut perms = std::fs::metadata(service_path.clone())?.permissions();
                perms.set_mode(0o755);
                std::fs::set_permissions(service_path.clone(), perms)?;
            }

            let systemd_help = format!("Don't forget to `systemctl daemon-reload`, `systemctl enable zeronsd-{}` and `systemctl start zeronsd-{}`.", self.network, self.network);
            let alpine_help = format!(
                "Don't forget to `rc-update add zeronsd-{}` and `rc-service zeronsd-{} start`",
                self.network, self.network
            );

            let help = match self.distro.as_deref() {
                Some("alpine") => alpine_help,
                _ => systemd_help,
            };

            eprintln!(
                "Service definition written to {}.\n{}",
                service_path
                    .to_str()
                    .expect("Could not coerce service path to string"),
                help,
            );
        } else if cfg!(target_os = "macos") {
            let template = self.supervise_template()?;
            let service_path = self.service_path();

            match std::fs::write(&service_path, template) {
                Ok(_) => {}
                Err(e) => {
                    return Err(anyhow!(
                        "Could not write the template {}; are you root? ({})",
                        service_path
                            .to_str()
                            .expect("Could not coerce service path to string"),
                        e,
                    ))
                }
            };

            eprintln!(
                "Service definition written to {}.\nTo start the service, run:\nsudo launchctl load {}",
                service_path.to_str().expect("Could not coerce service path to string"),
                service_path.to_str().expect("Could not coerce service path to string")
            );
        } else {
            return Err(anyhow!("Your platform is not supported for this command"));
        }
        Ok(())
    }

    pub fn uninstall_supervisor(&self) -> Result<(), anyhow::Error> {
        if cfg!(target_os = "linux") {
            match std::fs::remove_file(self.service_path()) {
                Ok(_) => {}
                Err(e) => {
                    return Err(anyhow!(
                        "Could not uninstall supervisor unit file ({}): {}",
                        self.service_path()
                            .to_str()
                            .expect("Could not coerce service path to string"),
                        e,
                    ))
                }
            };
            eprintln!(
                "Service definition removed from {}.\nDon't forget to reload systemd:\nsudo systemctl daemon-reload",
                self.service_path().to_str().expect("Could not coerce service path to string"),
            );
        } else if cfg!(target_os = "macos") {
            match std::fs::remove_file(self.service_path()) {
                Ok(_) => {}
                Err(e) => {
                    return Err(anyhow!(
                        "Could not uninstall supervisor unit file ({}): {}",
                        self.service_path()
                            .to_str()
                            .expect("Could not coerce service path to string"),
                        e,
                    ))
                }
            };

            eprintln!(
                "Service definition removed from {}.\nDon't forget to stop it:\nsudo launchctl remove {}",
                self.service_path().to_str().expect("Could not coerce service path to string"),
                self.service_name().replace(".plist", "")
            );
        } else {
            return Err(anyhow!("Your platform is not supported for this command"));
        }
        Ok(())
    }
}