1 //! Checks the licenses of third-party dependencies by inspecting vendors.
3 use std::collections::{BTreeSet, HashSet, HashMap};
6 use std::process::Command;
10 const LICENSES: &[&str] = &[
21 /// These are exceptions to Rust's permissive licensing policy, and
22 /// should be considered bugs. Exceptions are only allowed in Rust
23 /// tooling. It is _crucial_ that no exception crates be dependencies
24 /// of the Rust runtime (std/test).
25 const EXCEPTIONS: &[&str] = &[
26 "mdbook", // MPL2, mdbook
27 "openssl", // BSD+advertising clause, cargo, mdbook
28 "pest", // MPL2, mdbook via handlebars
29 "arrayref", // BSD-2-Clause, mdbook via handlebars via pest
30 "thread-id", // Apache-2.0, mdbook
31 "toml-query", // MPL-2.0, mdbook
32 "is-match", // MPL-2.0, mdbook
33 "cssparser", // MPL-2.0, rustdoc
34 "smallvec", // MPL-2.0, rustdoc
35 "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
36 "fuchsia-zircon", // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
37 "cssparser-macros", // MPL-2.0, rustdoc
38 "selectors", // MPL-2.0, rustdoc
39 "clippy_lints", // MPL-2.0, rls
40 "colored", // MPL-2.0, rustfmt
41 "ordslice", // Apache-2.0, rls
42 "cloudabi", // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
43 "ryu", // Apache-2.0, rls/cargo/... (because of serde)
44 "bytesize", // Apache-2.0, cargo
45 "im-rc", // MPL-2.0+, cargo
46 "adler32", // BSD-3-Clause AND Zlib, cargo dep that isn't used
47 "fortanix-sgx-abi", // MPL-2.0+, libstd but only for `sgx` target
48 "constant_time_eq", // CC0-1.0, rustfmt
51 /// Which crates to check against the whitelist?
52 const WHITELIST_CRATES: &[CrateVersion<'_>] = &[
53 CrateVersion("rustc", "0.0.0"),
54 CrateVersion("rustc_codegen_llvm", "0.0.0"),
57 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
58 const WHITELIST: &[Crate<'_>] = &[
60 Crate("aho-corasick"),
64 Crate("backtrace-sys"),
70 Crate("chalk-engine"),
71 Crate("chalk-macros"),
74 Crate("compiler_builtins"),
77 Crate("crossbeam-deque"),
78 Crate("crossbeam-epoch"),
79 Crate("crossbeam-utils"),
86 Crate("fuchsia-zircon"),
87 Crate("fuchsia-zircon-sys"),
92 Crate("kernel32-sys"),
98 Crate("log_settings"),
103 Crate("miniz_oxide"),
104 Crate("miniz_oxide_c_api"),
108 Crate("parking_lot"),
109 Crate("parking_lot_core"),
111 Crate("polonius-engine"),
112 Crate("proc-macro2"),
113 Crate("quick-error"),
116 Crate("rand_chacha"),
121 Crate("rand_xorshift"),
122 Crate("redox_syscall"),
123 Crate("redox_termios"),
125 Crate("regex-syntax"),
126 Crate("remove_dir_all"),
127 Crate("rustc-demangle"),
129 Crate("rustc-rayon"),
130 Crate("rustc-rayon-core"),
131 Crate("rustc_version"),
135 Crate("semver-parser"),
137 Crate("serde_derive"),
139 Crate("stable_deref_trait"),
141 Crate("synstructure"),
146 Crate("thread_local"),
148 Crate("unicode-width"),
149 Crate("unicode-xid"),
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 dependency 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
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 in 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 /// Gets 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>(
336 whitelist: &'a HashSet<Crate<'_>>,
337 resolve: &'a Resolve,
338 visited: &mut BTreeSet<CrateVersion<'a>>,
339 krate: CrateVersion<'a>,
340 must_be_on_whitelist: bool,
341 ) -> BTreeSet<Crate<'a>> {
342 // This 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 `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, so don't allow two versions of them
380 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
386 let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
387 for node in resolve.nodes.iter() {
388 name_to_id.entry(node.id.split_whitespace().next().unwrap())
393 for name in FORBIDDEN_TO_HAVE_DUPLICATES {
394 if name_to_id[name].len() <= 1 {
397 println!("crate `{}` is duplicated in `Cargo.lock`", name);
398 for id in name_to_id[name].iter() {
399 println!(" * {}", id);