You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
11KB

  1. use lazy_static::lazy_static;
  2. use reqwest::header::{HeaderMap, ACCEPT};
  3. use reqwest::{blocking::Client, StatusCode};
  4. use config::LinkChecker;
  5. use errors::Result;
  6. use std::collections::HashMap;
  7. use std::error::Error;
  8. use std::sync::{Arc, RwLock};
  9. #[derive(Clone, Debug, PartialEq)]
  10. pub struct LinkResult {
  11. pub code: Option<StatusCode>,
  12. /// Whether the HTTP request didn't make it to getting a HTTP code
  13. pub error: Option<String>,
  14. }
  15. impl LinkResult {
  16. pub fn is_valid(&self) -> bool {
  17. if self.error.is_some() {
  18. return false;
  19. }
  20. if let Some(c) = self.code {
  21. return c.is_success() || c == StatusCode::NOT_MODIFIED;
  22. }
  23. true
  24. }
  25. pub fn message(&self) -> String {
  26. if let Some(ref e) = self.error {
  27. return e.clone();
  28. }
  29. if let Some(c) = self.code {
  30. return format!("{}", c);
  31. }
  32. "Unknown error".to_string()
  33. }
  34. }
  35. lazy_static! {
  36. // Keep history of link checks so a rebuild doesn't have to check again
  37. static ref LINKS: Arc<RwLock<HashMap<String, LinkResult>>> = Arc::new(RwLock::new(HashMap::new()));
  38. }
  39. pub fn check_url(url: &str, config: &LinkChecker) -> LinkResult {
  40. {
  41. let guard = LINKS.read().unwrap();
  42. if let Some(res) = guard.get(url) {
  43. return res.clone();
  44. }
  45. }
  46. let mut headers = HeaderMap::new();
  47. headers.insert(ACCEPT, "text/html".parse().unwrap());
  48. headers.append(ACCEPT, "*/*".parse().unwrap());
  49. let client = Client::new();
  50. let check_anchor = !config.skip_anchor_prefixes.iter().any(|prefix| url.starts_with(prefix));
  51. // Need to actually do the link checking
  52. let res = match client.get(url).headers(headers).send() {
  53. Ok(ref mut response) if check_anchor && has_anchor(url) => {
  54. let body = {
  55. let mut buf: Vec<u8> = vec![];
  56. response.copy_to(&mut buf).unwrap();
  57. String::from_utf8(buf).unwrap()
  58. };
  59. match check_page_for_anchor(url, body) {
  60. Ok(_) => LinkResult { code: Some(response.status()), error: None },
  61. Err(e) => LinkResult { code: None, error: Some(e.to_string()) },
  62. }
  63. }
  64. Ok(response) => {
  65. if response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED {
  66. LinkResult { code: Some(response.status()), error: None }
  67. } else {
  68. let error_string = if response.status().is_informational() {
  69. format!("Informational status code ({}) received", response.status())
  70. } else if response.status().is_redirection() {
  71. format!("Redirection status code ({}) received", response.status())
  72. } else if response.status().is_client_error() {
  73. format!("Client error status code ({}) received", response.status())
  74. } else if response.status().is_server_error() {
  75. format!("Server error status code ({}) received", response.status())
  76. } else {
  77. format!("Non-success status code ({}) received", response.status())
  78. };
  79. LinkResult { code: None, error: Some(error_string) }
  80. }
  81. }
  82. Err(e) => LinkResult { code: None, error: Some(e.description().to_string()) },
  83. };
  84. LINKS.write().unwrap().insert(url.to_string(), res.clone());
  85. res
  86. }
  87. fn has_anchor(url: &str) -> bool {
  88. match url.find('#') {
  89. Some(index) => match url.get(index..=index + 1) {
  90. Some("#/") | Some("#!") | None => false,
  91. Some(_) => true,
  92. },
  93. None => false,
  94. }
  95. }
  96. fn check_page_for_anchor(url: &str, body: String) -> Result<()> {
  97. let index = url.find('#').unwrap();
  98. let anchor = url.get(index + 1..).unwrap();
  99. let checks: [String; 4] = [
  100. format!(" id='{}'", anchor),
  101. format!(r#" id="{}""#, anchor),
  102. format!(" name='{}'", anchor),
  103. format!(r#" name="{}""#, anchor),
  104. ];
  105. if checks.iter().any(|check| body[..].contains(&check[..])) {
  106. Ok(())
  107. } else {
  108. Err(errors::Error::from(format!("Anchor `#{}` not found on page", anchor)))
  109. }
  110. }
  111. #[cfg(test)]
  112. mod tests {
  113. use super::{check_page_for_anchor, check_url, has_anchor, LinkChecker, LINKS};
  114. use mockito::mock;
  115. // NOTE: HTTP mock paths below are randomly generated to avoid name
  116. // collisions. Mocks with the same path can sometimes bleed between tests
  117. // and cause them to randomly pass/fail. Please make sure to use unique
  118. // paths when adding or modifying tests that use Mockito.
  119. #[test]
  120. fn can_validate_ok_links() {
  121. let url = format!("{}{}", mockito::server_url(), "/ekbtwxfhjw");
  122. let _m = mock("GET", "/ekbtwxfhjw")
  123. .with_header("Content-Type", "text/html")
  124. .with_body(format!(
  125. r#"<!DOCTYPE html>
  126. <html>
  127. <head>
  128. <title>Test</title>
  129. </head>
  130. <body>
  131. <a href="{}">Mock URL</a>
  132. </body>
  133. </html>
  134. "#,
  135. url
  136. ))
  137. .create();
  138. let res = check_url(&url, &LinkChecker::default());
  139. assert!(res.is_valid());
  140. assert!(LINKS.read().unwrap().get(&url).is_some());
  141. }
  142. #[test]
  143. fn can_follow_301_links() {
  144. let _m1 = mock("GET", "/c7qrtrv3zz")
  145. .with_status(301)
  146. .with_header("Content-Type", "text/plain")
  147. .with_header("Location", format!("{}/rbs5avjs8e", mockito::server_url()).as_str())
  148. .with_body("Redirecting...")
  149. .create();
  150. let _m2 = mock("GET", "/rbs5avjs8e")
  151. .with_header("Content-Type", "text/plain")
  152. .with_body("Test")
  153. .create();
  154. let url = format!("{}{}", mockito::server_url(), "/c7qrtrv3zz");
  155. let res = check_url(&url, &LinkChecker::default());
  156. assert!(res.is_valid());
  157. assert!(res.code.is_some());
  158. assert!(res.error.is_none());
  159. }
  160. #[test]
  161. fn can_fail_301_to_404_links() {
  162. let _m1 = mock("GET", "/cav9vibhsc")
  163. .with_status(301)
  164. .with_header("Content-Type", "text/plain")
  165. .with_header("Location", format!("{}/72zmfg4smd", mockito::server_url()).as_str())
  166. .with_body("Redirecting...")
  167. .create();
  168. let _m2 = mock("GET", "/72zmfg4smd")
  169. .with_status(404)
  170. .with_header("Content-Type", "text/plain")
  171. .with_body("Not Found")
  172. .create();
  173. let url = format!("{}{}", mockito::server_url(), "/cav9vibhsc");
  174. let res = check_url(&url, &LinkChecker::default());
  175. assert_eq!(res.is_valid(), false);
  176. assert!(res.code.is_none());
  177. assert!(res.error.is_some());
  178. }
  179. #[test]
  180. fn can_fail_404_links() {
  181. let _m = mock("GET", "/nlhab9c1vc")
  182. .with_status(404)
  183. .with_header("Content-Type", "text/plain")
  184. .with_body("Not Found")
  185. .create();
  186. let url = format!("{}{}", mockito::server_url(), "/nlhab9c1vc");
  187. let res = check_url(&url, &LinkChecker::default());
  188. assert_eq!(res.is_valid(), false);
  189. assert!(res.code.is_none());
  190. assert!(res.error.is_some());
  191. }
  192. #[test]
  193. fn can_fail_500_links() {
  194. let _m = mock("GET", "/qdbrssazes")
  195. .with_status(500)
  196. .with_header("Content-Type", "text/plain")
  197. .with_body("Internal Server Error")
  198. .create();
  199. let url = format!("{}{}", mockito::server_url(), "/qdbrssazes");
  200. let res = check_url(&url, &LinkChecker::default());
  201. assert_eq!(res.is_valid(), false);
  202. assert!(res.code.is_none());
  203. assert!(res.error.is_some());
  204. }
  205. #[test]
  206. fn can_fail_unresolved_links() {
  207. let res = check_url("https://t6l5cn9lpm.lxizfnzckd", &LinkChecker::default());
  208. assert_eq!(res.is_valid(), false);
  209. assert!(res.code.is_none());
  210. assert!(res.error.is_some());
  211. }
  212. #[test]
  213. fn can_validate_anchors() {
  214. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  215. let body = r#"<body><h3 id="method.collect">collect</h3></body>"#.to_string();
  216. let res = check_page_for_anchor(url, body);
  217. assert!(res.is_ok());
  218. }
  219. #[test]
  220. fn can_validate_anchors_with_other_quotes() {
  221. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  222. let body = r#"<body><h3 id="method.collect">collect</h3></body>"#.to_string();
  223. let res = check_page_for_anchor(url, body);
  224. assert!(res.is_ok());
  225. }
  226. #[test]
  227. fn can_validate_anchors_with_name_attr() {
  228. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  229. let body = r#"<body><h3 name="method.collect">collect</h3></body>"#.to_string();
  230. let res = check_page_for_anchor(url, body);
  231. assert!(res.is_ok());
  232. }
  233. #[test]
  234. fn can_fail_when_anchor_not_found() {
  235. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#me";
  236. let body = r#"<body><h3 id="method.collect">collect</h3></body>"#.to_string();
  237. let res = check_page_for_anchor(url, body);
  238. assert!(res.is_err());
  239. }
  240. #[test]
  241. fn can_check_url_for_anchor() {
  242. let url = "https://doc.rust-lang.org/std/index.html#the-rust-standard-library";
  243. let res = has_anchor(url);
  244. assert_eq!(res, true);
  245. }
  246. #[test]
  247. fn will_return_false_when_no_anchor() {
  248. let url = "https://doc.rust-lang.org/std/index.html";
  249. let res = has_anchor(url);
  250. assert_eq!(res, false);
  251. }
  252. #[test]
  253. fn will_return_false_when_has_router_url() {
  254. let url = "https://doc.rust-lang.org/#/std";
  255. let res = has_anchor(url);
  256. assert_eq!(res, false);
  257. }
  258. #[test]
  259. fn will_return_false_when_has_router_url_alt() {
  260. let url = "https://doc.rust-lang.org/#!/std";
  261. let res = has_anchor(url);
  262. assert_eq!(res, false);
  263. }
  264. #[test]
  265. fn skip_anchor_prefixes() {
  266. let ignore_url = format!("{}{}", mockito::server_url(), "/ignore/");
  267. let config = LinkChecker { skip_prefixes: vec![], skip_anchor_prefixes: vec![ignore_url] };
  268. let _m1 = mock("GET", "/ignore/i30hobj1cy")
  269. .with_header("Content-Type", "text/html")
  270. .with_body(
  271. r#"<!DOCTYPE html>
  272. <html>
  273. <head>
  274. <title>Ignore</title>
  275. </head>
  276. <body>
  277. <p id="existent"></p>
  278. </body>
  279. </html>
  280. "#,
  281. )
  282. .create();
  283. // anchor check is ignored because the url matches the prefix
  284. let ignore = format!("{}{}", mockito::server_url(), "/ignore/i30hobj1cy#nonexistent");
  285. assert!(check_url(&ignore, &config).is_valid());
  286. let _m2 = mock("GET", "/guvqcqwmth")
  287. .with_header("Content-Type", "text/html")
  288. .with_body(
  289. r#"<!DOCTYPE html>
  290. <html>
  291. <head>
  292. <title>Test</title>
  293. </head>
  294. <body>
  295. <p id="existent"></p>
  296. </body>
  297. </html>
  298. "#,
  299. )
  300. .create();
  301. // other anchors are checked
  302. let existent = format!("{}{}", mockito::server_url(), "/guvqcqwmth#existent");
  303. assert!(check_url(&existent, &config).is_valid());
  304. let nonexistent = format!("{}{}", mockito::server_url(), "/guvqcqwmth#nonexistent");
  305. assert_eq!(check_url(&nonexistent, &config).is_valid(), false);
  306. }
  307. }