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};
17 use std::process::Command;
21 static LICENSES: &'static [&'static 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 static EXCEPTIONS: &'static [&'static 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
52 /// Which crates to check against the whitelist?
53 static WHITELIST_CRATES: &'static [CrateVersion] = &[
54 CrateVersion("rustc", "0.0.0"),
55 CrateVersion("rustc_trans", "0.0.0"),
58 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
59 static WHITELIST: &'static [Crate] = &[
60 Crate("aho-corasick"),
64 Crate("backtrace-sys"),
74 Crate("fuchsia-zircon"),
75 Crate("fuchsia-zircon-sys"),
78 Crate("kernel32-sys"),
82 Crate("log_settings"),
88 Crate("parking_lot_core"),
91 Crate("redox_syscall"),
92 Crate("redox_termios"),
94 Crate("regex-syntax"),
95 Crate("remove_dir_all"),
96 Crate("rustc-demangle"),
99 Crate("stable_deref_trait"),
104 Crate("thread_local"),
106 Crate("unicode-width"),
107 Crate("unreachable"),
108 Crate("utf8-ranges"),
111 Crate("winapi-build"),
112 Crate("winapi-i686-pc-windows-gnu"),
113 Crate("winapi-x86_64-pc-windows-gnu"),
117 // Some types for Serde to deserialize the output of `cargo metadata` to...
119 #[derive(Deserialize)]
124 #[derive(Deserialize)]
126 nodes: Vec<ResolveNode>,
129 #[derive(Deserialize)]
132 dependencies: Vec<String>,
135 /// A unique identifier for a crate
136 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
137 struct Crate<'a>(&'a str); // (name,)
139 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
140 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
143 pub fn id_str(&self) -> String {
144 format!("{} ", self.0)
148 impl<'a> CrateVersion<'a> {
149 /// Returns the struct and whether or not the dep is in-tree
150 pub fn from_str(s: &'a str) -> (Self, bool) {
151 let mut parts = s.split(" ");
152 let name = parts.next().unwrap();
153 let version = parts.next().unwrap();
154 let path = parts.next().unwrap();
156 let is_path_dep = path.starts_with("(path+");
158 (CrateVersion(name, version), is_path_dep)
161 pub fn id_str(&self) -> String {
162 format!("{} {}", self.0, self.1)
166 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
167 fn from(cv: CrateVersion<'a>) -> Crate<'a> {
172 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
174 /// Specifically, this checks that the license is correct.
175 pub fn check(path: &Path, bad: &mut bool) {
177 let path = path.join("vendor");
178 assert!(path.exists(), "vendor directory missing");
179 let mut saw_dir = false;
180 for dir in t!(path.read_dir()) {
184 // skip our exceptions
185 if EXCEPTIONS.iter().any(|exception| {
189 .contains(&format!("src/vendor/{}", exception))
194 let toml = dir.path().join("Cargo.toml");
195 *bad = *bad || !check_license(&toml);
197 assert!(saw_dir, "no vendored source");
200 /// Checks the dependency of WHITELIST_CRATES at the given path. Changes `bad` to `true` if a check
203 /// Specifically, this checks that the dependencies are on the WHITELIST.
204 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
205 // Get dependencies from cargo metadata
206 let resolve = get_deps(path, cargo);
208 // Get the whitelist into a convenient form
209 let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
211 // Check dependencies
212 let mut visited = BTreeSet::new();
213 let mut unapproved = BTreeSet::new();
214 for &krate in WHITELIST_CRATES.iter() {
215 let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
216 unapproved.append(&mut bad);
219 if unapproved.len() > 0 {
220 println!("Dependencies not on the whitelist:");
221 for dep in unapproved {
222 println!("* {}", dep.id_str());
228 fn check_license(path: &Path) -> bool {
230 panic!("{} does not exist", path.display());
232 let mut contents = String::new();
233 t!(t!(File::open(path)).read_to_string(&mut contents));
235 let mut found_license = false;
236 for line in contents.lines() {
237 if !line.starts_with("license") {
240 let license = extract_license(line);
241 if !LICENSES.contains(&&*license) {
242 println!("invalid license {} in {}", license, path.display());
245 found_license = true;
249 println!("no license in {}", path.display());
256 fn extract_license(line: &str) -> String {
257 let first_quote = line.find('"');
258 let last_quote = line.rfind('"');
259 if let (Some(f), Some(l)) = (first_quote, last_quote) {
260 let license = &line[f + 1..l];
263 "bad-license-parse".into()
267 /// Get the dependencies of the crate at the given path using `cargo metadata`.
268 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
269 // Run `cargo metadata` to get the set of dependencies
270 let output = Command::new(cargo)
272 .arg("--format-version")
274 .arg("--manifest-path")
275 .arg(path.join("Cargo.toml"))
277 .expect("Unable to run `cargo metadata`")
279 let output = String::from_utf8_lossy(&output);
280 let output: Output = serde_json::from_str(&output).unwrap();
285 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
286 /// the whitelist. Returns a list of illegal dependencies.
287 fn check_crate_whitelist<'a, 'b>(
288 whitelist: &'a HashSet<Crate>,
289 resolve: &'a Resolve,
290 visited: &'b mut BTreeSet<CrateVersion<'a>>,
291 krate: CrateVersion<'a>,
292 must_be_on_whitelist: bool,
293 ) -> BTreeSet<Crate<'a>> {
294 // Will contain bad deps
295 let mut unapproved = BTreeSet::new();
297 // Check if we have already visited this crate
298 if visited.contains(&krate) {
302 visited.insert(krate);
304 // If this path is in-tree, we don't require it to be on the whitelist
305 if must_be_on_whitelist {
306 // If this dependency is not on the WHITELIST, add to bad set
307 if !whitelist.contains(&krate.into()) {
308 unapproved.insert(krate.into());
312 // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!)
313 let to_check = resolve
316 .find(|n| n.id.starts_with(&krate.id_str()))
317 .expect("crate does not exist");
319 for dep in to_check.dependencies.iter() {
320 let (krate, is_path_dep) = CrateVersion::from_str(dep);
322 let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
323 unapproved.append(&mut bad);