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