i2pd-sys 0.0.1

Raw FFI bindings to a minimal C shim over libi2pd (PurpleI2P/i2pd).
Documentation
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
//! Builds `libi2pd`/`libi2pdclient` (from the committed `vendor/i2pd-src` snapshot) via CMake,
//! builds a minimal Boost subset (`vendor/boost-src`, extracted from the upstream git
//! superproject with `bcp`) via its own CMake support, compiles zlib (`vendor/zlib-src`) and the
//! C++ shim directly via `cc`, and generates Rust bindings against the shim header only (never
//! against libi2pd's own C++ headers).
//!
//! No shelling out to `configure`/`b2`/`bootstrap.sh` anywhere -- every dependency here is either
//! compiled directly (`cc::Build`) or driven through plain CMake (`cmake::Config`), matching how
//! `aws-lc-sys` builds AWS-LC: commit source, then compile it with ordinary build tooling. OpenSSL
//! is not vendored at all -- i2pd links against AWS-LC (via the `aws-lc-sys` dependency already
//! paid for elsewhere in this workspace through `aws-lc-rs`) instead, or against AWS-LC-FIPS (via
//! `aws-lc-fips-sys`) when the `fips` feature is enabled in place of the default `aws-lc` feature
//! -- see the `crypto_crate`/`include_var`/`libcrypto_var`/`libssl_var` branch below and
//! `src/lib.rs`'s crate docs for what that trade-off actually gets you; see `openssl_stub_lib`
//! below for why not having a real static-lib path from either crate at CMake-configure time is
//! safe.
//!
//! Toolchain selection: when `TARGET == HOST`, the ambient system `cc`/`c++` is used (covers a
//! plain glibc Linux build, and also covers building natively inside a musl system like an
//! Alpine container -- no custom toolchain needed in either case). True cross-compilation
//! (e.g. a glibc host targeting `x86_64-unknown-linux-musl`) requires a real musl C++ cross
//! toolchain to already exist on the machine (no C++ compiler shipped by default on glibc
//! distros can target musl) -- see `resolve_cross_compilers` for how that's located.

use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

