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