summaryrefslogtreecommitdiff
path: root/openssl-sys/build.rs
blob: 7df226f2a459604ab07383bcb2dd453a119a3d5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
extern crate cc;
extern crate pkg_config;
#[cfg(target_env = "msvc")]
extern crate vcpkg;

use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::panic::{self, AssertUnwindSafe};
use std::process::Command;

// The set of `OPENSSL_NO_<FOO>`s that we care about.
const DEFINES: &'static [&'static str] = &[
    "OPENSSL_NO_BUF_FREELISTS",
    "OPENSSL_NO_COMP",
    "OPENSSL_NO_EC",
    "OPENSSL_NO_EC2M",
    "OPENSSL_NO_ENGINE",
    "OPENSSL_NO_KRB5",
    "OPENSSL_NO_NEXTPROTONEG",
    "OPENSSL_NO_PSK",
    "OPENSSL_NO_RFC3779",
    "OPENSSL_NO_SHA",
    "OPENSSL_NO_SRP",
    "OPENSSL_NO_SSL3_METHOD",
    "OPENSSL_NO_TLSEXT",
];

enum Version {
    Openssl110,
    Openssl102,
    Openssl101,
    Libressl,
}

fn env(name: &str) -> Option<OsString> {
    let prefix = env::var("TARGET").unwrap().to_uppercase().replace("-", "_");
    let prefixed = format!("{}_{}", prefix, name);
    println!("cargo:rerun-if-env-changed={}", prefixed);

    if let Some(var) = env::var_os(&prefixed) {
        return Some(var);
    }

    println!("cargo:rerun-if-env-changed={}", name);
    env::var_os(name)
}

fn main() {
    let target = env::var("TARGET").unwrap();

    let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from);
    let include_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from);

    let (lib_dir, include_dir) = if lib_dir.is_none() || include_dir.is_none() {
        let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(&target));
        let openssl_dir = Path::new(&openssl_dir);
        let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib"));
        let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include"));
        (lib_dir, include_dir)
    } else {
        (lib_dir.unwrap(), include_dir.unwrap())
    };

    if !Path::new(&lib_dir).exists() {
        panic!(
            "OpenSSL library directory does not exist: {}",
            lib_dir.to_string_lossy()
        );
    }
    if !Path::new(&include_dir).exists() {
        panic!(
            "OpenSSL include directory does not exist: {}",
            include_dir.to_string_lossy()
        );
    }

    println!(
        "cargo:rustc-link-search=native={}",
        lib_dir.to_string_lossy()
    );
    println!("cargo:include={}", include_dir.to_string_lossy());

    let version = validate_headers(&[include_dir.clone().into()]);

    let libs_env = env("OPENSSL_LIBS");
    let libs = match libs_env.as_ref().and_then(|s| s.to_str()) {
        Some(ref v) => v.split(":").collect(),
        None => match version {
            Version::Openssl101 | Version::Openssl102 if target.contains("windows") => {
                vec!["ssleay32", "libeay32"]
            }
            Version::Openssl110 if target.contains("windows") => vec!["libssl", "libcrypto"],
            _ => vec!["ssl", "crypto"],
        },
    };

    let kind = determine_mode(Path::new(&lib_dir), &libs);
    for lib in libs.into_iter() {
        println!("cargo:rustc-link-lib={}={}", kind, lib);
    }
}

