main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #![allow(clippy::inconsistent_digit_grouping, clippy::unusual_byte_groupings)]
  2. extern crate autocfg;
  3. #[cfg(feature = "bindgen")]
  4. extern crate bindgen;
  5. extern crate cc;
  6. #[cfg(feature = "vendored")]
  7. extern crate openssl_src;
  8. extern crate pkg_config;
  9. #[cfg(target_env = "msvc")]
  10. extern crate vcpkg;
  11. use std::collections::HashSet;
  12. use std::env;
  13. use std::ffi::OsString;
  14. use std::path::{Path, PathBuf};
  15. mod cfgs;
  16. mod find_normal;
  17. #[cfg(feature = "vendored")]
  18. mod find_vendored;
  19. #[cfg(feature = "bindgen")]
  20. mod run_bindgen;
  21. #[derive(PartialEq)]
  22. enum Version {
  23. Openssl3xx,
  24. Openssl11x,
  25. Openssl10x,
  26. Libressl,
  27. }
  28. fn env_inner(name: &str) -> Option<OsString> {
  29. let var = env::var_os(name);
  30. println!("cargo:rerun-if-env-changed={}", name);
  31. match var {
  32. Some(ref v) => println!("{} = {}", name, v.to_string_lossy()),
  33. None => println!("{} unset", name),
  34. }
  35. var
  36. }
  37. fn env(name: &str) -> Option<OsString> {
  38. let prefix = env::var("TARGET").unwrap().to_uppercase().replace('-', "_");
  39. let prefixed = format!("{}_{}", prefix, name);
  40. env_inner(&prefixed).or_else(|| env_inner(name))
  41. }
  42. fn find_openssl(target: &str) -> (Vec<PathBuf>, PathBuf) {
  43. #[cfg(feature = "vendored")]
  44. {
  45. // vendor if the feature is present, unless
  46. // OPENSSL_NO_VENDOR exists and isn't `0`
  47. if env("OPENSSL_NO_VENDOR").map_or(true, |s| s == "0") {
  48. return find_vendored::get_openssl(target);
  49. }
  50. }
  51. find_normal::get_openssl(target)
  52. }
  53. fn main() {
  54. check_rustc_versions();
  55. let target = env::var("TARGET").unwrap();
  56. let (lib_dirs, include_dir) = find_openssl(&target);
  57. if !lib_dirs.iter().all(|p| Path::new(p).exists()) {
  58. panic!("OpenSSL library directory does not exist: {:?}", lib_dirs);
  59. }
  60. if !Path::new(&include_dir).exists() {
  61. panic!(
  62. "OpenSSL include directory does not exist: {}",
  63. include_dir.to_string_lossy()
  64. );
  65. }
  66. for lib_dir in lib_dirs.iter() {
  67. println!(
  68. "cargo:rustc-link-search=native={}",
  69. lib_dir.to_string_lossy()
  70. );
  71. }
  72. println!("cargo:include={}", include_dir.to_string_lossy());
  73. let version = postprocess(&[include_dir]);
  74. let libs_env = env("OPENSSL_LIBS");
  75. let libs = match libs_env.as_ref().and_then(|s| s.to_str()) {
  76. Some(v) => {
  77. if v.is_empty() {
  78. vec![]
  79. } else {
  80. v.split(':').collect()
  81. }
  82. }
  83. None => match version {
  84. Version::Openssl10x if target.contains("windows") => vec!["ssleay32", "libeay32"],
  85. Version::Openssl3xx | Version::Openssl11x if target.contains("windows-msvc") => {
  86. vec!["libssl", "libcrypto"]
  87. }
  88. _ => vec!["ssl", "crypto"],
  89. },
  90. };
  91. let kind = determine_mode(&lib_dirs, &libs);
  92. for lib in libs.into_iter() {
  93. println!("cargo:rustc-link-lib={}={}", kind, lib);
  94. }
  95. // https://github.com/openssl/openssl/pull/15086
  96. if version == Version::Openssl3xx
  97. && kind == "static"
  98. && (env::var("CARGO_CFG_TARGET_OS").unwrap() == "linux"
  99. || env::var("CARGO_CFG_TARGET_OS").unwrap() == "android")
  100. && env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32"
  101. {
  102. println!("cargo:rustc-link-lib=dylib=atomic");
  103. }
  104. if kind == "static" && target.contains("windows") {
  105. println!("cargo:rustc-link-lib=dylib=gdi32");
  106. println!("cargo:rustc-link-lib=dylib=user32");
  107. println!("cargo:rustc-link-lib=dylib=crypt32");
  108. println!("cargo:rustc-link-lib=dylib=ws2_32");
  109. println!("cargo:rustc-link-lib=dylib=advapi32");
  110. }
  111. }
  112. fn check_rustc_versions() {
  113. let cfg = autocfg::new();
  114. if cfg.probe_rustc_version(1, 31) {
  115. println!("cargo:rustc-cfg=const_fn");
  116. }
  117. }
  118. #[allow(clippy::let_and_return)]
  119. fn postprocess(include_dirs: &[PathBuf]) -> Version {
  120. let version = validate_headers(include_dirs);
  121. #[cfg(feature = "bindgen")]
  122. run_bindgen::run(&include_dirs);
  123. version
  124. }
  125. /// Validates the header files found in `include_dir` and then returns the
  126. /// version string of OpenSSL.
  127. #[allow(clippy::manual_strip)] // we need to support pre-1.45.0
  128. fn validate_headers(include_dirs: &[PathBuf]) -> Version {
  129. // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, 1.1.0, 1.1.1 and 3.0.0.
  130. // To correctly expose the right API from this crate, take a look at
  131. // `opensslv.h` to see what version OpenSSL claims to be.
  132. //
  133. // OpenSSL has a number of build-time configuration options which affect
  134. // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem
  135. // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem.
  136. //
  137. // To handle all this conditional compilation we slurp up the configuration
  138. // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines
  139. // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can
  140. // account for compile differences and such.
  141. println!("cargo:rerun-if-changed=build/expando.c");
  142. let mut gcc = cc::Build::new();
  143. for include_dir in include_dirs {
  144. gcc.include(include_dir);
  145. }
  146. let expanded = match gcc.file("build/expando.c").try_expand() {
  147. Ok(expanded) => expanded,
  148. Err(e) => {
  149. panic!(
  150. "
  151. Header expansion error:
  152. {:?}
  153. Failed to find OpenSSL development headers.
  154. You can try fixing this setting the `OPENSSL_DIR` environment variable
  155. pointing to your OpenSSL installation or installing OpenSSL headers package
  156. specific to your distribution:
  157. # On Ubuntu
  158. sudo apt-get install libssl-dev
  159. # On Arch Linux
  160. sudo pacman -S openssl
  161. # On Fedora
  162. sudo dnf install openssl-devel
  163. # On Alpine Linux
  164. apk add openssl-dev
  165. See rust-openssl README for more information:
  166. https://github.com/sfackler/rust-openssl#linux
  167. ",
  168. e
  169. );
  170. }
  171. };
  172. let expanded = String::from_utf8(expanded).unwrap();
  173. let mut enabled = vec![];
  174. let mut openssl_version = None;
  175. let mut libressl_version = None;
  176. for line in expanded.lines() {
  177. let line = line.trim();
  178. let openssl_prefix = "RUST_VERSION_OPENSSL_";
  179. let new_openssl_prefix = "RUST_VERSION_NEW_OPENSSL_";
  180. let libressl_prefix = "RUST_VERSION_LIBRESSL_";
  181. let conf_prefix = "RUST_CONF_";
  182. if line.starts_with(openssl_prefix) {
  183. let version = &line[openssl_prefix.len()..];
  184. openssl_version = Some(parse_version(version));
  185. } else if line.starts_with(new_openssl_prefix) {
  186. let version = &line[new_openssl_prefix.len()..];
  187. openssl_version = Some(parse_new_version(version));
  188. } else if line.starts_with(libressl_prefix) {
  189. let version = &line[libressl_prefix.len()..];
  190. libressl_version = Some(parse_version(version));
  191. } else if line.starts_with(conf_prefix) {
  192. enabled.push(&line[conf_prefix.len()..]);
  193. }
  194. }
  195. for enabled in &enabled {
  196. println!("cargo:rustc-cfg=osslconf=\"{}\"", enabled);
  197. }
  198. println!("cargo:conf={}", enabled.join(","));
  199. for cfg in cfgs::get(openssl_version, libressl_version) {
  200. println!("cargo:rustc-cfg={}", cfg);
  201. }
  202. if let Some(libressl_version) = libressl_version {
  203. println!("cargo:libressl_version_number={:x}", libressl_version);
  204. let major = (libressl_version >> 28) as u8;
  205. let minor = (libressl_version >> 20) as u8;
  206. let fix = (libressl_version >> 12) as u8;
  207. let (major, minor, fix) = match (major, minor, fix) {
  208. (2, 5, 0) => ('2', '5', '0'),
  209. (2, 5, 1) => ('2', '5', '1'),
  210. (2, 5, 2) => ('2', '5', '2'),
  211. (2, 5, _) => ('2', '5', 'x'),
  212. (2, 6, 0) => ('2', '6', '0'),
  213. (2, 6, 1) => ('2', '6', '1'),
  214. (2, 6, 2) => ('2', '6', '2'),
  215. (2, 6, _) => ('2', '6', 'x'),
  216. (2, 7, _) => ('2', '7', 'x'),
  217. (2, 8, 0) => ('2', '8', '0'),
  218. (2, 8, 1) => ('2', '8', '1'),
  219. (2, 8, _) => ('2', '8', 'x'),
  220. (2, 9, 0) => ('2', '9', '0'),
  221. (2, 9, _) => ('2', '9', 'x'),
  222. (3, 0, 0) => ('3', '0', '0'),
  223. (3, 0, 1) => ('3', '0', '1'),
  224. (3, 0, _) => ('3', '0', 'x'),
  225. (3, 1, 0) => ('3', '1', '0'),
  226. (3, 1, _) => ('3', '1', 'x'),
  227. (3, 2, 0) => ('3', '2', '0'),
  228. (3, 2, 1) => ('3', '2', '1'),
  229. (3, 2, _) => ('3', '2', 'x'),
  230. (3, 3, 0) => ('3', '3', '0'),
  231. (3, 3, 1) => ('3', '3', '1'),
  232. (3, 3, _) => ('3', '3', 'x'),
  233. (3, 4, 0) => ('3', '4', '0'),
  234. (3, 4, _) => ('3', '4', 'x'),
  235. (3, 5, _) => ('3', '5', 'x'),
  236. _ => version_error(),
  237. };
  238. println!("cargo:libressl=true");
  239. println!("cargo:libressl_version={}{}{}", major, minor, fix);
  240. println!("cargo:version=101");
  241. Version::Libressl
  242. } else {
  243. let openssl_version = openssl_version.unwrap();
  244. println!("cargo:version_number={:x}", openssl_version);
  245. if openssl_version >= 0x4_00_00_00_0 {
  246. version_error()
  247. } else if openssl_version >= 0x3_00_00_00_0 {
  248. Version::Openssl3xx
  249. } else if openssl_version >= 0x1_01_01_00_0 {
  250. println!("cargo:version=111");
  251. Version::Openssl11x
  252. } else if openssl_version >= 0x1_01_00_06_0 {
  253. println!("cargo:version=110");
  254. println!("cargo:patch=f");
  255. Version::Openssl11x
  256. } else if openssl_version >= 0x1_01_00_00_0 {
  257. println!("cargo:version=110");
  258. Version::Openssl11x
  259. } else if openssl_version >= 0x1_00_02_00_0 {
  260. println!("cargo:version=102");
  261. Version::Openssl10x
  262. } else if openssl_version >= 0x1_00_01_00_0 {
  263. println!("cargo:version=101");
  264. Version::Openssl10x
  265. } else {
  266. version_error()
  267. }
  268. }
  269. }
  270. fn version_error() -> ! {
  271. panic!(
  272. "
  273. This crate is only compatible with OpenSSL (version 1.0.1 through 1.1.1, or 3.0.0), or LibreSSL 2.5
  274. through 3.5, but a different version of OpenSSL was found. The build is now aborting
  275. due to this version mismatch.
  276. "
  277. );
  278. }
  279. // parses a string that looks like "0x100020cfL"
  280. #[allow(deprecated)] // trim_right_matches is now trim_end_matches
  281. #[allow(clippy::match_like_matches_macro)] // matches macro requires rust 1.42.0
  282. fn parse_version(version: &str) -> u64 {
  283. // cut off the 0x prefix
  284. assert!(version.starts_with("0x"));
  285. let version = &version[2..];
  286. // and the type specifier suffix
  287. let version = version.trim_right_matches(|c: char| match c {
  288. '0'..='9' | 'a'..='f' | 'A'..='F' => false,
  289. _ => true,
  290. });
  291. u64::from_str_radix(version, 16).unwrap()
  292. }
  293. // parses a string that looks like 3_0_0
  294. fn parse_new_version(version: &str) -> u64 {
  295. println!("version: {}", version);
  296. let mut it = version.split('_');
  297. let major = it.next().unwrap().parse::<u64>().unwrap();
  298. let minor = it.next().unwrap().parse::<u64>().unwrap();
  299. let patch = it.next().unwrap().parse::<u64>().unwrap();
  300. (major << 28) | (minor << 20) | (patch << 4)
  301. }
  302. /// Given a libdir for OpenSSL (where artifacts are located) as well as the name
  303. /// of the libraries we're linking to, figure out whether we should link them
  304. /// statically or dynamically.
  305. fn determine_mode(libdirs: &[PathBuf], libs: &[&str]) -> &'static str {
  306. // First see if a mode was explicitly requested
  307. let kind = env("OPENSSL_STATIC");
  308. match kind.as_ref().and_then(|s| s.to_str()) {
  309. Some("0") => return "dylib",
  310. Some(_) => return "static",
  311. None => {}
  312. }
  313. // Next, see what files we actually have to link against, and see what our
  314. // possibilities even are.
  315. let mut files = HashSet::new();
  316. for dir in libdirs {
  317. for path in dir
  318. .read_dir()
  319. .unwrap()
  320. .map(|e| e.unwrap())
  321. .map(|e| e.file_name())
  322. .filter_map(|e| e.into_string().ok())
  323. {
  324. files.insert(path);
  325. }
  326. }
  327. let can_static = libs
  328. .iter()
  329. .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l)));
  330. let can_dylib = libs.iter().all(|l| {
  331. files.contains(&format!("lib{}.so", l))
  332. || files.contains(&format!("{}.dll", l))
  333. || files.contains(&format!("lib{}.dylib", l))
  334. });
  335. match (can_static, can_dylib) {
  336. (true, false) => return "static",
  337. (false, true) => return "dylib",
  338. (false, false) => {
  339. panic!(
  340. "OpenSSL libdir at `{:?}` does not contain the required files \
  341. to either statically or dynamically link OpenSSL",
  342. libdirs
  343. );
  344. }
  345. (true, true) => {}
  346. }
  347. // Ok, we've got not explicit preference and can *either* link statically or
  348. // link dynamically. In the interest of "security upgrades" and/or "best
  349. // practices with security libs", let's link dynamically.
  350. "dylib"
  351. }