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
//! Syslog
//!
//! This crate provides facilities to send log messages via syslog.
//! It supports Unix sockets for local syslog, UDP and TCP for remote servers.
//!
//! Messages can be passed directly without modification, or in RFC 3164 or RFC 5424 format
//!
//! The code is available on [Github](https://github.com/Geal/rust-syslog)
//!
//! # Example
//!
//! ```
//! extern crate syslog;
//!
//! use syslog::{Facility,Severity};
//!
//! fn main() {
//!   match syslog::unix(Facility::LOG_USER) {
//!     Err(e)         => println!("impossible to connect to syslog: {:?}", e),
//!     Ok(writer) => {
//!       let r = writer.send(Severity::LOG_ALERT, "hello world");
//!       if r.is_err() {
//!         println!("error sending the log {}", r.err().expect("got error"));
//!       }
//!     }
//!   }
//! }
//! ```
#![crate_type = "lib"]

extern crate unix_socket;
extern crate libc;
extern crate time;
extern crate log;

use std::result::Result;
use std::io::{self, Write};
use std::env;
use std::collections::HashMap;
use std::net::{SocketAddr,ToSocketAddrs,UdpSocket,TcpStream};
use std::sync::{Arc, Mutex};
use std::path::Path;
use std::fmt;
use std::error::Error;

use libc::getpid;
use unix_socket::{UnixDatagram, UnixStream};
use log::{Log,LogRecord,LogMetadata,LogLevel,SetLoggerError};

mod facility;
pub use facility::Facility;

pub type Priority = u8;

/// RFC 5424 structured data
pub type StructuredData = HashMap<String, HashMap<String, String>>;


#[allow(non_camel_case_types)]
#[derive(Copy,Clone)]
pub enum Severity {
  LOG_EMERG,
  LOG_ALERT,
  LOG_CRIT,
  LOG_ERR,
  LOG_WARNING,
  LOG_NOTICE,
  LOG_INFO,
  LOG_DEBUG
}

enum LoggerBackend {
  /// Unix socket, temp file path, log file path
  Unix(UnixDatagram),
  UnixStream(Arc<Mutex<UnixStream>>),
  Udp(Box<UdpSocket>, SocketAddr),
  Tcp(Arc<Mutex<TcpStream>>)
}

#[derive(Debug)]
pub struct SyslogError {
    description: String,
}

impl Error for SyslogError {
    fn description(&self) -> &str {
        &self.description
    }

    fn cause(&self) -> Option<&Error> { None }
}

impl fmt::Display for SyslogError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description)
    }
}

/// Main logging structure
pub struct Logger {
  facility: Facility,
  hostname: Option<String>,
  process:  String,
  pid:      i32,
  s:        LoggerBackend
}

/// Returns a Logger using unix socket to target local syslog ( using /dev/log or /var/run/syslog)
pub fn unix(facility: Facility) -> Result<Box<Logger>, io::Error> {
    unix_custom(facility, "/dev/log").or_else(|e| if e.kind() == io::ErrorKind::NotFound {
        unix_custom(facility, "/var/run/syslog")
    } else {
        Err(e)
    })
}

/// Returns a Logger using unix socket to target local syslog at user provided path
pub fn unix_custom<P: AsRef<Path>>(facility: Facility, path: P) -> Result<Box<Logger>, io::Error> {
    let (process_name, pid) = get_process_info().unwrap();
    let sock = try!(UnixDatagram::unbound());
    match sock.connect(&path) {
        Ok(()) => {
            Ok(Box::new(Logger {
                facility: facility.clone(),
                hostname: None,
                process:  process_name,
                pid:      pid,
                s:        LoggerBackend::Unix(sock),
            }))
        },
        Err(ref e) if e.raw_os_error() == Some(libc::EPROTOTYPE) => {
            let sock = try!(UnixStream::connect(path));
            Ok(Box::new(Logger {
                facility: facility.clone(),
                hostname: None,
                process:  process_name,
                pid:      pid,
                s:        LoggerBackend::UnixStream(Arc::new(Mutex::new(sock))),
            }))
        },
        Err(e) => Err(e),
    }
}

/// returns a UDP logger connecting `local` and `server`
pub fn udp<T: ToSocketAddrs>(local: T, server: T, hostname:String, facility: Facility) -> Result<Box<Logger>, io::Error> {
  server.to_socket_addrs().and_then(|mut server_addr_opt| {
    server_addr_opt.next().ok_or(
      io::Error::new(
        io::ErrorKind::InvalidInput,
        "invalid server address"
      )
    )
  }).and_then(|server_addr| {
    UdpSocket::bind(local).map(|socket| {
      let (process_name, pid) = get_process_info().unwrap();
      Box::new(Logger {
        facility: facility.clone(),
        hostname: Some(hostname),
        process:  process_name,
        pid:      pid,
        s:        LoggerBackend::Udp(Box::new(socket), server_addr)
      })
    })
  })
}

