tor_log.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright (c) 2016-2017, 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(all(not(test), not(feature = "testing")))]
  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. #[no_mangle]
  87. static LOG_WARN_: c_int;
  88. static LOG_NOTICE_: c_int;
  89. }
  90. /// Domain log types. These mirror definitions in /src/common/torlog.h
  91. /// C_RUST_COUPLED: src/common/log.c, log severity types
  92. extern "C" {
  93. #[no_mangle]
  94. static LD_NET_: u32;
  95. static LD_GENERAL_: u32;
  96. }
  97. /// Translate Rust defintions of log domain levels to C. This exposes a 1:1
  98. /// mapping between types.
  99. #[inline]
  100. pub unsafe fn translate_domain(domain: LogDomain) -> u32 {
  101. match domain {
  102. LogDomain::Net => LD_NET_,
  103. LogDomain::General => LD_GENERAL_,
  104. }
  105. }
  106. /// Translate Rust defintions of log severity levels to C. This exposes a
  107. /// 1:1 mapping between types.
  108. #[inline]
  109. pub unsafe fn translate_severity(severity: LogSeverity) -> c_int {
  110. match severity {
  111. LogSeverity::Warn => LOG_WARN_,
  112. LogSeverity::Notice => LOG_NOTICE_,
  113. }
  114. }
  115. /// The main entry point into Tor's logger. When in non-test mode, this
  116. /// will link directly with `tor_log_string` in /src/or/log.c
  117. extern "C" {
  118. pub fn tor_log_string(
  119. severity: c_int,
  120. domain: u32,
  121. function: *const c_char,
  122. string: *const c_char,
  123. );
  124. }
  125. }
  126. /// This module exposes no-op functionality for testing other Rust modules
  127. /// without linking to C.
  128. #[cfg(any(test, feature = "testing"))]
  129. pub mod log {
  130. use libc::{c_char, c_int};
  131. use super::LogDomain;
  132. use super::LogSeverity;
  133. pub static mut LAST_LOGGED_FUNCTION: *mut String = 0 as *mut String;
  134. pub static mut LAST_LOGGED_MESSAGE: *mut String = 0 as *mut String;
  135. pub unsafe fn tor_log_string(
  136. _severity: c_int,
  137. _domain: u32,
  138. function: *const c_char,
  139. message: *const c_char,
  140. ) {
  141. use std::ffi::CStr;
  142. let f = CStr::from_ptr(function);
  143. let fct = match f.to_str() {
  144. Ok(n) => n,
  145. Err(_) => "",
  146. };
  147. LAST_LOGGED_FUNCTION = Box::into_raw(Box::new(String::from(fct)));
  148. let m = CStr::from_ptr(message);
  149. let msg = match m.to_str() {
  150. Ok(n) => n,
  151. Err(_) => "",
  152. };
  153. LAST_LOGGED_MESSAGE = Box::into_raw(Box::new(String::from(msg)));
  154. }
  155. pub unsafe fn translate_domain(_domain: LogDomain) -> u32 {
  156. 1
  157. }
  158. pub unsafe fn translate_severity(_severity: LogSeverity) -> c_int {
  159. 1
  160. }
  161. }
  162. #[cfg(test)]
  163. mod test {
  164. use tor_log::*;
  165. use tor_log::log::{LAST_LOGGED_FUNCTION, LAST_LOGGED_MESSAGE};
  166. #[test]
  167. fn test_get_log_message() {
  168. {
  169. fn test_macro() {
  170. tor_log_msg!(
  171. LogSeverity::Warn,
  172. LogDomain::Net,
  173. "test_macro",
  174. "test log message {}",
  175. "a",
  176. );
  177. }
  178. test_macro();
  179. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  180. assert_eq!("test_macro", *function);
  181. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  182. assert_eq!("test log message a", *message);
  183. }
  184. // test multiple inputs into the log message
  185. {
  186. fn test_macro() {
  187. tor_log_msg!(
  188. LogSeverity::Warn,
  189. LogDomain::Net,
  190. "next_test_macro",
  191. "test log message {} {} {} {} {}",
  192. 1,
  193. 2,
  194. 3,
  195. 4,
  196. 5
  197. );
  198. }
  199. test_macro();
  200. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  201. assert_eq!("next_test_macro", *function);
  202. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  203. assert_eq!("test log message 1 2 3 4 5", *message);
  204. }
  205. // test how a long log message will be formatted
  206. {
  207. fn test_macro() {
  208. tor_log_msg!(
  209. LogSeverity::Warn,
  210. LogDomain::Net,
  211. "test_macro",
  212. "{}",
  213. "All the world's a stage, and all the men and women \
  214. merely players: they have their exits and their \
  215. entrances; and one man in his time plays many parts, his \
  216. acts being seven ages."
  217. );
  218. }
  219. test_macro();
  220. let expected_string = "All the world's a \
  221. stage, and all the men \
  222. and women merely players: \
  223. they have their exits and \
  224. their entrances; and one man \
  225. in his time plays many parts, \
  226. his acts being seven ages.";
  227. let function = unsafe { Box::from_raw(LAST_LOGGED_FUNCTION) };
  228. assert_eq!("test_macro", *function);
  229. let message = unsafe { Box::from_raw(LAST_LOGGED_MESSAGE) };
  230. assert_eq!(expected_string, *message);
  231. }
  232. }
  233. }