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
// Just a quick hack to get logging into syslog. Longer term,
// this should be done in pam-bindings: https://github.com/anowell/pam-rs/pull/12

use anyhow::{anyhow, Result};
use std::env;
use std::fmt::Display;
use syslog::{Facility, Formatter3164, Logger, LoggerBackend};

pub trait Log {
    fn debug<S: Display>(&mut self, message: S) -> Result<()>;
    fn info<S: Display>(&mut self, message: S) -> Result<()>;
    fn error<S: Display>(&mut self, message: S) -> Result<()>;
}

pub struct PrintLog;

impl Log for PrintLog {
    fn debug<S: Display>(&mut self, message: S) -> Result<()> {
        print!("DEBUG: {}", message);
        Ok(())
    }

    fn info<S: Display>(&mut self, message: S) -> Result<()> {
        print!("INFO: {}", message);
        Ok(())
    }

    fn error<S: Display>(&mut self, message: S) -> Result<()> {
        print!("ERROR: {}", message);
        Ok(())
    }
}

pub struct SyslogLogger {
    log: Logger<LoggerBackend, Formatter3164>,
    prefix: String,
    debug: bool,
}

impl SyslogLogger {
    pub(crate) fn new(service_name: &str, debug: bool) -> Self {
        match syslog::unix(Formatter3164 {
            facility: Facility::LOG_AUTHPRIV,
            hostname: None,
            process: process_name().unwrap_or("unknown".into()),
            pid: std::process::id(),
        }) {
            Ok(log) => SyslogLogger {
                log,
                prefix: format!("pam_ssh_agent({}:auth): ", service_name),
                debug,
            },
            Err(e) => panic!("Failed to create syslog: {:?}", e),
        }
    }
}

impl Log for SyslogLogger {
    fn debug<S: Display>(&mut self, message: S) -> Result<()> {
        if !self.debug {
            return Ok(());
        }
        self.log
            .info(format!("{}{}", self.prefix, message))
            .map_err(|e| anyhow!("failed to log: {:?}", e))
    }

    fn info<S: Display>(&mut self, message: S) -> Result<()> {
        self.log
            .info(format!("{}{}", self.prefix, message))
            .map_err(|e| anyhow!("failed to log: {:?}", e))
    }

    fn error<S: Display>(&mut self, message: S) -> Result<()> {
        self.log
            .err(format!("{}{}", self.prefix, message))
            .map_err(|e| anyhow!("failed to log: {:?}", e))
    }
}

fn process_name() -> Result<String> {
    Ok(env::current_exe()?
        .file_name()
        .ok_or(anyhow!("no filename"))?
        .to_string_lossy()
        .into())
}