fn find_openssl_dir(target: &str) -> OsString {
    let host = env::var("HOST").unwrap();

    if host == target && target.contains("apple-darwin") {
        let homebrew = Path::new("/usr/local/opt/openssl@1.1");
        if homebrew.exists() {
            return homebrew.to_path_buf().into();
        }
        let homebrew = Path::new("/usr/local/opt/openssl");
        if homebrew.exists() {
            return homebrew.to_path_buf().into();
        }
    }

    try_pkg_config();
    try_vcpkg();

    // FreeBSD ships with OpenSSL but doesn't include a pkg-config file :(
    if host == target && target.contains("freebsd") {
        return OsString::from("/usr");
    }

    let mut msg = format!(
        "

Could not find directory of OpenSSL installation, and this `-sys` crate cannot
proceed without this knowledge. If OpenSSL is installed and this crate had
trouble finding it,  you can set the `OPENSSL_DIR` environment variable for the
compilation process.

If you're in a situation where you think the directory *should* be found
automatically, please open a bug at https://github.com/sfackler/rust-openssl
and include information about your system as well as this message.

    $HOST = {}
    $TARGET = {}
    openssl-sys = {}

",
        host,
        target,
        env!("CARGO_PKG_VERSION")
    );

    if host.contains("apple-darwin") && target.contains("apple-darwin") {
        let system = Path::new("/usr/lib/libssl.0.9.8.dylib");
        if system.exists() {
            msg.push_str(&format!(
                "

It looks like you're compiling on macOS, where the system contains a version of
OpenSSL 0.9.8. This crate no longer supports OpenSSL 0.9.8.

As a consumer of this crate, you can fix this error by using Homebrew to
install the `openssl` package, or as a maintainer you can use the openssl-sys
0.7 crate for support with OpenSSL 0.9.8.

Unfortunately though the compile cannot continue, so aborting.

"
            ));
        }
    }

    if host.contains("unknown-linux") && target.contains("unknown-linux-gnu") {
        if Command::new("pkg-config").output().is_err() {
            msg.push_str(&format!(
                "
It looks like you're compiling on Linux and also targeting Linux. Currently this
requires the `pkg-config` utility to find OpenSSL but unfortunately `pkg-config`
could not be found. If you have OpenSSL installed you can likely fix this by
installing `pkg-config`.

"
            ));
        }
    }

    if host.contains("windows") && target.contains("windows-gnu") {
        msg.push_str(&format!(
            "
It looks like you're compiling for MinGW but you may not have either OpenSSL or
pkg-config installed. You can install these two dependencies with:

    pacman -S openssl-devel pkg-config

and try building this crate again.

"
        ));
    }

    if host.contains("windows") && target.contains("windows-msvc") {
        msg.push_str(&format!(
            "
It looks like you're compiling for MSVC but we couldn't detect an OpenSSL
installation. If there isn't one installed then you can try the rust-openssl
README for more information about how to download precompiled binaries of
OpenSSL:

    https://github.com/sfackler/rust-openssl#windows

"
        ));
    }

    panic!(msg);
}

/// Attempt to find OpenSSL through pkg-config.
///
/// Note that if this succeeds then the function does not return as pkg-config
/// typically tells us all the information that we need.
fn try_pkg_config() {
    let target = env::var("TARGET").unwrap();
    let host = env::var("HOST").unwrap();

    // If we're going to windows-gnu we can use pkg-config, but only so long as
    // we're coming from a windows host.
    //
    // Otherwise if we're going to windows we probably can't use pkg-config.
    if target.contains("windows-gnu") && host.contains("windows") {
        env::set_var("PKG_CONFIG_ALLOW_CROSS", "1");
    } else if target.contains("windows") {
        return;
    }

    let lib = match pkg_config::Config::new()
        .print_system_libs(false)
        .find("openssl")
    {
        Ok(lib) => lib,
        Err(e) => {
            println!("run pkg_config fail: {:?}", e);
            return;
        }
    };

    validate_headers(&lib.include_paths);

    for include in lib.include_paths.iter() {
        println!("cargo:include={}", include.display());
    }

    std::process::exit(0);
}

/// Attempt to find OpenSSL through vcpkg.
///
/// Note that if this succeeds then the function does not return as vcpkg
/// should emit all of the cargo metadata that we need.
#[cfg(target_env = "msvc")]
fn try_vcpkg() {
    // vcpkg will not emit any metadata if it can not find libraries
    // appropriate for the target triple with the desired linkage.

    let mut lib = vcpkg::Config::new()
        .emit_includes(true)
        .lib_name("libcrypto")
        .lib_name("libssl")
        .probe("openssl");

    if let Err(e) = lib {
        println!(
            "note: vcpkg did not find openssl as libcrypto and libssl : {:?}",
            e
        );
        lib = vcpkg::Config::new()
            .emit_includes(true)
            .lib_name("libeay32")
            .lib_name("ssleay32")
            .probe("openssl");
    }
    if let Err(e) = lib {
        println!(
            "note: vcpkg did not find openssl as ssleay32 and libeay32: {:?}",
            e
        );
        return;
    }

    let lib = lib.unwrap();
    validate_headers(&lib.include_paths);

    println!("cargo:rustc-link-lib=user32");
    println!("cargo:rustc-link-lib=gdi32");
    println!("cargo:rustc-link-lib=crypt32");

    std::process::exit(0);
}