fn main() {
    // Fail fast, before spending minutes compiling zlib/Boost/i2pd: src/lib.rs also has
    // compile_error! guards for these two cases, but build.rs runs *before* the crate itself
    // gets compiled, so leaving this check only in lib.rs means an invalid feature selection
    // would instead surface as a confusing panic deep in the AWS-LC `DEP_*` lookup below (it'd
    // be missing because the corresponding optional dependency was never pulled in), only after
    // the entire native build already ran.
    let fips = env::var("CARGO_FEATURE_FIPS").is_ok();
    let aws_lc = env::var("CARGO_FEATURE_AWS_LC").is_ok();
    match (aws_lc, fips) {
        (true, true) => panic!(
            "features `aws-lc` and `fips` are mutually exclusive -- pick exactly one: \
             `--features fips` alone needs `default-features = false` too, since `aws-lc` is on \
             by default."
        ),
        (false, false) => panic!(
            "no crypto backend feature selected -- enable exactly one of the `aws-lc` (default) \
             or `fips` features."
        ),
        _ => {}
    }

    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
    let vendor_dir = manifest_dir.join("vendor");
    let i2pd_dir = vendor_dir.join("i2pd-src");
    let boost_dir = vendor_dir.join("boost-src");
    let zlib_dir = vendor_dir.join("zlib-src");

    let target = env::var("TARGET").expect("TARGET");
    let host = env::var("HOST").expect("HOST");
    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));

    let compilers = if target == host {
        None // ambient cc/c++ -- native build, including native-musl-on-musl (e.g. Alpine)
    } else {
        Some(resolve_cross_compilers(&target))
    };

    // --- zlib: compiled directly, no `./configure` ---
    let zlib_lib = build_zlib(&zlib_dir, &out_dir, compilers.as_ref());

    // --- Boost: minimal subset, built via its own CMake support (no b2) ---
    let boost_install = build_boost(&boost_dir, compilers.as_ref());

    // --- AWS-LC (via aws-lc-sys) or AWS-LC-FIPS (via aws-lc-fips-sys) stands in for OpenSSL --
    // exactly one is ever linked in, selected by the mutually-exclusive `aws-lc` (default) /
    // `fips` features (see the compile_error! guard in src/lib.rs). Both crates publish the same
    // `cargo:include=` / `cargo:libcrypto=` / `cargo:libssl=` build-script metadata convention
    // under their own `links` name, so the two backends differ here only in which `DEP_*`
    // variable prefix gets read -- update BOTH prefixes below if either crate's version pin
    // drifts (the version number is baked into its `links` name, hence into these var names).
    let (crypto_crate, include_var, libcrypto_var, libssl_var) = if cfg!(feature = "fips") {
        (
            "aws-lc-fips-sys",
            "DEP_AWS_LC_FIPS_0_13_16_INCLUDE",
            "DEP_AWS_LC_FIPS_0_13_16_LIBCRYPTO",
            "DEP_AWS_LC_FIPS_0_13_16_LIBSSL",
        )
    } else {
        (
            "aws-lc-sys",
            "DEP_AWS_LC_0_43_0_INCLUDE",
            "DEP_AWS_LC_0_43_0_LIBCRYPTO",
            "DEP_AWS_LC_0_43_0_LIBSSL",
        )
    };
    let openssl_include = PathBuf::from(env::var(include_var).unwrap_or_else(|_| {
        panic!(
            "{include_var} not set -- {crypto_crate}'s version pin drifted? update the `links` \
             name referenced here to match Cargo.lock"
        )
    }));
    let openssl_crypto_stub = openssl_stub_lib(&out_dir, "crypto", compilers.as_ref());
    let openssl_ssl_stub = openssl_stub_lib(&out_dir, "ssl", compilers.as_ref());

    // --- i2pd itself ---
    let i2pd_install = build_i2pd(
        &i2pd_dir,
        &boost_install,
        &openssl_include,
        &openssl_crypto_stub,
        &openssl_ssl_stub,
        &zlib_dir,
        &zlib_lib,
        compilers.as_ref(),
    );

    println!(
        "cargo:rustc-link-search=native={}",
        i2pd_install.join("lib").display()
    );
    println!(
        "cargo:rustc-link-search=native={}",
        boost_install.join("lib").display()
    );
    println!("cargo:rustc-link-search=native={}", zlib_lib.parent().unwrap().display());

    // aws-lc-sys's/aws-lc-fips-sys's own build script emits its `-L` search path correctly, but
    // its own `cargo:rustc-link-lib` directives are keyed to link *names* that drift with its
    // version pin -- re-emitting our own, using the exact names it publishes via `DEP_*`, is
    // simpler than trying to keep a hardcoded name in sync across upgrades.
    let aws_lc_crypto = env::var(libcrypto_var)
        .unwrap_or_else(|_| panic!("{libcrypto_var} not set -- see the INCLUDE var comment above"));
    let aws_lc_ssl = env::var(libssl_var).ok();

    // --- shim: hand-written C++ FFI surface, compiled directly ---
    let mut shim = cc::Build::new();
    shim.cpp(true).std("c++17").warnings(false);
    if let Some(c) = &compilers {
        shim.compiler(&c.cxx);
    }
    for flag in HARDENING_CFLAGS {
        shim.flag_if_supported(flag);
    }
    shim.include(i2pd_dir.join("libi2pd"))
        .include(i2pd_dir.join("libi2pd_client"))
        .include(boost_install.join("include"))
        .include(&openssl_include)
        .include(zlib_dir)
        .file("shim/shim.cpp")
        .compile("tachyon_i2pd_shim");
    println!("cargo:rustc-link-search=native={}", out_dir.display());

    // Every static lib this crate needs linked into whatever final binary depends on it --
    // including transitively, through `tachyon-i2p`/`tachyon-web` several package boundaries
    // away. That distinction matters: `cargo:rustc-link-arg` (raw linker flags) is explicitly
    // documented as taking effect *only* for the current package's own build targets, never for
    // downstream dependents -- which would silently drop every one of these libraries from e.g.
    // `tachyon-web`'s own binaries/tests, which only reach this crate three `Cargo.toml`s away.
    // `cargo:rustc-link-lib` is the directive documented to propagate to dependents' link lines,
    // which is what's needed here.
    //
    // Listed in dependency order (dependent before its dependency) so a single left-to-right
    // pass -- the model a strict linker like GNU `ld` (used for musl cross-compilation) uses --
    // already resolves everything without needing a `--start-group`/`--end-group` wrapper (which
    // would have the same downstream-propagation problem as any other raw linker arg). `libssl`
    // needing symbols from `libcrypto` is why the AWS-LC pair is ordered ssl-then-crypto, same
    // logic as everything above it. `i2pd` before `i2pdclient` before `i2pdlang` mirrors i2pd's
    // own upstream CMake link line (`build/CMakeLists.txt`'s `WITH_BINARY` target) -- the shim
    // only actually calls into `libi2pd` (api.h/Destination.h/Streaming.h/Identity.h all live
    // there, not in libi2pd_client), so `i2pdclient` is along only for symbols `i2pd` itself
    // might pull in from it; harmless to list either way since an archive with nothing
    // referenced from it contributes no object files to the final link.
    for lib in ["tachyon_i2pd_shim", "i2pd", "i2pdclient", "i2pdlang"] {
        println!("cargo:rustc-link-lib=static:+verbatim=lib{lib}.a");
    }
    // Every compiled (non-header-only) static lib CMake produced for our BOOST_INCLUDE_LIBRARIES
    // closure -- asio/property_tree are header-only, no .a produced for either. Harmless to list
    // libs i2pd doesn't actually reference: the linker only pulls in archive members that are
    // actually used.
    // (boost_system is header-only since Boost 1.69 -- no .a produced for it either.
    // serialization/wserialization/spirit/phoenix/proto/thread/chrono/ratio were all removed
    // from the vendored snapshot entirely -- see SNAPSHOT_NOTES.txt in vendor/boost-src -- since
    // nothing in i2pd's own source ever includes boost/serialization, boost/archive,
    // boost/thread, or boost/chrono (it uses std::thread/std::chrono throughout). That whole
    // chain was only present because property_tree's upstream CMakeLists.txt unconditionally
    // declares a `Boost::serialization` link dependency for an optional ptree-serialization
    // feature i2pd's actual headers never touch; serialization pulls in spirit, which in turn
    // pulls in thread (hence chrono, hence ratio) -- patching that one dependency edge out of
    // property_tree's CMakeLists.txt let all six be removed as a connected, verified-orphaned
    // chain, not six independent guesses.)
    for lib in ["filesystem", "program_options", "atomic", "date_time", "container"] {
        println!("cargo:rustc-link-lib=static:+verbatim=libboost_{lib}.a");
    }
    println!("cargo:rustc-link-lib=static:+verbatim=libz.a");
    if let Some(aws_lc_ssl) = &aws_lc_ssl {
        println!("cargo:rustc-link-lib=static:+verbatim=lib{aws_lc_ssl}.a");
    }
    println!("cargo:rustc-link-lib=static:+verbatim=lib{aws_lc_crypto}.a");
    // `cc::Build` (used for the shim and zlib above) already emits `cargo:rustc-link-lib=stdc++`
    // automatically for a C++ build (its default `cargo_metadata(true)`), which -- being a plain
    // `rustc-link-lib` directive, not a raw link arg -- propagates downstream the same as
    // everything else here, so no explicit libstdc++ entry is needed in this list.

    // --- bindgen, against the shim header only ---
    let bindings = bindgen::Builder::default()
        .header("shim/shim.h")
        .allowlist_function("i2pd_.*")
        .allowlist_type("I2pd.*")
        .generate()
        .expect("bindgen failed to generate shim bindings");
    bindings
        .write_to_file(out_dir.join("bindings.rs"))
        .expect("failed to write bindgen bindings.rs");

    println!("cargo:rerun-if-changed=shim/shim.h");
    println!("cargo:rerun-if-changed=shim/shim.cpp");
}

