1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Check license of third-party deps by inspecting vendor
13 use std::collections::{BTreeSet, HashSet, HashMap};
16 use std::process::Command;
20 const LICENSES: &[&str] = &[
31 /// These are exceptions to Rust's permissive licensing policy, and
32 /// should be considered bugs. Exceptions are only allowed in Rust
33 /// tooling. It is _crucial_ that no exception crates be dependencies
34 /// of the Rust runtime (std / test).
35 const EXCEPTIONS: &[&str] = &[
36 "mdbook", // MPL2, mdbook
37 "openssl", // BSD+advertising clause, cargo, mdbook
38 "pest", // MPL2, mdbook via handlebars
39 "thread-id", // Apache-2.0, mdbook
40 "toml-query", // MPL-2.0, mdbook
41 "is-match", // MPL-2.0, mdbook
42 "cssparser", // MPL-2.0, rustdoc
43 "smallvec", // MPL-2.0, rustdoc
44 "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
45 "fuchsia-zircon", // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
46 "cssparser-macros", // MPL-2.0, rustdoc
47 "selectors", // MPL-2.0, rustdoc
48 "clippy_lints", // MPL-2.0, rls
49 "colored", // MPL-2.0, rustfmt
50 "ordslice", // Apache-2.0, rls
51 "cloudabi", // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
52 "ryu", // Apache-2.0, rls/cargo/... (b/c of serde)
53 "bytesize", // Apache-2.0, cargo
54 "im-rc", // MPL-2.0+, cargo
55 "adler32", // BSD-3-Clause AND Zlib, cargo dep that isn't used
56 "fortanix-sgx-abi", // MPL-2.0+, libstd but only for sgx target
59 /// Which crates to check against the whitelist?
60 const WHITELIST_CRATES: &[CrateVersion] = &[
61 CrateVersion("rustc", "0.0.0"),
62 CrateVersion("rustc_codegen_llvm", "0.0.0"),
65 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
66 const WHITELIST: &[Crate] = &[
68 Crate("aho-corasick"),
72 Crate("backtrace-sys"),
78 Crate("chalk-engine"),
79 Crate("chalk-macros"),
84 Crate("crossbeam-deque"),
85 Crate("crossbeam-epoch"),
86 Crate("crossbeam-utils"),
93 Crate("fuchsia-zircon"),
94 Crate("fuchsia-zircon-sys"),
98 Crate("kernel32-sys"),
104 Crate("log_settings"),
109 Crate("miniz_oxide"),
110 Crate("miniz_oxide_c_api"),
114 Crate("parking_lot"),
115 Crate("parking_lot_core"),
117 Crate("polonius-engine"),
118 Crate("quick-error"),
120 Crate("rand_chacha"),
125 Crate("rand_xorshift"),
126 Crate("redox_syscall"),
127 Crate("redox_termios"),
129 Crate("regex-syntax"),
130 Crate("remove_dir_all"),
131 Crate("rustc-demangle"),
133 Crate("rustc-rayon"),
134 Crate("rustc-rayon-core"),
135 Crate("rustc_version"),
139 Crate("semver-parser"),
142 Crate("stable_deref_trait"),
147 Crate("thread_local"),
149 Crate("unicode-width"),
150 Crate("unreachable"),
151 Crate("utf8-ranges"),
153 Crate("version_check"),
156 Crate("winapi-build"),
157 Crate("winapi-i686-pc-windows-gnu"),
158 Crate("winapi-util"),
159 Crate("winapi-x86_64-pc-windows-gnu"),
163 // Some types for Serde to deserialize the output of `cargo metadata` to...
165 #[derive(Deserialize)]
170 #[derive(Deserialize)]
172 nodes: Vec<ResolveNode>,
175 #[derive(Deserialize)]
178 dependencies: Vec<String>,
181 /// A unique identifier for a crate
182 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
183 struct Crate<'a>(&'a str); // (name,)
185 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
186 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
189 pub fn id_str(&self) -> String {
190 format!("{} ", self.0)
194 impl<'a> CrateVersion<'a> {
195 /// Returns the struct and whether or not the dep is in-tree
196 pub fn from_str(s: &'a str) -> (Self, bool) {
197 let mut parts = s.split(' ');
198 let name = parts.next().unwrap();
199 let version = parts.next().unwrap();
200 let path = parts.next().unwrap();
202 let is_path_dep = path.starts_with("(path+");
204 (CrateVersion(name, version), is_path_dep)
207 pub fn id_str(&self) -> String {
208 format!("{} {}", self.0, self.1)
212 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
213 fn from(cv: CrateVersion<'a>) -> Crate<'a> {
218 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
220 /// Specifically, this checks that the license is correct.
221 pub fn check(path: &Path, bad: &mut bool) {
223 let path = path.join("../vendor");
224 assert!(path.exists(), "vendor directory missing");
225 let mut saw_dir = false;
226 for dir in t!(path.read_dir()) {
230 // skip our exceptions
231 let is_exception = EXCEPTIONS.iter().any(|exception| {
235 .contains(&format!("vendor/{}", exception))
241 let toml = dir.path().join("Cargo.toml");
242 *bad = *bad || !check_license(&toml);
244 assert!(saw_dir, "no vendored source");
247 /// Checks the dependency of WHITELIST_CRATES at the given path. Changes `bad` to `true` if a check
250 /// Specifically, this checks that the dependencies are on the WHITELIST.
251 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
252 // Get dependencies from cargo metadata
253 let resolve = get_deps(path, cargo);
255 // Get the whitelist into a convenient form
256 let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
258 // Check dependencies
259 let mut visited = BTreeSet::new();
260 let mut unapproved = BTreeSet::new();
261 for &krate in WHITELIST_CRATES.iter() {
262 let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
263 unapproved.append(&mut bad);
266 if !unapproved.is_empty() {
267 println!("Dependencies not on the whitelist:");
268 for dep in unapproved {
269 println!("* {}", dep.id_str());
274 check_crate_duplicate(&resolve, bad);
277 fn check_license(path: &Path) -> bool {
279 panic!("{} does not exist", path.display());
281 let contents = t!(fs::read_to_string(&path));
283 let mut found_license = false;
284 for line in contents.lines() {
285 if !line.starts_with("license") {
288 let license = extract_license(line);
289 if !LICENSES.contains(&&*license) {
290 println!("invalid license {} in {}", license, path.display());
293 found_license = true;
297 println!("no license in {}", path.display());
304 fn extract_license(line: &str) -> String {
305 let first_quote = line.find('"');
306 let last_quote = line.rfind('"');
307 if let (Some(f), Some(l)) = (first_quote, last_quote) {
308 let license = &line[f + 1..l];
311 "bad-license-parse".into()
315 /// Get the dependencies of the crate at the given path using `cargo metadata`.
316 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
317 // Run `cargo metadata` to get the set of dependencies
318 let output = Command::new(cargo)
320 .arg("--format-version")
322 .arg("--manifest-path")
323 .arg(path.join("../Cargo.toml"))
325 .expect("Unable to run `cargo metadata`")
327 let output = String::from_utf8_lossy(&output);
328 let output: Output = serde_json::from_str(&output).unwrap();
333 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
334 /// the whitelist. Returns a list of illegal dependencies.
335 fn check_crate_whitelist<'a, 'b>(
336 whitelist: &'a HashSet<Crate>,
337 resolve: &'a Resolve,
338 visited: &'b mut BTreeSet<CrateVersion<'a>>,
339 krate: CrateVersion<'a>,
340 must_be_on_whitelist: bool,
341 ) -> BTreeSet<Crate<'a>> {
342 // Will contain bad deps
343 let mut unapproved = BTreeSet::new();
345 // Check if we have already visited this crate
346 if visited.contains(&krate) {
350 visited.insert(krate);
352 // If this path is in-tree, we don't require it to be on the whitelist
353 if must_be_on_whitelist {
354 // If this dependency is not on the WHITELIST, add to bad set
355 if !whitelist.contains(&krate.into()) {
356 unapproved.insert(krate.into());
360 // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!)
361 let to_check = resolve
364 .find(|n| n.id.starts_with(&krate.id_str()))
365 .expect("crate does not exist");
367 for dep in to_check.dependencies.iter() {
368 let (krate, is_path_dep) = CrateVersion::from_str(dep);
370 let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
371 unapproved.append(&mut bad);
377 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
378 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
379 // These two crates take quite a long time to build, let's not let two
380 // versions of them accidentally sneak into our dependency graph to
381 // ensure we keep our CI times under control
382 // "cargo", // FIXME(#53005)
385 let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
386 for node in resolve.nodes.iter() {
387 name_to_id.entry(node.id.split_whitespace().next().unwrap())
392 for name in FORBIDDEN_TO_HAVE_DUPLICATES {
393 if name_to_id[name].len() <= 1 {
396 println!("crate `{}` is duplicated in `Cargo.lock`", name);
397 for id in name_to_id[name].iter() {
398 println!(" * {}", id);