]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
8626ba060bf713f66ddc37332d9774db9681340b
[rust.git] / src / tools / tidy / src / deps.rs
1 //! Checks the licenses of third-party dependencies by inspecting vendors.
2
3 use std::collections::{BTreeSet, HashSet, HashMap};
4 use std::fs;
5 use std::path::Path;
6 use std::process::Command;
7
8 use serde::Deserialize;
9 use serde_json;
10
11 const LICENSES: &[&str] = &[
12     "MIT/Apache-2.0",
13     "MIT / Apache-2.0",
14     "Apache-2.0/MIT",
15     "Apache-2.0 / MIT",
16     "MIT OR Apache-2.0",
17     "MIT",
18     "Unlicense/MIT",
19     "Unlicense OR MIT",
20 ];
21
22 /// These are exceptions to Rust's permissive licensing policy, and
23 /// should be considered bugs. Exceptions are only allowed in Rust
24 /// tooling. It is _crucial_ that no exception crates be dependencies
25 /// of the Rust runtime (std/test).
26 const EXCEPTIONS: &[&str] = &[
27     "mdbook",             // MPL2, mdbook
28     "openssl",            // BSD+advertising clause, cargo, mdbook
29     "pest",               // MPL2, mdbook via handlebars
30     "arrayref",           // BSD-2-Clause, mdbook via handlebars via pest
31     "thread-id",          // Apache-2.0, mdbook
32     "toml-query",         // MPL-2.0, mdbook
33     "is-match",           // MPL-2.0, mdbook
34     "cssparser",          // MPL-2.0, rustdoc
35     "smallvec",           // MPL-2.0, rustdoc
36     "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
37     "fuchsia-zircon",     // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
38     "cssparser-macros",   // MPL-2.0, rustdoc
39     "selectors",          // MPL-2.0, rustdoc
40     "clippy_lints",       // MPL-2.0, rls
41     "colored",            // MPL-2.0, rustfmt
42     "ordslice",           // Apache-2.0, rls
43     "cloudabi",           // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
44     "ryu",                // Apache-2.0, rls/cargo/... (because of serde)
45     "bytesize",           // Apache-2.0, cargo
46     "im-rc",              // MPL-2.0+, cargo
47     "adler32",            // BSD-3-Clause AND Zlib, cargo dep that isn't used
48     "fortanix-sgx-abi",   // MPL-2.0+, libstd but only for `sgx` target
49     "constant_time_eq",   // CC0-1.0, rustfmt
50 ];
51
52 /// Which crates to check against the whitelist?
53 const WHITELIST_CRATES: &[CrateVersion<'_>] = &[
54     CrateVersion("rustc", "0.0.0"),
55     CrateVersion("rustc_codegen_llvm", "0.0.0"),
56 ];
57
58 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
59 const WHITELIST: &[Crate<'_>] = &[
60     Crate("adler32"),
61     Crate("aho-corasick"),
62     Crate("arrayvec"),
63     Crate("atty"),
64     Crate("backtrace"),
65     Crate("backtrace-sys"),
66     Crate("bitflags"),
67     Crate("build_const"),
68     Crate("byteorder"),
69     Crate("cc"),
70     Crate("cfg-if"),
71     Crate("chalk-engine"),
72     Crate("chalk-macros"),
73     Crate("cloudabi"),
74     Crate("cmake"),
75     Crate("compiler_builtins"),
76     Crate("crc"),
77     Crate("crc32fast"),
78     Crate("crossbeam-deque"),
79     Crate("crossbeam-epoch"),
80     Crate("crossbeam-utils"),
81     Crate("datafrog"),
82     Crate("either"),
83     Crate("ena"),
84     Crate("env_logger"),
85     Crate("filetime"),
86     Crate("flate2"),
87     Crate("fuchsia-zircon"),
88     Crate("fuchsia-zircon-sys"),
89     Crate("getopts"),
90     Crate("humantime"),
91     Crate("itertools"),
92     Crate("jobserver"),
93     Crate("kernel32-sys"),
94     Crate("lazy_static"),
95     Crate("libc"),
96     Crate("libz-sys"),
97     Crate("lock_api"),
98     Crate("log"),
99     Crate("log_settings"),
100     Crate("measureme"),
101     Crate("memchr"),
102     Crate("memmap"),
103     Crate("memoffset"),
104     Crate("miniz-sys"),
105     Crate("miniz_oxide"),
106     Crate("miniz_oxide_c_api"),
107     Crate("nodrop"),
108     Crate("num_cpus"),
109     Crate("owning_ref"),
110     Crate("parking_lot"),
111     Crate("parking_lot_core"),
112     Crate("pkg-config"),
113     Crate("polonius-engine"),
114     Crate("proc-macro2"),
115     Crate("quick-error"),
116     Crate("quote"),
117     Crate("rand"),
118     Crate("rand_chacha"),
119     Crate("rand_core"),
120     Crate("rand_hc"),
121     Crate("rand_isaac"),
122     Crate("rand_pcg"),
123     Crate("rand_xorshift"),
124     Crate("redox_syscall"),
125     Crate("redox_termios"),
126     Crate("regex"),
127     Crate("regex-syntax"),
128     Crate("remove_dir_all"),
129     Crate("rustc-demangle"),
130     Crate("rustc-hash"),
131     Crate("rustc-rayon"),
132     Crate("rustc-rayon-core"),
133     Crate("rustc_version"),
134     Crate("scoped-tls"),
135     Crate("scopeguard"),
136     Crate("semver"),
137     Crate("semver-parser"),
138     Crate("serde"),
139     Crate("serde_derive"),
140     Crate("smallvec"),
141     Crate("stable_deref_trait"),
142     Crate("syn"),
143     Crate("synstructure"),
144     Crate("tempfile"),
145     Crate("termcolor"),
146     Crate("terminon"),
147     Crate("termion"),
148     Crate("thread_local"),
149     Crate("ucd-util"),
150     Crate("unicode-width"),
151     Crate("unicode-xid"),
152     Crate("unreachable"),
153     Crate("utf8-ranges"),
154     Crate("vcpkg"),
155     Crate("version_check"),
156     Crate("void"),
157     Crate("winapi"),
158     Crate("winapi-build"),
159     Crate("winapi-i686-pc-windows-gnu"),
160     Crate("winapi-util"),
161     Crate("winapi-x86_64-pc-windows-gnu"),
162     Crate("wincolor"),
163 ];
164
165 // Some types for Serde to deserialize the output of `cargo metadata` to.
166
167 #[derive(Deserialize)]
168 struct Output {
169     resolve: Resolve,
170 }
171
172 #[derive(Deserialize)]
173 struct Resolve {
174     nodes: Vec<ResolveNode>,
175 }
176
177 #[derive(Deserialize)]
178 struct ResolveNode {
179     id: String,
180     dependencies: Vec<String>,
181 }
182
183 /// A unique identifier for a crate.
184 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
185 struct Crate<'a>(&'a str); // (name)
186
187 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
188 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
189
190 impl Crate<'_> {
191     pub fn id_str(&self) -> String {
192         format!("{} ", self.0)
193     }
194 }
195
196 impl<'a> CrateVersion<'a> {
197     /// Returns the struct and whether or not the dependency is in-tree.
198     pub fn from_str(s: &'a str) -> (Self, bool) {
199         let mut parts = s.split(' ');
200         let name = parts.next().unwrap();
201         let version = parts.next().unwrap();
202         let path = parts.next().unwrap();
203
204         let is_path_dep = path.starts_with("(path+");
205
206         (CrateVersion(name, version), is_path_dep)
207     }
208
209     pub fn id_str(&self) -> String {
210         format!("{} {}", self.0, self.1)
211     }
212 }
213
214 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
215     fn from(cv: CrateVersion<'a>) -> Crate<'a> {
216         Crate(cv.0)
217     }
218 }
219
220 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
221 ///
222 /// Specifically, this checks that the license is correct.
223 pub fn check(path: &Path, bad: &mut bool) {
224     // Check licences.
225     let path = path.join("../vendor");
226     assert!(path.exists(), "vendor directory missing");
227     let mut saw_dir = false;
228     for dir in t!(path.read_dir()) {
229         saw_dir = true;
230         let dir = t!(dir);
231
232         // Skip our exceptions.
233         let is_exception = EXCEPTIONS.iter().any(|exception| {
234             dir.path()
235                 .to_str()
236                 .unwrap()
237                 .contains(&format!("vendor/{}", exception))
238         });
239         if is_exception {
240             continue;
241         }
242
243         let toml = dir.path().join("Cargo.toml");
244         *bad = *bad || !check_license(&toml);
245     }
246     assert!(saw_dir, "no vendored source");
247 }
248
249 /// Checks the dependency of `WHITELIST_CRATES` at the given path. Changes `bad` to `true` if a
250 /// check failed.
251 ///
252 /// Specifically, this checks that the dependencies are on the `WHITELIST`.
253 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
254     // Get dependencies from Cargo metadata.
255     let resolve = get_deps(path, cargo);
256
257     // Get the whitelist in a convenient form.
258     let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
259
260     // Check dependencies.
261     let mut visited = BTreeSet::new();
262     let mut unapproved = BTreeSet::new();
263     for &krate in WHITELIST_CRATES.iter() {
264         let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
265         unapproved.append(&mut bad);
266     }
267
268     if !unapproved.is_empty() {
269         println!("Dependencies not on the whitelist:");
270         for dep in unapproved {
271             println!("* {}", dep.id_str());
272         }
273         *bad = true;
274     }
275
276     check_crate_duplicate(&resolve, bad);
277 }
278
279 fn check_license(path: &Path) -> bool {
280     if !path.exists() {
281         panic!("{} does not exist", path.display());
282     }
283     let contents = t!(fs::read_to_string(&path));
284
285     let mut found_license = false;
286     for line in contents.lines() {
287         if !line.starts_with("license") {
288             continue;
289         }
290         let license = extract_license(line);
291         if !LICENSES.contains(&&*license) {
292             println!("invalid license {} in {}", license, path.display());
293             return false;
294         }
295         found_license = true;
296         break;
297     }
298     if !found_license {
299         println!("no license in {}", path.display());
300         return false;
301     }
302
303     true
304 }
305
306 fn extract_license(line: &str) -> String {
307     let first_quote = line.find('"');
308     let last_quote = line.rfind('"');
309     if let (Some(f), Some(l)) = (first_quote, last_quote) {
310         let license = &line[f + 1..l];
311         license.into()
312     } else {
313         "bad-license-parse".into()
314     }
315 }
316
317 /// Gets the dependencies of the crate at the given path using `cargo metadata`.
318 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
319     // Run `cargo metadata` to get the set of dependencies.
320     let output = Command::new(cargo)
321         .arg("metadata")
322         .arg("--format-version")
323         .arg("1")
324         .arg("--manifest-path")
325         .arg(path.join("../Cargo.toml"))
326         .output()
327         .expect("Unable to run `cargo metadata`")
328         .stdout;
329     let output = String::from_utf8_lossy(&output);
330     let output: Output = serde_json::from_str(&output).unwrap();
331
332     output.resolve
333 }
334
335 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
336 /// the whitelist. Returns a list of illegal dependencies.
337 fn check_crate_whitelist<'a>(
338     whitelist: &'a HashSet<Crate<'_>>,
339     resolve: &'a Resolve,
340     visited: &mut BTreeSet<CrateVersion<'a>>,
341     krate: CrateVersion<'a>,
342     must_be_on_whitelist: bool,
343 ) -> BTreeSet<Crate<'a>> {
344     // This will contain bad deps.
345     let mut unapproved = BTreeSet::new();
346
347     // Check if we have already visited this crate.
348     if visited.contains(&krate) {
349         return unapproved;
350     }
351
352     visited.insert(krate);
353
354     // If this path is in-tree, we don't require it to be on the whitelist.
355     if must_be_on_whitelist {
356         // If this dependency is not on `WHITELIST`, add to bad set.
357         if !whitelist.contains(&krate.into()) {
358             unapproved.insert(krate.into());
359         }
360     }
361
362     // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!).
363     let to_check = resolve
364         .nodes
365         .iter()
366         .find(|n| n.id.starts_with(&krate.id_str()))
367         .expect("crate does not exist");
368
369     for dep in to_check.dependencies.iter() {
370         let (krate, is_path_dep) = CrateVersion::from_str(dep);
371
372         let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
373         unapproved.append(&mut bad);
374     }
375
376     unapproved
377 }
378
379 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
380     const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
381         // These two crates take quite a long time to build, so don't allow two versions of them
382         // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
383         // under control.
384
385         "cargo",
386         "rustc-ap-syntax",
387     ];
388     let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
389     for node in resolve.nodes.iter() {
390         name_to_id.entry(node.id.split_whitespace().next().unwrap())
391             .or_default()
392             .push(&node.id);
393     }
394
395     for name in FORBIDDEN_TO_HAVE_DUPLICATES {
396         if name_to_id[name].len() <= 1 {
397             continue
398         }
399         println!("crate `{}` is duplicated in `Cargo.lock`", name);
400         for id in name_to_id[name].iter() {
401             println!("  * {}", id);
402         }
403         *bad = true;
404     }
405 }