find_normal.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. use pkg_config;
  2. use std::ffi::OsString;
  3. use std::path::{Path, PathBuf};
  4. use std::process::{self, Command};
  5. use super::env;
  6. pub fn get_openssl(target: &str) -> (Vec<PathBuf>, PathBuf) {
  7. let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from);
  8. let include_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from);
  9. match (lib_dir, include_dir) {
  10. (Some(lib_dir), Some(include_dir)) => (vec![lib_dir], include_dir),
  11. (lib_dir, include_dir) => {
  12. let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(target));
  13. let openssl_dir = Path::new(&openssl_dir);
  14. let lib_dir = lib_dir.map(|d| vec![d]).unwrap_or_else(|| {
  15. let mut lib_dirs = vec![];
  16. // OpenSSL 3.0 now puts it's libraries in lib64/ by default,
  17. // check for both it and lib/.
  18. if openssl_dir.join("lib64").exists() {
  19. lib_dirs.push(openssl_dir.join("lib64"));
  20. }
  21. if openssl_dir.join("lib").exists() {
  22. lib_dirs.push(openssl_dir.join("lib"));
  23. }
  24. lib_dirs
  25. });
  26. let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include"));
  27. (lib_dir, include_dir)
  28. }
  29. }
  30. }
  31. fn resolve_with_wellknown_homebrew_location(dir: &str) -> Option<PathBuf> {
  32. let versions = ["openssl@3", "[email protected]"];
  33. // Check up default aarch 64 Homebrew installation location first
  34. // for quick resolution if possible.
  35. // `pkg-config` on brew doesn't necessarily contain settings for openssl apparently.
  36. for version in &versions {
  37. let homebrew = Path::new(dir).join(format!("opt/{}", version));
  38. if homebrew.exists() {
  39. return Some(homebrew);
  40. }
  41. }
  42. for version in &versions {
  43. // Calling `brew --prefix <package>` command usually slow and
  44. // takes seconds, and will be used only as a last resort.
  45. let output = execute_command_and_get_output("brew", &["--prefix", version]);
  46. if let Some(ref output) = output {
  47. let homebrew = Path::new(&output);
  48. if homebrew.exists() {
  49. return Some(homebrew.to_path_buf());
  50. }
  51. }
  52. }
  53. None
  54. }
  55. fn resolve_with_wellknown_location(dir: &str) -> Option<PathBuf> {
  56. let root_dir = Path::new(dir);
  57. let include_openssl = root_dir.join("include/openssl");
  58. if include_openssl.exists() {
  59. Some(root_dir.to_path_buf())
  60. } else {
  61. None
  62. }
  63. }
  64. fn find_openssl_dir(target: &str) -> OsString {
  65. let host = env::var("HOST").unwrap();
  66. if host == target && target.ends_with("-apple-darwin") {
  67. let homebrew_dir = match target {
  68. "aarch64-apple-darwin" => "/opt/homebrew",
  69. _ => "/usr/local",
  70. };
  71. if let Some(dir) = resolve_with_wellknown_homebrew_location(homebrew_dir) {
  72. return dir.into();
  73. } else if let Some(dir) = resolve_with_wellknown_location("/opt/pkg") {
  74. // pkgsrc
  75. return dir.into();
  76. } else if let Some(dir) = resolve_with_wellknown_location("/opt/local") {
  77. // MacPorts
  78. return dir.into();
  79. }
  80. }
  81. try_pkg_config();
  82. try_vcpkg();
  83. // FreeBSD ships with OpenSSL but doesn't include a pkg-config file :(
  84. if host == target && target.contains("freebsd") {
  85. return OsString::from("/usr");
  86. }
  87. // DragonFly has libressl (or openssl) in ports, but this doesn't include a pkg-config file
  88. if host == target && target.contains("dragonfly") {
  89. return OsString::from("/usr/local");
  90. }
  91. let mut msg = format!(
  92. "
  93. Could not find directory of OpenSSL installation, and this `-sys` crate cannot
  94. proceed without this knowledge. If OpenSSL is installed and this crate had
  95. trouble finding it, you can set the `OPENSSL_DIR` environment variable for the
  96. compilation process.
  97. Make sure you also have the development packages of openssl installed.
  98. For example, `libssl-dev` on Ubuntu or `openssl-devel` on Fedora.
  99. If you're in a situation where you think the directory *should* be found
  100. automatically, please open a bug at https://github.com/sfackler/rust-openssl
  101. and include information about your system as well as this message.
  102. $HOST = {}
  103. $TARGET = {}
  104. openssl-sys = {}
  105. ",
  106. host,
  107. target,
  108. env!("CARGO_PKG_VERSION")
  109. );
  110. if host.contains("apple-darwin") && target.contains("apple-darwin") {
  111. let system = Path::new("/usr/lib/libssl.0.9.8.dylib");
  112. if system.exists() {
  113. msg.push_str(
  114. "
  115. openssl-sys crate build failed: no supported version of OpenSSL found.
  116. Ways to fix it:
  117. - Use the `vendored` feature of openssl-sys crate to build OpenSSL from source.
  118. - Use Homebrew to install the `openssl` package.
  119. ",
  120. );
  121. }
  122. }
  123. if host.contains("unknown-linux")
  124. && target.contains("unknown-linux-gnu")
  125. && Command::new("pkg-config").output().is_err()
  126. {
  127. msg.push_str(
  128. "
  129. It looks like you're compiling on Linux and also targeting Linux. Currently this
  130. requires the `pkg-config` utility to find OpenSSL but unfortunately `pkg-config`
  131. could not be found. If you have OpenSSL installed you can likely fix this by
  132. installing `pkg-config`.
  133. ",
  134. );
  135. }
  136. if host.contains("windows") && target.contains("windows-gnu") {
  137. msg.push_str(
  138. "
  139. It looks like you're compiling for MinGW but you may not have either OpenSSL or
  140. pkg-config installed. You can install these two dependencies with:
  141. pacman -S openssl-devel pkg-config
  142. and try building this crate again.
  143. ",
  144. );
  145. }
  146. if host.contains("windows") && target.contains("windows-msvc") {
  147. msg.push_str(
  148. "
  149. It looks like you're compiling for MSVC but we couldn't detect an OpenSSL
  150. installation. If there isn't one installed then you can try the rust-openssl
  151. README for more information about how to download precompiled binaries of
  152. OpenSSL:
  153. https://github.com/sfackler/rust-openssl#windows
  154. ",
  155. );
  156. }
  157. panic!("{}", msg);
  158. }
  159. /// Attempt to find OpenSSL through pkg-config.
  160. ///
  161. /// Note that if this succeeds then the function does not return as pkg-config
  162. /// typically tells us all the information that we need.
  163. fn try_pkg_config() {
  164. let target = env::var("TARGET").unwrap();
  165. let host = env::var("HOST").unwrap();
  166. // If we're going to windows-gnu we can use pkg-config, but only so long as
  167. // we're coming from a windows host.
  168. //
  169. // Otherwise if we're going to windows we probably can't use pkg-config.
  170. if target.contains("windows-gnu") && host.contains("windows") {
  171. env::set_var("PKG_CONFIG_ALLOW_CROSS", "1");
  172. } else if target.contains("windows") {
  173. return;
  174. }
  175. let lib = match pkg_config::Config::new()
  176. .print_system_libs(false)
  177. .find("openssl")
  178. {
  179. Ok(lib) => lib,
  180. Err(e) => {
  181. println!("run pkg_config fail: {:?}", e);
  182. return;
  183. }
  184. };
  185. super::postprocess(&lib.include_paths);
  186. for include in lib.include_paths.iter() {
  187. println!("cargo:include={}", include.display());
  188. }
  189. process::exit(0);
  190. }
  191. /// Attempt to find OpenSSL through vcpkg.
  192. ///
  193. /// Note that if this succeeds then the function does not return as vcpkg
  194. /// should emit all of the cargo metadata that we need.
  195. #[cfg(target_env = "msvc")]
  196. fn try_vcpkg() {
  197. // vcpkg will not emit any metadata if it can not find libraries
  198. // appropriate for the target triple with the desired linkage.
  199. let lib = match vcpkg::Config::new()
  200. .emit_includes(true)
  201. .find_package("openssl")
  202. {
  203. Ok(lib) => lib,
  204. Err(e) => {
  205. println!("note: vcpkg did not find openssl: {}", e);
  206. return;
  207. }
  208. };
  209. super::postprocess(&lib.include_paths);
  210. println!("cargo:rustc-link-lib=user32");
  211. println!("cargo:rustc-link-lib=gdi32");
  212. println!("cargo:rustc-link-lib=crypt32");
  213. process::exit(0);
  214. }
  215. #[cfg(not(target_env = "msvc"))]
  216. fn try_vcpkg() {}
  217. fn execute_command_and_get_output(cmd: &str, args: &[&str]) -> Option<String> {
  218. let out = Command::new(cmd).args(args).output();
  219. if let Ok(ref r1) = out {
  220. if r1.status.success() {
  221. let r2 = String::from_utf8(r1.stdout.clone());
  222. if let Ok(r3) = r2 {
  223. return Some(r3.trim().to_string());
  224. }
  225. }
  226. }
  227. None
  228. }