struct CrossCompilers {
    cc: PathBuf,
    cxx: PathBuf,
    ar: Option<PathBuf>,
}

/// Locates a musl C++ cross toolchain for true cross-compilation (glibc host, musl target).
/// Checked in order: `CXX_<target>` / `CC_<target>` env vars (the standard `cc`-crate
/// convention), then `MUSL_CROSS_TOOLCHAIN` pointing at a `musl-cross-make`-style install
/// (`<dir>/bin/<target-triple>-g++`), then a same-named compiler already on `$PATH`. Deliberately
/// does *not* try to build a toolchain from scratch here -- that's a 20-40 minute surprise on a
/// library crate's first build and isn't how other native-FFI crates in the ecosystem handle
/// less-common cross targets either. See `i2pd-sys/README.md` for how to set one up
/// (`musl-cross-make`, pinned in this repo's history from the R&D phase of this feature).
fn resolve_cross_compilers(target: &str) -> CrossCompilers {
    let env_key = |prefix: &str| format!("{prefix}_{}", target.replace('-', "_"));

    if let (Ok(cc), Ok(cxx)) = (env::var(env_key("CC")), env::var(env_key("CXX"))) {
        return CrossCompilers {
            cc: cc.into(),
            cxx: cxx.into(),
            ar: env::var(env_key("AR")).ok().map(PathBuf::from),
        };
    }

    if let Ok(toolchain_dir) = env::var("MUSL_CROSS_TOOLCHAIN") {
        let bin = PathBuf::from(&toolchain_dir).join("bin");
        let cc = bin.join(format!("{target}-gcc"));
        let cxx = bin.join(format!("{target}-g++"));
        if cxx.exists() {
            let ar = bin.join(format!("{target}-ar"));
            return CrossCompilers { cc, cxx, ar: ar.exists().then_some(ar) };
        }
    }

    let path_cc = format!("{target}-gcc");
    let path_cxx = format!("{target}-g++");
    if which(&path_cxx) {
        return CrossCompilers {
            cc: path_cc.into(),
            cxx: path_cxx.into(),
            ar: which(&format!("{target}-ar")).then(|| format!("{target}-ar").into()),
        };
    }

    panic!(
        "cross-compiling to `{target}` needs a real musl C++ toolchain (binutils+gcc+musl+\
         libstdc++) -- no C++ compiler shipped by default on a glibc host can target musl. \
         Point `MUSL_CROSS_TOOLCHAIN` at a `musl-cross-make` install (containing \
         bin/{target}-g++), or set `CC_{t}`/`CXX_{t}` directly, or put `{target}-g++` on \
         $PATH. See i2pd-sys/README.md for how to build one with musl-cross-make. (Building \
         natively *inside* a musl system, e.g. an Alpine container, needs none of this --\
         only true cross-compilation from a non-musl host does.)",
        t = target.replace('-', "_"),
    );
}