#[cfg(not(target_env = "msvc"))]
fn try_vcpkg() {}

/// Validates the header files found in `include_dir` and then returns the
/// version string of OpenSSL.
fn validate_headers(include_dirs: &[PathBuf]) -> Version {
    // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, and 1.1.0. To
    // correctly expose the right API from this crate, take a look at
    // `opensslv.h` to see what version OpenSSL claims to be.
    //
    // OpenSSL has a number of build-time configuration options which affect
    // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem
    // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem.
    //
    // To handle all this conditional compilation we slurp up the configuration
    // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines
    // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can
    // account for compile differences and such.
    let mut path = PathBuf::from(env::var_os("OUT_DIR").unwrap());
    path.push("expando.c");
    let mut file = BufWriter::new(File::create(&path).unwrap());

    write!(
        file,
        "\
#include <openssl/opensslv.h>
#include <openssl/opensslconf.h>

#if LIBRESSL_VERSION_NUMBER >= 0x20700000
RUST_LIBRESSL_NEW
#elif LIBRESSL_VERSION_NUMBER >= 0x20603000
RUST_LIBRESSL_26X
#elif LIBRESSL_VERSION_NUMBER >= 0x20602000
RUST_LIBRESSL_262
#elif LIBRESSL_VERSION_NUMBER >= 0x20601000
RUST_LIBRESSL_261
#elif LIBRESSL_VERSION_NUMBER >= 0x20600000
RUST_LIBRESSL_260
#elif LIBRESSL_VERSION_NUMBER >= 0x20503000
RUST_LIBRESSL_25X
#elif LIBRESSL_VERSION_NUMBER >= 0x20502000
RUST_LIBRESSL_252
#elif LIBRESSL_VERSION_NUMBER >= 0x20501000
RUST_LIBRESSL_251
#elif LIBRESSL_VERSION_NUMBER >= 0x20500000
RUST_LIBRESSL_250
#elif defined (LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20500000
RUST_LIBRESSL_OLD
#elif OPENSSL_VERSION_NUMBER >= 0x10102000
RUST_OPENSSL_NEW
#elif OPENSSL_VERSION_NUMBER >= 0x10101000
RUST_OPENSSL_111
#elif OPENSSL_VERSION_NUMBER >= 0x10100060
RUST_OPENSSL_110F
#elif OPENSSL_VERSION_NUMBER >= 0x10100000
RUST_OPENSSL_110
#elif OPENSSL_VERSION_NUMBER >= 0x10002000
RUST_OPENSSL_102
#elif OPENSSL_VERSION_NUMBER >= 0x10001000
RUST_OPENSSL_101
#else
RUST_OPENSSL_OLD
#endif
"
    ).unwrap();

    for define in DEFINES {
        write!(
            file,
            "\
#ifdef {define}
RUST_{define}_RUST
#endif
",
            define = define
        ).unwrap();
    }

    file.flush().unwrap();
    drop(file);

    let mut gcc = cc::Build::new();
    for include_dir in include_dirs {
        gcc.include(include_dir);
    }
    // https://github.com/alexcrichton/gcc-rs/issues/133
    let expanded = match panic::catch_unwind(AssertUnwindSafe(|| gcc.file(&path).expand())) {
        Ok(expanded) => expanded,
        Err(_) => {
            panic!(
                "
Failed to find OpenSSL development headers.

You can try fixing this setting the `OPENSSL_DIR` environment variable
pointing to your OpenSSL installation or installing OpenSSL headers package
specific to your distribution:

    # On Ubuntu
    sudo apt-get install libssl-dev
    # On Arch Linux
    sudo pacman -S openssl
    # On Fedora
    sudo dnf install openssl-devel

See rust-openssl README for more information:

    https://github.com/sfackler/rust-openssl#linux
"
            );
        }
    };
    let expanded = String::from_utf8(expanded).unwrap();

    let mut enabled = vec![];
    for &define in DEFINES {
        if expanded.contains(&format!("RUST_{}_RUST", define)) {
            println!("cargo:rustc-cfg=osslconf=\"{}\"", define);
            enabled.push(define);
        }
    }
    println!("cargo:conf={}", enabled.join(","));

    if expanded.contains("RUST_LIBRESSL_250") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl250");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=250");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_251") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl251");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=251");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_252") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl252");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=252");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_25X") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl25x");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=25x");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_260") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl260");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=260");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_261") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl261");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=261");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_262") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl262");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=262");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_LIBRESSL_26X") {
        println!("cargo:rustc-cfg=libressl");
        println!("cargo:rustc-cfg=libressl26x");
        println!("cargo:libressl=true");
        println!("cargo:libressl_version=26x");
        println!("cargo:version=101");
        Version::Libressl
    } else if expanded.contains("RUST_OPENSSL_111") {
        println!("cargo:rustc-cfg=ossl111");
        println!("cargo:rustc-cfg=ossl110");
        println!("cargo:version=111");
        Version::Openssl110
    } else if expanded.contains("RUST_OPENSSL_110F") {
        println!("cargo:rustc-cfg=ossl110");
        println!("cargo:rustc-cfg=ossl110f");
        println!("cargo:version=110");
        println!("cargo:patch=f");
        Version::Openssl110
    } else if expanded.contains("RUST_OPENSSL_110") {
        println!("cargo:rustc-cfg=ossl110");
        println!("cargo:version=110");
        Version::Openssl110
    } else if expanded.contains("RUST_OPENSSL_102") {
        println!("cargo:rustc-cfg=ossl102");
        println!("cargo:version=102");
        Version::Openssl102
    } else if expanded.contains("RUST_OPENSSL_101") {
        println!("cargo:rustc-cfg=ossl101");
        println!("cargo:version=101");
        Version::Openssl101
    } else {
        panic!(
            "

This crate is only compatible with OpenSSL 1.0.1 through 1.1.1, or LibreSSL 2.5
and 2.6, but a different version of OpenSSL was found. The build is now aborting
due to this version mismatch.

"
        );
    }
}

