Skip to main content

cargo/ops/
registry.rs

1use std::collections::BTreeMap;
2use std::fs::{self, File};
3use std::io::{self, BufRead};
4use std::iter::repeat;
5use std::str;
6use std::time::Duration;
7use std::{cmp, env};
8
9use crates_io::{NewCrate, NewCrateDependency, Registry};
10use curl::easy::{Easy, InfoType, SslOpt};
11use log::{log, Level};
12use url::percent_encoding::{percent_encode, QUERY_ENCODE_SET};
13
14use crate::core::dependency::Kind;
15use crate::core::manifest::ManifestMetadata;
16use crate::core::source::Source;
17use crate::core::{Package, SourceId, Workspace};
18use crate::ops;
19use crate::sources::{RegistrySource, SourceConfigMap};
20use crate::util::config::{self, Config};
21use crate::util::errors::{CargoResult, CargoResultExt};
22use crate::util::important_paths::find_root_manifest_for_wd;
23use crate::util::ToUrl;
24use crate::util::{paths, validate_package_name};
25use crate::version;
26
27pub struct RegistryConfig {
28    pub index: Option<String>,
29    pub token: Option<String>,
30}
31
32pub struct PublishOpts<'cfg> {
33    pub config: &'cfg Config,
34    pub token: Option<String>,
35    pub index: Option<String>,
36    pub verify: bool,
37    pub allow_dirty: bool,
38    pub jobs: Option<u32>,
39    pub target: Option<String>,
40    pub dry_run: bool,
41    pub registry: Option<String>,
42}
43
44pub fn publish(ws: &Workspace<'_>, opts: &PublishOpts<'_>) -> CargoResult<()> {
45    let pkg = ws.current()?;
46
47    if let Some(ref allowed_registries) = *pkg.publish() {
48        if !match opts.registry {
49            Some(ref registry) => allowed_registries.contains(registry),
50            None => false,
51        } {
52            failure::bail!(
53                "some crates cannot be published.\n\
54                 `{}` is marked as unpublishable",
55                pkg.name()
56            );
57        }
58    }
59
60    if !pkg.manifest().patch().is_empty() {
61        failure::bail!("published crates cannot contain [patch] sections");
62    }
63
64    let (mut registry, reg_id) = registry(
65        opts.config,
66        opts.token.clone(),
67        opts.index.clone(),
68        opts.registry.clone(),
69        true,
70    )?;
71    verify_dependencies(pkg, reg_id)?;
72
73    // Prepare a tarball, with a non-surpressable warning if metadata
74    // is missing since this is being put online.
75    let tarball = ops::package(
76        ws,
77        &ops::PackageOpts {
78            config: opts.config,
79            verify: opts.verify,
80            list: false,
81            check_metadata: true,
82            allow_dirty: opts.allow_dirty,
83            target: opts.target.clone(),
84            jobs: opts.jobs,
85        },
86    )?
87    .unwrap();
88
89    // Upload said tarball to the specified destination
90    opts.config
91        .shell()
92        .status("Uploading", pkg.package_id().to_string())?;
93    transmit(
94        opts.config,
95        pkg,
96        tarball.file(),
97        &mut registry,
98        reg_id,
99        opts.dry_run,
100    )?;
101
102    Ok(())
103}
104
105fn verify_dependencies(pkg: &Package, registry_src: SourceId) -> CargoResult<()> {
106    for dep in pkg.dependencies().iter() {
107        if dep.source_id().is_path() {
108            if !dep.specified_req() {
109                failure::bail!(
110                    "all path dependencies must have a version specified \
111                     when publishing.\ndependency `{}` does not specify \
112                     a version",
113                    dep.package_name()
114                )
115            }
116        } else if dep.source_id() != registry_src {
117            if dep.source_id().is_registry() {
118                // Block requests to send to a registry if it is not an alternative
119                // registry
120                if !registry_src.is_alt_registry() {
121                    failure::bail!("crates cannot be published to crates.io with dependencies sourced from other\n\
122                           registries either publish `{}` on crates.io or pull it into this repository\n\
123                           and specify it with a path and version\n\
124                           (crate `{}` is pulled from {})",
125                          dep.package_name(),
126                          dep.package_name(),
127                          dep.source_id());
128                }
129            } else {
130                failure::bail!(
131                    "crates cannot be published to crates.io with dependencies sourced from \
132                     a repository\neither publish `{}` as its own crate on crates.io and \
133                     specify a crates.io version as a dependency or pull it into this \
134                     repository and specify it with a path and version\n(crate `{}` has \
135                     repository path `{}`)",
136                    dep.package_name(),
137                    dep.package_name(),
138                    dep.source_id()
139                );
140            }
141        }
142    }
143    Ok(())
144}
145
146fn transmit(
147    config: &Config,
148    pkg: &Package,
149    tarball: &File,
150    registry: &mut Registry,
151    registry_id: SourceId,
152    dry_run: bool,
153) -> CargoResult<()> {
154    let deps = pkg
155        .dependencies()
156        .iter()
157        .map(|dep| {
158            // If the dependency is from a different registry, then include the
159            // registry in the dependency.
160            let dep_registry_id = match dep.registry_id() {
161                Some(id) => id,
162                None => SourceId::crates_io(config)?,
163            };
164            // In the index and Web API, None means "from the same registry"
165            // whereas in Cargo.toml, it means "from crates.io".
166            let dep_registry = if dep_registry_id != registry_id {
167                Some(dep_registry_id.url().to_string())
168            } else {
169                None
170            };
171
172            Ok(NewCrateDependency {
173                optional: dep.is_optional(),
174                default_features: dep.uses_default_features(),
175                name: dep.package_name().to_string(),
176                features: dep.features().iter().map(|s| s.to_string()).collect(),
177                version_req: dep.version_req().to_string(),
178                target: dep.platform().map(|s| s.to_string()),
179                kind: match dep.kind() {
180                    Kind::Normal => "normal",
181                    Kind::Build => "build",
182                    Kind::Development => "dev",
183                }
184                .to_string(),
185                registry: dep_registry,
186                explicit_name_in_toml: dep.explicit_name_in_toml().map(|s| s.to_string()),
187            })
188        })
189        .collect::<CargoResult<Vec<NewCrateDependency>>>()?;
190    let manifest = pkg.manifest();
191    let ManifestMetadata {
192        ref authors,
193        ref description,
194        ref homepage,
195        ref documentation,
196        ref keywords,
197        ref readme,
198        ref repository,
199        ref license,
200        ref license_file,
201        ref categories,
202        ref badges,
203        ref links,
204    } = *manifest.metadata();
205    let readme_content = match *readme {
206        Some(ref readme) => Some(paths::read(&pkg.root().join(readme))?),
207        None => None,
208    };
209    if let Some(ref file) = *license_file {
210        if fs::metadata(&pkg.root().join(file)).is_err() {
211            failure::bail!("the license file `{}` does not exist", file)
212        }
213    }
214
215    // Do not upload if performing a dry run
216    if dry_run {
217        config.shell().warn("aborting upload due to dry run")?;
218        return Ok(());
219    }
220
221    let summary = pkg.summary();
222    let string_features = summary
223        .features()
224        .iter()
225        .map(|(feat, values)| {
226            (
227                feat.to_string(),
228                values.iter().map(|fv| fv.to_string(&summary)).collect(),
229            )
230        })
231        .collect::<BTreeMap<String, Vec<String>>>();
232
233    let publish = registry.publish(
234        &NewCrate {
235            name: pkg.name().to_string(),
236            vers: pkg.version().to_string(),
237            deps,
238            features: string_features,
239            authors: authors.clone(),
240            description: description.clone(),
241            homepage: homepage.clone(),
242            documentation: documentation.clone(),
243            keywords: keywords.clone(),
244            categories: categories.clone(),
245            readme: readme_content,
246            readme_file: readme.clone(),
247            repository: repository.clone(),
248            license: license.clone(),
249            license_file: license_file.clone(),
250            badges: badges.clone(),
251            links: links.clone(),
252        },
253        tarball,
254    );
255
256    match publish {
257        Ok(warnings) => {
258            if !warnings.invalid_categories.is_empty() {
259                let msg = format!(
260                    "\
261                     the following are not valid category slugs and were \
262                     ignored: {}. Please see https://crates.io/category_slugs \
263                     for the list of all category slugs. \
264                     ",
265                    warnings.invalid_categories.join(", ")
266                );
267                config.shell().warn(&msg)?;
268            }
269
270            if !warnings.invalid_badges.is_empty() {
271                let msg = format!(
272                    "\
273                     the following are not valid badges and were ignored: {}. \
274                     Either the badge type specified is unknown or a required \
275                     attribute is missing. Please see \
276                     http://doc.crates.io/manifest.html#package-metadata \
277                     for valid badge types and their required attributes.",
278                    warnings.invalid_badges.join(", ")
279                );
280                config.shell().warn(&msg)?;
281            }
282
283            if !warnings.other.is_empty() {
284                for msg in warnings.other {
285                    config.shell().warn(&msg)?;
286                }
287            }
288
289            Ok(())
290        }
291        Err(e) => Err(e),
292    }
293}
294
295pub fn registry_configuration(
296    config: &Config,
297    registry: Option<String>,
298) -> CargoResult<RegistryConfig> {
299    let (index, token) = match registry {
300        Some(registry) => {
301            validate_package_name(&registry, "registry name", "")?;
302            (
303                Some(config.get_registry_index(&registry)?.to_string()),
304                config
305                    .get_string(&format!("registries.{}.token", registry))?
306                    .map(|p| p.val),
307            )
308        }
309        None => {
310            // Checking out for default index and token
311            (
312                config.get_string("registry.index")?.map(|p| p.val),
313                config.get_string("registry.token")?.map(|p| p.val),
314            )
315        }
316    };
317
318    Ok(RegistryConfig { index, token })
319}
320
321pub fn registry(
322    config: &Config,
323    token: Option<String>,
324    index: Option<String>,
325    registry: Option<String>,
326    force_update: bool,
327) -> CargoResult<(Registry, SourceId)> {
328    // Parse all configuration options
329    let RegistryConfig {
330        token: token_config,
331        index: index_config,
332    } = registry_configuration(config, registry.clone())?;
333    let token = token.or(token_config);
334    let sid = get_source_id(config, index_config.or(index), registry)?;
335    let api_host = {
336        let mut src = RegistrySource::remote(sid, config);
337        // Only update the index if the config is not available or `force` is set.
338        let cfg = src.config();
339        let cfg = if force_update || cfg.is_err() {
340            src.update()
341                .chain_err(|| format!("failed to update {}", sid))?;
342            cfg.or_else(|_| src.config())?
343        } else {
344            cfg.unwrap()
345        };
346        cfg.and_then(|cfg| cfg.api)
347            .ok_or_else(|| failure::format_err!("{} does not support API commands", sid))?
348    };
349    let handle = http_handle(config)?;
350    Ok((Registry::new_handle(api_host, token, handle), sid))
351}
352
353/// Create a new HTTP handle with appropriate global configuration for cargo.
354pub fn http_handle(config: &Config) -> CargoResult<Easy> {
355    let (mut handle, timeout) = http_handle_and_timeout(config)?;
356    timeout.configure(&mut handle)?;
357    Ok(handle)
358}
359
360pub fn http_handle_and_timeout(config: &Config) -> CargoResult<(Easy, HttpTimeout)> {
361    if config.frozen() {
362        failure::bail!(
363            "attempting to make an HTTP request, but --frozen was \
364             specified"
365        )
366    }
367    if !config.network_allowed() {
368        failure::bail!("can't make HTTP request in the offline mode")
369    }
370
371    // The timeout option for libcurl by default times out the entire transfer,
372    // but we probably don't want this. Instead we only set timeouts for the
373    // connect phase as well as a "low speed" timeout so if we don't receive
374    // many bytes in a large-ish period of time then we time out.
375    let mut handle = Easy::new();
376    let timeout = configure_http_handle(config, &mut handle)?;
377    Ok((handle, timeout))
378}
379
380pub fn needs_custom_http_transport(config: &Config) -> CargoResult<bool> {
381    let proxy_exists = http_proxy_exists(config)?;
382    let timeout = HttpTimeout::new(config)?.is_non_default();
383    let cainfo = config.get_path("http.cainfo")?;
384    let check_revoke = config.get_bool("http.check-revoke")?;
385    let user_agent = config.get_string("http.user-agent")?;
386
387    Ok(proxy_exists
388        || timeout
389        || cainfo.is_some()
390        || check_revoke.is_some()
391        || user_agent.is_some())
392}
393
394/// Configure a libcurl http handle with the defaults options for Cargo
395pub fn configure_http_handle(config: &Config, handle: &mut Easy) -> CargoResult<HttpTimeout> {
396    if let Some(proxy) = http_proxy(config)? {
397        handle.proxy(&proxy)?;
398    }
399    if let Some(cainfo) = config.get_path("http.cainfo")? {
400        handle.cainfo(&cainfo.val)?;
401    }
402    if let Some(check) = config.get_bool("http.check-revoke")? {
403        handle.ssl_options(SslOpt::new().no_revoke(!check.val))?;
404    }
405    if let Some(user_agent) = config.get_string("http.user-agent")? {
406        handle.useragent(&user_agent.val)?;
407    } else {
408        handle.useragent(&version().to_string())?;
409    }
410
411    if let Some(true) = config.get::<Option<bool>>("http.debug")? {
412        handle.verbose(true)?;
413        handle.debug_function(|kind, data| {
414            let (prefix, level) = match kind {
415                InfoType::Text => ("*", Level::Debug),
416                InfoType::HeaderIn => ("<", Level::Debug),
417                InfoType::HeaderOut => (">", Level::Debug),
418                InfoType::DataIn => ("{", Level::Trace),
419                InfoType::DataOut => ("}", Level::Trace),
420                InfoType::SslDataIn | InfoType::SslDataOut => return,
421                _ => return,
422            };
423            match str::from_utf8(data) {
424                Ok(s) => {
425                    for line in s.lines() {
426                        log!(level, "http-debug: {} {}", prefix, line);
427                    }
428                }
429                Err(_) => {
430                    log!(
431                        level,
432                        "http-debug: {} ({} bytes of data)",
433                        prefix,
434                        data.len()
435                    );
436                }
437            }
438        })?;
439    }
440
441    HttpTimeout::new(config)
442}
443
444#[must_use]
445pub struct HttpTimeout {
446    pub dur: Duration,
447    pub low_speed_limit: u32,
448}
449
450impl HttpTimeout {
451    pub fn new(config: &Config) -> CargoResult<HttpTimeout> {
452        let low_speed_limit = config
453            .get::<Option<u32>>("http.low-speed-limit")?
454            .unwrap_or(10);
455        let seconds = config
456            .get::<Option<u64>>("http.timeout")?
457            .or_else(|| env::var("HTTP_TIMEOUT").ok().and_then(|s| s.parse().ok()))
458            .unwrap_or(30);
459        Ok(HttpTimeout {
460            dur: Duration::new(seconds, 0),
461            low_speed_limit,
462        })
463    }
464
465    fn is_non_default(&self) -> bool {
466        self.dur != Duration::new(30, 0) || self.low_speed_limit != 10
467    }
468
469    pub fn configure(&self, handle: &mut Easy) -> CargoResult<()> {
470        // The timeout option for libcurl by default times out the entire
471        // transfer, but we probably don't want this. Instead we only set
472        // timeouts for the connect phase as well as a "low speed" timeout so
473        // if we don't receive many bytes in a large-ish period of time then we
474        // time out.
475        handle.connect_timeout(self.dur)?;
476        handle.low_speed_time(self.dur)?;
477        handle.low_speed_limit(self.low_speed_limit)?;
478        Ok(())
479    }
480}
481
482/// Find an explicit HTTP proxy if one is available.
483///
484/// Favor cargo's `http.proxy`, then git's `http.proxy`. Proxies specified
485/// via environment variables are picked up by libcurl.
486fn http_proxy(config: &Config) -> CargoResult<Option<String>> {
487    if let Some(s) = config.get_string("http.proxy")? {
488        return Ok(Some(s.val));
489    }
490    if let Ok(cfg) = git2::Config::open_default() {
491        if let Ok(s) = cfg.get_str("http.proxy") {
492            return Ok(Some(s.to_string()));
493        }
494    }
495    Ok(None)
496}
497
498/// Determine if an http proxy exists.
499///
500/// Checks the following for existence, in order:
501///
502/// * cargo's `http.proxy`
503/// * git's `http.proxy`
504/// * `http_proxy` env var
505/// * `HTTP_PROXY` env var
506/// * `https_proxy` env var
507/// * `HTTPS_PROXY` env var
508fn http_proxy_exists(config: &Config) -> CargoResult<bool> {
509    if http_proxy(config)?.is_some() {
510        Ok(true)
511    } else {
512        Ok(["http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY"]
513            .iter()
514            .any(|v| env::var(v).is_ok()))
515    }
516}
517
518pub fn registry_login(
519    config: &Config,
520    token: Option<String>,
521    reg: Option<String>,
522) -> CargoResult<()> {
523    let (registry, _) = registry(config, token.clone(), None, reg.clone(), false)?;
524
525    let token = match token {
526        Some(token) => token,
527        None => {
528            println!(
529                "please visit {}/me and paste the API Token below",
530                registry.host()
531            );
532            let mut line = String::new();
533            let input = io::stdin();
534            input
535                .lock()
536                .read_line(&mut line)
537                .chain_err(|| "failed to read stdin")
538                .map_err(failure::Error::from)?;
539            line.trim().to_string()
540        }
541    };
542
543    let RegistryConfig {
544        token: old_token, ..
545    } = registry_configuration(config, reg.clone())?;
546
547    if let Some(old_token) = old_token {
548        if old_token == token {
549            config.shell().status("Login", "already logged in")?;
550            return Ok(());
551        }
552    }
553
554    config::save_credentials(config, token, reg.clone())?;
555    config.shell().status(
556        "Login",
557        format!(
558            "token for `{}` saved",
559            reg.as_ref().map_or("crates.io", String::as_str)
560        ),
561    )?;
562    Ok(())
563}
564
565pub struct OwnersOptions {
566    pub krate: Option<String>,
567    pub token: Option<String>,
568    pub index: Option<String>,
569    pub to_add: Option<Vec<String>>,
570    pub to_remove: Option<Vec<String>>,
571    pub list: bool,
572    pub registry: Option<String>,
573}
574
575pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
576    let name = match opts.krate {
577        Some(ref name) => name.clone(),
578        None => {
579            let manifest_path = find_root_manifest_for_wd(config.cwd())?;
580            let ws = Workspace::new(&manifest_path, config)?;
581            ws.current()?.package_id().name().to_string()
582        }
583    };
584
585    let (mut registry, _) = registry(
586        config,
587        opts.token.clone(),
588        opts.index.clone(),
589        opts.registry.clone(),
590        true,
591    )?;
592
593    if let Some(ref v) = opts.to_add {
594        let v = v.iter().map(|s| &s[..]).collect::<Vec<_>>();
595        let msg = registry.add_owners(&name, &v).map_err(|e| {
596            failure::format_err!("failed to invite owners to crate {}: {}", name, e)
597        })?;
598
599        config.shell().status("Owner", msg)?;
600    }
601
602    if let Some(ref v) = opts.to_remove {
603        let v = v.iter().map(|s| &s[..]).collect::<Vec<_>>();
604        config
605            .shell()
606            .status("Owner", format!("removing {:?} from crate {}", v, name))?;
607        registry
608            .remove_owners(&name, &v)
609            .chain_err(|| format!("failed to remove owners from crate {}", name))?;
610    }
611
612    if opts.list {
613        let owners = registry
614            .list_owners(&name)
615            .chain_err(|| format!("failed to list owners of crate {}", name))?;
616        for owner in owners.iter() {
617            print!("{}", owner.login);
618            match (owner.name.as_ref(), owner.email.as_ref()) {
619                (Some(name), Some(email)) => println!(" ({} <{}>)", name, email),
620                (Some(s), None) | (None, Some(s)) => println!(" ({})", s),
621                (None, None) => println!(),
622            }
623        }
624    }
625
626    Ok(())
627}
628
629pub fn yank(
630    config: &Config,
631    krate: Option<String>,
632    version: Option<String>,
633    token: Option<String>,
634    index: Option<String>,
635    undo: bool,
636    reg: Option<String>,
637) -> CargoResult<()> {
638    let name = match krate {
639        Some(name) => name,
640        None => {
641            let manifest_path = find_root_manifest_for_wd(config.cwd())?;
642            let ws = Workspace::new(&manifest_path, config)?;
643            ws.current()?.package_id().name().to_string()
644        }
645    };
646    let version = match version {
647        Some(v) => v,
648        None => failure::bail!("a version must be specified to yank"),
649    };
650
651    let (mut registry, _) = registry(config, token, index, reg, true)?;
652
653    if undo {
654        config
655            .shell()
656            .status("Unyank", format!("{}:{}", name, version))?;
657        registry
658            .unyank(&name, &version)
659            .chain_err(|| "failed to undo a yank")?;
660    } else {
661        config
662            .shell()
663            .status("Yank", format!("{}:{}", name, version))?;
664        registry
665            .yank(&name, &version)
666            .chain_err(|| "failed to yank")?;
667    }
668
669    Ok(())
670}
671
672fn get_source_id(
673    config: &Config,
674    index: Option<String>,
675    reg: Option<String>,
676) -> CargoResult<SourceId> {
677    match (reg, index) {
678        (Some(r), _) => SourceId::alt_registry(config, &r),
679        (_, Some(i)) => SourceId::for_registry(&i.to_url()?),
680        _ => {
681            let map = SourceConfigMap::new(config)?;
682            let src = map.load(SourceId::crates_io(config)?)?;
683            Ok(src.replaced_source_id())
684        }
685    }
686}
687
688pub fn search(
689    query: &str,
690    config: &Config,
691    index: Option<String>,
692    limit: u32,
693    reg: Option<String>,
694) -> CargoResult<()> {
695    fn truncate_with_ellipsis(s: &str, max_width: usize) -> String {
696        // We should truncate at grapheme-boundary and compute character-widths,
697        // yet the dependencies on unicode-segmentation and unicode-width are
698        // not worth it.
699        let mut chars = s.chars();
700        let mut prefix = (&mut chars).take(max_width - 1).collect::<String>();
701        if chars.next().is_some() {
702            prefix.push('…');
703        }
704        prefix
705    }
706
707    let (mut registry, _) = registry(config, None, index, reg, false)?;
708    let (crates, total_crates) = registry
709        .search(query, limit)
710        .chain_err(|| "failed to retrieve search results from the registry")?;
711
712    let names = crates
713        .iter()
714        .map(|krate| format!("{} = \"{}\"", krate.name, krate.max_version))
715        .collect::<Vec<String>>();
716
717    let description_margin = names.iter().map(|s| s.len() + 4).max().unwrap_or_default();
718
719    let description_length = cmp::max(80, 128 - description_margin);
720
721    let descriptions = crates.iter().map(|krate| {
722        krate
723            .description
724            .as_ref()
725            .map(|desc| truncate_with_ellipsis(&desc.replace("\n", " "), description_length))
726    });
727
728    for (name, description) in names.into_iter().zip(descriptions) {
729        let line = match description {
730            Some(desc) => {
731                let space = repeat(' ')
732                    .take(description_margin - name.len())
733                    .collect::<String>();
734                name + &space + "# " + &desc
735            }
736            None => name,
737        };
738        println!("{}", line);
739    }
740
741    let search_max_limit = 100;
742    if total_crates > limit && limit < search_max_limit {
743        println!(
744            "... and {} crates more (use --limit N to see more)",
745            total_crates - limit
746        );
747    } else if total_crates > limit && limit >= search_max_limit {
748        println!(
749            "... and {} crates more (go to http://crates.io/search?q={} to see more)",
750            total_crates - limit,
751            percent_encode(query.as_bytes(), QUERY_ENCODE_SET)
752        );
753    }
754
755    Ok(())
756}