fn which(cmd: &str) -> bool {
    Command::new(cmd)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// `_FORTIFY_SOURCE=2` (buffer-overflow-checked libc call variants -- needs `-O1`+, which every
/// build here already has via `CMAKE_BUILD_TYPE=Release`/`cc::Build`'s release-profile default;
/// silently a no-op, not an error, under an unoptimized debug build) and `-fstack-protector-strong`
/// (broader coverage than plain `-fstack-protector`: any function with a local array or a
/// address-taken local, not just ones GCC's narrower heuristic flags) applied to every C/C++
/// translation unit this crate compiles -- zlib (decompresses attacker-controlled network data),
/// the shim, and i2pd itself (parses the raw I2P wire protocol from arbitrary peers) are all
/// exactly the kind of code these mitigations exist for. Deliberately *not* relying on i2pd's own
/// `WITH_HARDENING` CMake option for this: reading `vendor/i2pd-src/build/CMakeLists.txt` shows
/// it's wired up only under `CMAKE_CXX_COMPILER_ID STREQUAL "GNU"` -- a silent no-op under Clang
/// (confirmed empirically: it's what this sandbox's ambient `cc`/`c++` resolves to), which isn't
/// an exotic case this crate needs to worry about only in theory -- `build.rs` already documents
/// "ambient system cc/c++" as the whole native (non-cross) build path. Passed as plain compiler
/// flags here instead, identical on GCC and Clang, so it isn't compiler-dependent.
const HARDENING_CFLAGS: [&str; 2] = ["-D_FORTIFY_SOURCE=2", "-fstack-protector-strong"];

fn build_zlib(zlib_dir: &Path, out_dir: &Path, compilers: Option<&CrossCompilers>) -> PathBuf {
    let sources = [
        "adler32.c", "compress.c", "crc32.c", "deflate.c", "gzclose.c", "gzlib.c", "gzread.c",
        "gzwrite.c", "infback.c", "inflate.c", "inftrees.c", "inffast.c", "trees.c", "uncompr.c",
        "zutil.c",
    ];
    let mut build = cc::Build::new();
    // Normally `./configure` probes for and defines this; since we compile zlib directly
    // without it, supply it ourselves -- true on every target this crate supports (POSIX).
    build.warnings(false).include(zlib_dir).define("HAVE_UNISTD_H", None);
    if let Some(c) = compilers {
        build.compiler(&c.cc);
    }
    for flag in HARDENING_CFLAGS {
        build.flag_if_supported(flag);
    }
    for src in sources {
        build.file(zlib_dir.join(src));
    }
    build.compile("z");
    out_dir.join("libz.a")
}

fn build_boost(boost_dir: &Path, compilers: Option<&CrossCompilers>) -> PathBuf {
    let mut cfg = cmake::Config::new(boost_dir);
    cfg.define(
        "BOOST_INCLUDE_LIBRARIES",
        "filesystem;program_options;atomic;system;date_time;asio;property_tree;dynamic_bitset",
    )
    .define("CMAKE_BUILD_TYPE", "Release")
    .define("BUILD_TESTING", "OFF")
    .build_target("install");
    apply_cross(&mut cfg, compilers);
    cfg.build()
}

/// i2pd's CMake does `find_package(OpenSSL REQUIRED)` producing `OpenSSL::Crypto`/`OpenSSL::SSL`
/// imported *static*-library targets. Because i2pd (`WITH_BINARY=OFF`) only ever builds static
/// libraries here (`ar`-archiving `.o` files into `libi2pd.a` etc.), those imported targets are
/// never actually linked at *this* stage -- static-library archiving doesn't resolve symbols.
/// Real symbol resolution against AWS-LC's actual compiled crypto/ssl code happens later, at
/// whatever final binary links against `i2pd-sys` (via aws-lc-sys's own `cargo:rustc-link-lib`
/// directives -- see the comment in `main()`). CMake's `find_package(OpenSSL REQUIRED)` still
/// insists the configured `OPENSSL_CRYPTO_LIBRARY`/`OPENSSL_SSL_LIBRARY` paths exist on disk
/// (it's a hard existence check), so this creates a trivial empty static archive purely to
/// satisfy that check -- its contents are never used.
fn openssl_stub_lib(out_dir: &Path, name: &str, compilers: Option<&CrossCompilers>) -> PathBuf {
    let stub_dir = out_dir.join("openssl-stub");
    std::fs::create_dir_all(&stub_dir).expect("create openssl-stub dir");
    let stub_c = stub_dir.join(format!("{name}_stub.c"));
    std::fs::write(&stub_c, "// intentionally empty -- see openssl_stub_lib in build.rs\n")
        .expect("write stub source");

    let mut build = cc::Build::new();
    build.warnings(false);
    if let Some(c) = compilers {
        build.compiler(&c.cc);
    }
    build.file(&stub_c).compile(&format!("tachyon_openssl_stub_{name}"));
    out_dir.join(format!("libtachyon_openssl_stub_{name}.a"))
}

#[allow(clippy::too_many_arguments)]
fn build_i2pd(
    i2pd_dir: &Path,
    boost_install: &Path,
    openssl_include: &Path,
    openssl_crypto_stub: &Path,
    openssl_ssl_stub: &Path,
    zlib_dir: &Path,
    zlib_lib: &Path,
    compilers: Option<&CrossCompilers>,
) -> PathBuf {
    let mut cfg = cmake::Config::new(i2pd_dir.join("build"));
    cfg.define("WITH_LIBRARY", "ON")
        .define("WITH_BINARY", "OFF")
        .define("WITH_UPNP", "OFF")
        // Real under GCC (see vendor/i2pd-src/build/CMakeLists.txt), a no-op under Clang -- kept
        // on anyway since it's free when it does apply; HARDENING_CFLAGS below is what actually
        // guarantees coverage on both.
        .define("WITH_HARDENING", "ON")
        .define("BUILD_TESTING", "OFF")
        .define("CMAKE_BUILD_TYPE", "Release")
        .define("Boost_NO_SYSTEM_PATHS", "ON")
        .define("Boost_USE_STATIC_LIBS", "ON")
        .define("Boost_USE_STATIC_RUNTIME", "ON")
        .define("BOOST_ROOT", boost_install)
        .define("OPENSSL_INCLUDE_DIR", openssl_include)
        .define("OPENSSL_CRYPTO_LIBRARY", openssl_crypto_stub)
        .define("OPENSSL_SSL_LIBRARY", openssl_ssl_stub)
        .define("OPENSSL_VERSION", "1.1.1")
        .define("ZLIB_INCLUDE_DIR", zlib_dir)
        .define("ZLIB_LIBRARY", zlib_lib)
        .build_target("install");
    for flag in HARDENING_CFLAGS {
        cfg.cflag(flag).cxxflag(flag);
    }
    apply_cross(&mut cfg, compilers);
    cfg.build()
}

fn apply_cross(cfg: &mut cmake::Config, compilers: Option<&CrossCompilers>) {
    let Some(c) = compilers else { return };
    cfg.define("CMAKE_C_COMPILER", &c.cc)
        .define("CMAKE_CXX_COMPILER", &c.cxx)
        .define("CMAKE_EXE_LINKER_FLAGS", "-static");
    if let Some(ar) = &c.ar {
        cfg.define("CMAKE_AR", ar);
    }
}