/// Given a libdir for OpenSSL (where artifacts are located) as well as the name
/// of the libraries we're linking to, figure out whether we should link them
/// statically or dynamically.
fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str {
    // First see if a mode was explicitly requested
    let kind = env("OPENSSL_STATIC");
    match kind.as_ref().and_then(|s| s.to_str()).map(|s| &s[..]) {
        Some("0") => return "dylib",
        Some(_) => return "static",
        None => {}
    }

    // Next, see what files we actually have to link against, and see what our
    // possibilities even are.
    let files = libdir
        .read_dir()
        .unwrap()
        .map(|e| e.unwrap())
        .map(|e| e.file_name())
        .filter_map(|e| e.into_string().ok())
        .collect::<HashSet<_>>();
    let can_static = libs.iter()
        .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l)));
    let can_dylib = libs.iter().all(|l| {
        files.contains(&format!("lib{}.so", l)) || files.contains(&format!("{}.dll", l))
            || files.contains(&format!("lib{}.dylib", l))
    });
    match (can_static, can_dylib) {
        (true, false) => return "static",
        (false, true) => return "dylib",
        (false, false) => {
            panic!(
                "OpenSSL libdir at `{}` does not contain the required files \
                 to either statically or dynamically link OpenSSL",
                libdir.display()
            );
        }
        (true, true) => {}
    }

    // Ok, we've got not explicit preference and can *either* link statically or
    // link dynamically. In the interest of "security upgrades" and/or "best
    // practices with security libs", let's link dynamically.
    "dylib"
}