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 src/vendor
13 use std::collections::{BTreeSet, HashSet, HashMap};
17 use std::process::Command;
21 static LICENSES: &'static [&'static str] = &[
32 /// These are exceptions to Rust's permissive licensing policy, and
33 /// should be considered bugs. Exceptions are only allowed in Rust
34 /// tooling. It is _crucial_ that no exception crates be dependencies
35 /// of the Rust runtime (std / test).
36 static EXCEPTIONS: &'static [&'static str] = &[
37 "mdbook", // MPL2, mdbook
38 "openssl", // BSD+advertising clause, cargo, mdbook
39 "pest", // MPL2, mdbook via handlebars
40 "thread-id", // Apache-2.0, mdbook
41 "toml-query", // MPL-2.0, mdbook
42 "is-match", // MPL-2.0, mdbook
43 "cssparser", // MPL-2.0, rustdoc
44 "smallvec", // MPL-2.0, rustdoc
45 "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
46 "fuchsia-zircon", // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
47 "cssparser-macros", // MPL-2.0, rustdoc
48 "selectors", // MPL-2.0, rustdoc
49 "clippy_lints", // MPL-2.0, rls
50 "colored", // MPL-2.0, rustfmt
51 "ordslice", // Apache-2.0, rls
52 "cloudabi", // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
55 /// Which crates to check against the whitelist?
56 static WHITELIST_CRATES: &'static [CrateVersion] = &[
57 CrateVersion("rustc", "0.0.0"),
58 CrateVersion("rustc_codegen_llvm", "0.0.0"),
61 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
62 static WHITELIST: &'static [Crate] = &[
63 Crate("aho-corasick"),
67 Crate("backtrace-sys"),
71 Crate("chalk-engine"),
72 Crate("chalk-macros"),
75 Crate("crossbeam-deque"),
76 Crate("crossbeam-epoch"),
77 Crate("crossbeam-utils"),
84 Crate("fuchsia-zircon"),
85 Crate("fuchsia-zircon-sys"),
89 Crate("kernel32-sys"),
93 Crate("log_settings"),
100 Crate("parking_lot"),
101 Crate("parking_lot_core"),
102 Crate("polonius-engine"),
104 Crate("quick-error"),
106 Crate("redox_syscall"),
107 Crate("redox_termios"),
109 Crate("regex-syntax"),
110 Crate("remove_dir_all"),
111 Crate("rustc-demangle"),
113 Crate("rustc-rayon"),
114 Crate("rustc-rayon-core"),
118 Crate("stable_deref_trait"),
123 Crate("thread_local"),
125 Crate("unicode-width"),
126 Crate("unreachable"),
127 Crate("utf8-ranges"),
130 Crate("winapi-build"),
131 Crate("winapi-i686-pc-windows-gnu"),
132 Crate("winapi-x86_64-pc-windows-gnu"),
136 // Some types for Serde to deserialize the output of `cargo metadata` to...
138 #[derive(Deserialize)]
143 #[derive(Deserialize)]
145 nodes: Vec<ResolveNode>,
148 #[derive(Deserialize)]
151 dependencies: Vec<String>,
154 /// A unique identifier for a crate
155 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
156 struct Crate<'a>(&'a str); // (name,)
158 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
159 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
162 pub fn id_str(&self) -> String {
163 format!("{} ", self.0)
167 impl<'a> CrateVersion<'a> {
168 /// Returns the struct and whether or not the dep is in-tree
169 pub fn from_str(s: &'a str) -> (Self, bool) {
170 let mut parts = s.split(' ');
171 let name = parts.next().unwrap();
172 let version = parts.next().unwrap();
173 let path = parts.next().unwrap();
175 let is_path_dep = path.starts_with("(path+");
177 (CrateVersion(name, version), is_path_dep)
180 pub fn id_str(&self) -> String {
181 format!("{} {}", self.0, self.1)
185 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
186 fn from(cv: CrateVersion<'a>) -> Crate<'a> {
191 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
193 /// Specifically, this checks that the license is correct.
194 pub fn check(path: &Path, bad: &mut bool) {
196 let path = path.join("vendor");
197 assert!(path.exists(), "vendor directory missing");
198 let mut saw_dir = false;
199 for dir in t!(path.read_dir()) {
203 // skip our exceptions
204 if EXCEPTIONS.iter().any(|exception| {
208 .contains(&format!("src/vendor/{}", exception))
213 let toml = dir.path().join("Cargo.toml");
214 *bad = *bad || !check_license(&toml);
216 assert!(saw_dir, "no vendored source");
219 /// Checks the dependency of WHITELIST_CRATES at the given path. Changes `bad` to `true` if a check
222 /// Specifically, this checks that the dependencies are on the WHITELIST.
223 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
224 // Get dependencies from cargo metadata
225 let resolve = get_deps(path, cargo);
227 // Get the whitelist into a convenient form
228 let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
230 // Check dependencies
231 let mut visited = BTreeSet::new();
232 let mut unapproved = BTreeSet::new();
233 for &krate in WHITELIST_CRATES.iter() {
234 let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
235 unapproved.append(&mut bad);
238 if unapproved.len() > 0 {
239 println!("Dependencies not on the whitelist:");
240 for dep in unapproved {
241 println!("* {}", dep.id_str());
246 check_crate_duplicate(&resolve, bad);
249 fn check_license(path: &Path) -> bool {
251 panic!("{} does not exist", path.display());
253 let mut contents = String::new();
254 t!(t!(File::open(path)).read_to_string(&mut contents));
256 let mut found_license = false;
257 for line in contents.lines() {
258 if !line.starts_with("license") {
261 let license = extract_license(line);
262 if !LICENSES.contains(&&*license) {
263 println!("invalid license {} in {}", license, path.display());
266 found_license = true;
270 println!("no license in {}", path.display());
277 fn extract_license(line: &str) -> String {
278 let first_quote = line.find('"');
279 let last_quote = line.rfind('"');
280 if let (Some(f), Some(l)) = (first_quote, last_quote) {
281 let license = &line[f + 1..l];
284 "bad-license-parse".into()
288 /// Get the dependencies of the crate at the given path using `cargo metadata`.
289 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
290 // Run `cargo metadata` to get the set of dependencies
291 let output = Command::new(cargo)
293 .arg("--format-version")
295 .arg("--manifest-path")
296 .arg(path.join("Cargo.toml"))
298 .expect("Unable to run `cargo metadata`")
300 let output = String::from_utf8_lossy(&output);
301 let output: Output = serde_json::from_str(&output).unwrap();
306 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
307 /// the whitelist. Returns a list of illegal dependencies.
308 fn check_crate_whitelist<'a, 'b>(
309 whitelist: &'a HashSet<Crate>,
310 resolve: &'a Resolve,
311 visited: &'b mut BTreeSet<CrateVersion<'a>>,
312 krate: CrateVersion<'a>,
313 must_be_on_whitelist: bool,
314 ) -> BTreeSet<Crate<'a>> {
315 // Will contain bad deps
316 let mut unapproved = BTreeSet::new();
318 // Check if we have already visited this crate
319 if visited.contains(&krate) {
323 visited.insert(krate);
325 // If this path is in-tree, we don't require it to be on the whitelist
326 if must_be_on_whitelist {
327 // If this dependency is not on the WHITELIST, add to bad set
328 if !whitelist.contains(&krate.into()) {
329 unapproved.insert(krate.into());
333 // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!)
334 let to_check = resolve
337 .find(|n| n.id.starts_with(&krate.id_str()))
338 .expect("crate does not exist");
340 for dep in to_check.dependencies.iter() {
341 let (krate, is_path_dep) = CrateVersion::from_str(dep);
343 let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
344 unapproved.append(&mut bad);
350 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
351 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
352 // These two crates take quite a long time to build, let's not let two
353 // versions of them accidentally sneak into our dependency graph to
354 // ensure we keep our CI times under control
355 // "cargo", // FIXME(#53005)
356 // "rustc-ap-syntax", // FIXME(#53006)
358 let mut name_to_id = HashMap::new();
359 for node in resolve.nodes.iter() {
360 name_to_id.entry(node.id.split_whitespace().next().unwrap())
361 .or_insert(Vec::new())
365 for name in FORBIDDEN_TO_HAVE_DUPLICATES {
366 if name_to_id[name].len() <= 1 {
369 println!("crate `{}` is duplicated in `Cargo.lock`", name);
370 for id in name_to_id[name].iter() {
371 println!(" * {}", id);