/// returns a TCP logger connecting `local` and `server`
pub fn tcp<T: ToSocketAddrs>(server: T, hostname: String, facility: Facility) -> Result<Box<Logger>, io::Error> {
  TcpStream::connect(server).map(|socket| {
      let (process_name, pid) = get_process_info().unwrap();
      Box::new(Logger {
        facility: facility.clone(),
        hostname: Some(hostname),
        process:  process_name,
        pid:      pid,
        s:        LoggerBackend::Tcp(Arc::new(Mutex::new(socket)))
      })
  })
}

/// Unix socket Logger init function compatible with log crate
pub fn init_unix(facility: Facility, log_level: log::LogLevelFilter) -> Result<(), SetLoggerError> {
  log::set_logger(|max_level| {
    max_level.set(log_level);
    unix(facility).unwrap()
  })
}

/// Unix socket Logger init function compatible with log crate and user provided socket path
pub fn init_unix_custom<P: AsRef<Path>>(facility: Facility, log_level: log::LogLevelFilter, path: P) -> Result<(), SetLoggerError> {
    log::set_logger(|max_level| {
      max_level.set(log_level);
      unix_custom(facility, path).unwrap()
    })
}

/// UDP Logger init function compatible with log crate
pub fn init_udp<T: ToSocketAddrs>(local: T, server: T, hostname:String, facility: Facility, log_level: log::LogLevelFilter) -> Result<(), SetLoggerError> {
  log::set_logger(|max_level| {
    max_level.set(log_level);
    udp(local, server, hostname, facility).unwrap()
  })
}

/// TCP Logger init function compatible with log crate
pub fn init_tcp<T: ToSocketAddrs>(server: T, hostname: String, facility: Facility, log_level: log::LogLevelFilter) -> Result<(), SetLoggerError> {
  log::set_logger(|max_level| {
    max_level.set(log_level);
    tcp(server, hostname, facility).unwrap()
  })
}

/// Initializes logging subsystem for log crate
///
/// This tries to connect to syslog by following ways:
///
/// 1. Unix sockets /dev/log and /var/run/syslog (in this order)
/// 2. Tcp connection to 127.0.0.1:601
/// 3. Udp connection to 127.0.0.1:514
///
/// Note the last option usually (almost) never fails in this method. So
/// this method doesn't return error even if there is no syslog.
///
/// If `application_name` is `None` name is derived from executable name
pub fn init(facility: Facility, log_level: log::LogLevelFilter,
    application_name: Option<&str>)
    -> Result<(), SyslogError>
{
  let backend = unix(facility).map(|logger| logger.s)
    .or_else(|_| {
        TcpStream::connect(("127.0.0.1", 601))
        .map(|s| LoggerBackend::Tcp(Arc::new(Mutex::new(s))))
    })
    .or_else(|_| {
        let udp_addr = "127.0.0.1:514".parse().unwrap();
        UdpSocket::bind(("127.0.0.1", 0))
        .map(|s| LoggerBackend::Udp(Box::new(s), udp_addr))
    }).map_err(|e| SyslogError{ description: e.description().to_owned() })?;
  let (process_name, pid) = get_process_info().unwrap();
  log::set_logger(|max_level| {
    max_level.set(log_level);
    Box::new(Logger {
        facility: facility.clone(),
        hostname: None,
        process:  application_name
            .map(|v| v.to_string())
            .unwrap_or(process_name),
        pid:      pid,
        s:        backend,
    })
  }).map_err(|e| SyslogError{ description: e.description().to_owned() })
}

impl Logger {
  /// format a message as a RFC 3164 log message
  pub fn format_3164<T: fmt::Display>(&self, severity:Severity, message: T) -> String {
    if let Some(ref hostname) = self.hostname {
        format!("<{}>{} {} {}[{}]: {}",
          self.encode_priority(severity, self.facility),
          time::now().strftime("%b %d %T").unwrap(),
          hostname, self.process, self.pid, message)
    } else {
        format!("<{}>{} {}[{}]: {}",
          self.encode_priority(severity, self.facility),
          time::now().strftime("%b %d %T").unwrap(),
          self.process, self.pid, message)
    }
  }

  /// format RFC 5424 structured data as `([id (name="value")*])*`
  pub fn format_5424_structured_data(&self, data: StructuredData) -> String {
    if data.is_empty() {
      "-".to_string()
    } else {
      let mut res = String::new();
      for (id, params) in data.iter() {
        res = res + "["+id;
        for (name,value) in params.iter() {
          res = res + " " + name + "=\"" + value + "\"";
        }
        res = res + "]";
      }

      res
    }
  }

  /// format a message as a RFC 5424 log message
  pub fn format_5424<T: fmt::Display>(&self, severity:Severity, message_id: i32, data: StructuredData, message: T) -> String {
    let f =  format!("<{}> {} {} {} {} {} {} {} {}",
      self.encode_priority(severity, self.facility),
      1, // version
      time::now_utc().rfc3339(),
      self.hostname.as_ref().map(|x| &x[..]).unwrap_or("localhost"),
      self.process, self.pid, message_id,
      self.format_5424_structured_data(data), message);
    return f;
  }

