tor_log.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // Copyright (c) 2016-2018, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. // Note that these functions are untested due to the fact that there are no
  4. // return variables to test and they are calling into a C API.
  5. /// The related domain which the logging message is relevant. For example,
  6. /// log messages relevant to networking would use LogDomain::LdNet, whereas
  7. /// general messages can use LdGeneral.
  8. #[derive(Eq, PartialEq)]
  9. pub enum LogDomain {
  10. Net,
  11. General,
  12. }
  13. /// The severity level at which to log messages.
  14. #[derive(Eq, PartialEq)]
  15. pub enum LogSeverity {
  16. Notice,
  17. Warn,
  18. }
  19. /// Main entry point for Rust modules to log messages.
  20. ///
  21. /// # Inputs
  22. ///
  23. /// * A `severity` of type LogSeverity, which defines the level of severity the
  24. /// message will be logged.
  25. /// * A `domain` of type LogDomain, which defines the domain the log message
  26. /// will be associated with.
  27. /// * A `function` of type &str, which defines the name of the function where
  28. /// the message is being logged. There is a current RFC for a macro that
  29. /// defines function names. When it is, we should use it. See
  30. /// https://github.com/rust-lang/rfcs/pull/1719
  31. /// * A `message` of type &str, which is the log message itself.
  32. #[macro_export]
  33. macro_rules! tor_log_msg {
  34. ($severity: path,
  35. $domain: path,
  36. $function: expr,
  37. $($message:tt)*) =>
  38. {
  39. {
  40. let msg = format!($($message)*);
  41. $crate::tor_log_msg_impl($severity, $domain, $function, msg)
  42. }
  43. };
  44. }
  45. #[inline]
  46. pub fn tor_log_msg_impl(
  47. severity: LogSeverity,
  48. domain: LogDomain,
  49. function: &str,
  50. message: String,
  51. ) {
  52. use std::ffi::CString;
  53. /// Default function name to log in case of errors when converting
  54. /// a function name to a CString
  55. const ERR_LOG_FUNCTION: &str = "tor_log_msg";
  56. /// Default message to log in case of errors when converting a log
  57. /// message to a CString
  58. const ERR_LOG_MSG: &str = "Unable to log message from Rust \
  59. module due to error when converting to CString";
  60. let func = match CString::new(function) {
  61. Ok(n) => n,
  62. Err(_) => CString::new(ERR_LOG_FUNCTION).unwrap(),
  63. };
  64. let msg = match CString::new(message) {
  65. Ok(n) => n,
  66. Err(_) => CString::new(ERR_LOG_MSG).unwrap(),
  67. };
  68. // Bind to a local variable to preserve ownership. This is essential so
  69. // that ownership is guaranteed until these local variables go out of scope
  70. let func_ptr = func.as_ptr();
  71. let msg_ptr = msg.as_ptr();
  72. let c_severity = unsafe { log::translate_severity(severity) };
  73. let c_domain = unsafe { log::translate_domain(domain) };
  74. unsafe { log::tor_log_string(c_severity, c_domain, func_ptr, msg_ptr) }
  75. }
  76. /// This implementation is used when compiling for actual use, as opposed to
  77. /// testing.
  78. #[cfg(not(test))]
  79. pub mod log {
  80. use libc::{c_char, c_int};
  81. use super::LogDomain;
  82. use super::LogSeverity;
  83. /// Severity log types. These mirror definitions in /src/common/torlog.h
  84. /// C_RUST_COUPLED: src/common/log.c, log domain types
  85. extern "C" {
  86. static LOG_WARN_: c_int;
  87. static LOG_NOTICE_: c_int;
  88. }
  89. /// Domain log types. These mirror definitions in /src/common/torlog.h
  90. /// C_RUST_COUPLED: src/common/log.c, log severity types
  91. extern "C" {
  92. static LD_NET_: u32;
  93. static LD_GENERAL_: u32;
  94. }
  95. /// Translate Rust defintions of log domain levels to C. This exposes a 1:1
  96. /// mapping between types.
  97. #[inline]
  98. pub unsafe fn translate_domain(domain: LogDomain) -> u32 {
  99. match domain {
  100. LogDomain::Net => LD_NET_,
  101. LogDomain::General => LD_GENERAL_,
  102. }
  103. }
  104. /// Translate Rust defintions of log severity levels to C. This exposes a
  105. /// 1:1 mapping between types.
  106. #[inline]
  107. pub unsafe fn translate_severity(severity: LogSeverity) -> c_int {
  108. match severity {
  109. LogSeverity::Warn => LOG_WARN_,
  110. LogSeverity::Notice => LOG_NOTICE_,
  111. }
  112. }
  113. /// The main entry point into Tor's logger. When in non-test mode, this
  114. /// will link directly with `tor_log_string` in torlog.c
  115. extern "C" {
  116. pub fn tor_log_string(
  117. severity: c_int,
  118. domain: u32,
  119. function: *const c_char,
  120. string: *const c_char,
  121. );
  122. }
  123. }
  124. /// This module exposes no-op functionality for testing other Rust modules
  125. /// without linking to C.
  126. #[cfg(test)]
  127. pub mod log {
  128. use libc::{c_char, c_int};
  129. use super::LogDomain;
  130. use super::LogSeverity;
  131. pub static mut LAST_LOGGED_FUNCTION: *mut String = 0 as *mut String;
  132. pub static mut LAST_LOGGED_MESSAGE: *mut String = 0 as *mut String;
  133. pub unsafe fn tor_log_string(
  134. _severity: c_int,
  135. _domain: u32,
  136. function: *const c_char,
  137. message: *const c_char,
  138. ) {
  139. use std::ffi::CStr;
  140. let f = CStr::from_ptr(function);
  141. let fct = match f.to_str() {
  142. Ok(n) => n,
  143. Err(_) => "",
  144. };
  145. LAST_LOGGED_FUNCTION = Box::into_raw(Box::new(String::from(fct)));
  146. let m = CStr::from_ptr(message);
  147. let msg = match m.to_str() {
  148. Ok(n) => n,
  149. Err(_) => "",
  150. };
  151. LAST_LOGGED_MESSAGE = Box::into_raw(Box::new(String::from(msg)));
  152. }
  153. pub unsafe fn translate_domain(_domain: LogDomain) -> u32 {
  154. 1
  155. }
  156. pub unsafe fn translate_severity(_severity: LogSeverity) -> c_int {
  157. 1
  158. }
  159. }
  160. #[cfg(test)]
  161. mod test {
  162. use tor_log::*;
  163. use tor_log::log::{LAST_LOGGED_FUNCTION, LAST_LOGGED_MESSAGE};
  164. #[test]
  165. fn test_get_log_message() {
  166. {
  167. fn test_macro() {
  168. tor_log_msg!(
  169. LogSeverity::Warn,
  170. LogDomain::Net,
  171. "test_macro",
  172. "test log message {}",
  173. "a",
  174. );
  175. }
  176. test_macro();
  177. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  178. assert_eq!("test_macro", *function);
  179. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  180. assert_eq!("test log message a", *message);
  181. }
  182. // test multiple inputs into the log message
  183. {
  184. fn test_macro() {
  185. tor_log_msg!(
  186. LogSeverity::Warn,
  187. LogDomain::Net,
  188. "next_test_macro",
  189. "test log message {} {} {} {} {}",
  190. 1,
  191. 2,
  192. 3,
  193. 4,
  194. 5
  195. );
  196. }
  197. test_macro();
  198. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  199. assert_eq!("next_test_macro", *function);
  200. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  201. assert_eq!("test log message 1 2 3 4 5", *message);
  202. }
  203. // test how a long log message will be formatted
  204. {
  205. fn test_macro() {
  206. tor_log_msg!(
  207. LogSeverity::Warn,
  208. LogDomain::Net,
  209. "test_macro",
  210. "{}",
  211. "All the world's a stage, and all the men and women \
  212. merely players: they have their exits and their \
  213. entrances; and one man in his time plays many parts, his \
  214. acts being seven ages."
  215. );
  216. }
  217. test_macro();
  218. let expected_string = "All the world's a \
  219. stage, and all the men \
  220. and women merely players: \
  221. they have their exits and \
  222. their entrances; and one man \
  223. in his time plays many parts, \
  224. his acts being seven ages.";
  225. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  226. assert_eq!("test_macro", *function);
  227. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  228. assert_eq!(expected_string, *message);
  229. }
  230. }
  231. }