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