  fn encode_priority(&self, severity: Severity, facility: Facility) -> Priority {
    return facility as u8 | severity as u8
  }

  /// Sends a basic log message of the format `<priority> message`
  pub fn send<T: fmt::Display>(&self, severity: Severity, message: T) -> Result<usize, io::Error> {
    let formatted =  format!("<{}> {}",
      self.encode_priority(severity, self.facility.clone()),
      message).into_bytes();
    self.send_raw(&formatted[..])
  }

  /// Sends a RFC 3164 log message
  pub fn send_3164<T: fmt::Display>(&self, severity: Severity, message: T) -> Result<usize, io::Error> {
    let formatted = self.format_3164(severity, message).into_bytes();
    self.send_raw(&formatted[..])
  }

  /// Sends a RFC 5424 log message
  pub fn send_5424<T: fmt::Display>(&self, severity: Severity, message_id: i32, data: StructuredData, message: T) -> Result<usize, io::Error> {
    let formatted = self.format_5424(severity, message_id, data, message).into_bytes();
    self.send_raw(&formatted[..])
  }

  /// Sends a message directly, without any formatting
  pub fn send_raw(&self, message: &[u8]) -> Result<usize, io::Error> {
    match self.s {
      LoggerBackend::Unix(ref dgram) => dgram.send(&message[..]),
      LoggerBackend::UnixStream(ref socket_wrap) => {
        let mut socket = socket_wrap.lock().unwrap();
        let null = [0 ; 1];
        socket.write(&message[..]).and_then(|_| socket.write(&null))
      },
      LoggerBackend::Udp(ref socket, ref addr)    => socket.send_to(&message[..], addr),
      LoggerBackend::Tcp(ref socket_wrap)         => {
        let mut socket = socket_wrap.lock().unwrap();
        socket.write(&message[..])
      }
    }
  }

  pub fn emerg<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_EMERG, message)
  }

  pub fn alert<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_ALERT, message)
  }

  pub fn crit<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_CRIT, message)
  }

  pub fn err<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_ERR, message)
  }

  pub fn warning<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_WARNING, message)
  }

  pub fn notice<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_NOTICE, message)
  }

  pub fn info<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_INFO, message)
  }

  pub fn debug<T: fmt::Display>(&self, message: T) -> Result<usize, io::Error> {
    self.send_3164(Severity::LOG_DEBUG, message)
  }

  pub fn process_name(&self) -> &String {
    &self.process
  }

  pub fn process_id(&self) -> i32 {
    self.pid
  }

  pub fn set_process_name(&mut self, name: String) {
    self.process = name
  }

  pub fn set_process_id(&mut self, id: i32) {
    self.pid = id
  }
  
  /// Changes facility
  pub fn set_facility(&mut self, facility: Facility) {
    self.facility = facility;
  }
}

#[allow(unused_variables,unused_must_use)]
impl Log for Logger {
  fn enabled(&self, metadata: &LogMetadata) -> bool {
    true
  }

  fn log(&self, record: &LogRecord) {
    let message = &(format!("{}", record.args()));
    match record.level() {
      LogLevel::Error => self.err(message),
      LogLevel::Warn  => self.warning(message),
      LogLevel::Info  => self.info(message),
      LogLevel::Debug => self.debug(message),
      LogLevel::Trace => self.debug(message)
    };
  }
}

fn get_process_info() -> Option<(String,i32)> {
  env::current_exe().ok().and_then(|path| {
    path.file_name().and_then(|os_name| os_name.to_str()).map(|name| name.to_string())
  }).map(|name| {
    let pid = unsafe { getpid() };
    (name, pid)
  })
}

#[test]
#[allow(unused_must_use)]
fn message() {
  use std::thread;
  use std::sync::mpsc::channel;

  let r = unix(Facility::LOG_USER);
  //let r = tcp("127.0.0.1:4242", "localhost".to_string(), Facility::LOG_USER);
  if r.is_ok() {
    let w = r.unwrap();
    let m:String = w.format_3164(Severity::LOG_ALERT, "hello");
    println!("test: {}", m);
    let r = w.send_3164(Severity::LOG_ALERT, "pouet");
    if r.is_err() {
      println!("error sending: {}", r.unwrap_err());
    }
    //assert_eq!(m, "<9> test hello".to_string());

    let data = Arc::new(w);
    let (tx, rx) = channel();
    for i in 0..3 {
      let shared = data.clone();
      let tx = tx.clone();
      thread::spawn(move || {
        //let mut logger = *shared;
        let message = &format!("sent from {}", i);
        shared.send_3164(Severity::LOG_DEBUG, message);
        tx.send(());
      });
    }

    for _ in 0..3 {
      rx.recv();
    }
  }
}