1 #![allow(clippy::inconsistent_digit_grouping, clippy::unusual_byte_groupings)]
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) => {
89             if v.is_empty() {
90                 vec![]
91             } else {
92                 v.split(':').collect()
93             }
94         }
95         None => match version {
96             Version::Openssl10x if target.contains("windows") => vec!["ssleay32", "libeay32"],
97             Version::Openssl11x if target.contains("windows-msvc") => vec!["libssl", "libcrypto"],
98             _ => vec!["ssl", "crypto"],
99         },
100     };
101 
102     let kind = determine_mode(Path::new(&lib_dir), &libs);
103     for lib in libs.into_iter() {
104         println!("cargo:rustc-link-lib={}={}", kind, lib);
105     }
106 
107     if kind == "static" && target.contains("windows") {
108         println!("cargo:rustc-link-lib=dylib=gdi32");
109         println!("cargo:rustc-link-lib=dylib=user32");
110         println!("cargo:rustc-link-lib=dylib=crypt32");
111         println!("cargo:rustc-link-lib=dylib=ws2_32");
112         println!("cargo:rustc-link-lib=dylib=advapi32");
113     }
114 }
115 
check_rustc_versions()116 fn check_rustc_versions() {
117     let cfg = autocfg::new();
118 
119     if cfg.probe_rustc_version(1, 31) {
120         println!("cargo:rustc-cfg=const_fn");
121     }
122 }
123 
124 /// Validates the header files found in `include_dir` and then returns the
125 /// version string of OpenSSL.
126 #[allow(clippy::manual_strip)] // we need to support pre-1.45.0
validate_headers(include_dirs: &[PathBuf]) -> Version127 fn validate_headers(include_dirs: &[PathBuf]) -> Version {
128     // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, and 1.1.0. To
129     // correctly expose the right API from this crate, take a look at
130     // `opensslv.h` to see what version OpenSSL claims to be.
131     //
132     // OpenSSL has a number of build-time configuration options which affect
133     // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem
134     // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem.
135     //
136     // To handle all this conditional compilation we slurp up the configuration
137     // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines
138     // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can
139     // account for compile differences and such.
140     let mut gcc = cc::Build::new();
141     for include_dir in include_dirs {
142         gcc.include(include_dir);
143     }
144     let expanded = match gcc.file("build/expando.c").try_expand() {
145         Ok(expanded) => expanded,
146         Err(e) => {
147             panic!(
148                 "
149 Header expansion error:
150 {:?}
151 
152 Failed to find OpenSSL development headers.
153 
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 
158     # On Ubuntu
159     sudo apt-get install libssl-dev
160     # On Arch Linux
161     sudo pacman -S openssl
162     # On Fedora
163     sudo dnf install openssl-devel
164 
165 See rust-openssl README for more information:
166 
167     https://github.com/sfackler/rust-openssl#linux
168 ",
169                 e
170             );
171         }
172     };
173     let expanded = String::from_utf8(expanded).unwrap();
174 
175     let mut enabled = vec![];
176     let mut openssl_version = None;
177     let mut libressl_version = None;
178     for line in expanded.lines() {
179         let line = line.trim();
180 
181         let openssl_prefix = "RUST_VERSION_OPENSSL_";
182         let libressl_prefix = "RUST_VERSION_LIBRESSL_";
183         let conf_prefix = "RUST_CONF_";
184         if line.starts_with(openssl_prefix) {
185             let version = &line[openssl_prefix.len()..];
186             openssl_version = Some(parse_version(version));
187         } else if line.starts_with(libressl_prefix) {
188             let version = &line[libressl_prefix.len()..];
189             libressl_version = Some(parse_version(version));
190         } else if line.starts_with(conf_prefix) {
191             enabled.push(&line[conf_prefix.len()..]);
192         }
193     }
194 
195     for enabled in &enabled {
196         println!("cargo:rustc-cfg=osslconf=\"{}\"", enabled);
197     }
198     println!("cargo:conf={}", enabled.join(","));
199 
200     for cfg in cfgs::get(openssl_version, libressl_version) {
201         println!("cargo:rustc-cfg={}", cfg);
202     }
203 
204     if let Some(libressl_version) = libressl_version {
205         println!("cargo:libressl_version_number={:x}", libressl_version);
206 
207         let major = (libressl_version >> 28) as u8;
208         let minor = (libressl_version >> 20) as u8;
209         let fix = (libressl_version >> 12) as u8;
210         let (major, minor, fix) = match (major, minor, fix) {
211             (2, 5, 0) => ('2', '5', '0'),
212             (2, 5, 1) => ('2', '5', '1'),
213             (2, 5, 2) => ('2', '5', '2'),
214             (2, 5, _) => ('2', '5', 'x'),
215             (2, 6, 0) => ('2', '6', '0'),
216             (2, 6, 1) => ('2', '6', '1'),
217             (2, 6, 2) => ('2', '6', '2'),
218             (2, 6, _) => ('2', '6', 'x'),
219             (2, 7, _) => ('2', '7', 'x'),
220             (2, 8, 0) => ('2', '8', '0'),
221             (2, 8, 1) => ('2', '8', '1'),
222             (2, 8, _) => ('2', '8', 'x'),
223             (2, 9, 0) => ('2', '9', '0'),
224             (2, 9, _) => ('2', '9', 'x'),
225             (3, 0, 0) => ('3', '0', '0'),
226             (3, 0, 1) => ('3', '0', '1'),
227             (3, 0, _) => ('3', '0', 'x'),
228             (3, 1, 0) => ('3', '1', '0'),
229             (3, 1, _) => ('3', '1', 'x'),
230             (3, 2, 0) => ('3', '2', '0'),
231             (3, 2, 1) => ('3', '2', '1'),
232             (3, 2, _) => ('3', '2', 'x'),
233             (3, 3, 0) => ('3', '3', '0'),
234             (3, 3, 1) => ('3', '3', '1'),
235             _ => version_error(),
236         };
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 
246         if openssl_version >= 0x1_01_02_00_0 {
247             version_error()
248         } else if openssl_version >= 0x1_01_01_00_0 {
249             println!("cargo:version=111");
250             Version::Openssl11x
251         } else if openssl_version >= 0x1_01_00_06_0 {
252             println!("cargo:version=110");
253             println!("cargo:patch=f");
254             Version::Openssl11x
255         } else if openssl_version >= 0x1_01_00_00_0 {
256             println!("cargo:version=110");
257             Version::Openssl11x
258         } else if openssl_version >= 0x1_00_02_00_0 {
259             println!("cargo:version=102");
260             Version::Openssl10x
261         } else if openssl_version >= 0x1_00_01_00_0 {
262             println!("cargo:version=101");
263             Version::Openssl10x
264         } else {
265             version_error()
266         }
267     }
268 }
269 
version_error() -> !270 fn version_error() -> ! {
271     panic!(
272         "
273 
274 This crate is only compatible with OpenSSL 1.0.1 through 1.1.1, or LibreSSL 2.5
275 through 3.3.1, but a different version of OpenSSL was found. The build is now aborting
276 due to this version mismatch.
277 
278 "
279     );
280 }
281 
282 // parses a string that looks like "0x100020cfL"
283 #[allow(deprecated)] // trim_right_matches is now trim_end_matches
284 #[allow(clippy::match_like_matches_macro)] // matches macro requires rust 1.42.0
parse_version(version: &str) -> u64285 fn parse_version(version: &str) -> u64 {
286     // cut off the 0x prefix
287     assert!(version.starts_with("0x"));
288     let version = &version[2..];
289 
290     // and the type specifier suffix
291     let version = version.trim_right_matches(|c: char| match c {
292         '0'..='9' | 'a'..='f' | 'A'..='F' => false,
293         _ => true,
294     });
295 
296     u64::from_str_radix(version, 16).unwrap()
297 }
298 
299 /// Given a libdir for OpenSSL (where artifacts are located) as well as the name
300 /// of the libraries we're linking to, figure out whether we should link them
301 /// statically or dynamically.
determine_mode(libdir: &Path, libs: &[&str]) -> &'static str302 fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str {
303     // First see if a mode was explicitly requested
304     let kind = env("OPENSSL_STATIC");
305     match kind.as_ref().and_then(|s| s.to_str()).map(|s| &s[..]) {
306         Some("0") => return "dylib",
307         Some(_) => return "static",
308         None => {}
309     }
310 
311     // Next, see what files we actually have to link against, and see what our
312     // possibilities even are.
313     let files = libdir
314         .read_dir()
315         .unwrap()
316         .map(|e| e.unwrap())
317         .map(|e| e.file_name())
318         .filter_map(|e| e.into_string().ok())
319         .collect::<HashSet<_>>();
320     let can_static = libs
321         .iter()
322         .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l)));
323     let can_dylib = libs.iter().all(|l| {
324         files.contains(&format!("lib{}.so", l))
325             || files.contains(&format!("{}.dll", l))
326             || files.contains(&format!("lib{}.dylib", l))
327     });
328     match (can_static, can_dylib) {
329         (true, false) => return "static",
330         (false, true) => return "dylib",
331         (false, false) => {
332             panic!(
333                 "OpenSSL libdir at `{}` does not contain the required files \
334                  to either statically or dynamically link OpenSSL",
335                 libdir.display()
336             );
337         }
338         (true, true) => {}
339     }
340 
341     // Ok, we've got not explicit preference and can *either* link statically or
342     // link dynamically. In the interest of "security upgrades" and/or "best
343     // practices with security libs", let's link dynamically.
344     "dylib"
345 }
346