rpassword-4.0.5/.gitignore010066000017500001751000000001111357224255700137610ustar0000000000000000/target /Cargo.lock /tests/*_actual_* /tests/stdout /tests/stderr /.idea rpassword-4.0.5/.travis.yml010064000017500001751000000001701332765316000140770ustar0000000000000000language: rust os: - linux - osx rust: - stable script: - cargo build --example tests - ./tests/tests-unix.sh rpassword-4.0.5/Cargo.toml.orig010066000017500001751000000012241361144000000146370ustar0000000000000000[package] name = "rpassword" version = "4.0.5" authors = ["Conrad Kleinespel "] description = "Read passwords in console applications." license = "Apache-2.0" homepage = "https://github.com/conradkleinespel/rpassword" repository = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = ["read", "password", "security", "pass", "getpass"] [target.'cfg(unix)'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon"] } rpassword-4.0.5/Cargo.toml0000644000000022371361144176400111750ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "rpassword" version = "4.0.5" authors = ["Conrad Kleinespel "] description = "Read passwords in console applications." homepage = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = ["read", "password", "security", "pass", "getpass"] license = "Apache-2.0" repository = "https://github.com/conradkleinespel/rpassword" [target."cfg(unix)".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon"] rpassword-4.0.5/LICENSE-APACHE010064000017500001751000000236751332765316000137310ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS rpassword-4.0.5/README.md010066000017500001751000000055601361143775200132620ustar0000000000000000# Rustastic Password [![Build Status](https://travis-ci.org/conradkleinespel/rpassword.svg?branch=master)](https://travis-ci.org/conradkleinespel/rpassword) [![Build status](https://ci.appveyor.com/api/projects/status/h7ak407y28k0ufw2?svg=true)](https://ci.appveyor.com/project/conradkleinespel/rpassword) [![Chat on Discord](https://img.shields.io/badge/chat-on%20discord-7289DA)](https://discord.gg/9zXtYqQ) `rpassword` package allows you to safely read passwords in a console application on Linux, OSX and Windows. ## Supporting `rpassword` `rpassword` is currently being maintained as a side-project, during nights and weekends, next to my full-time job. I am looking for a way to sustain my work on open source. If you find value in what I do and you would like to contribute, please consider: - [Becoming a backer on Patreon](https://www.patreon.com/conradkleinespel) - [Making a recurring donation on Liberapay](https://liberapay.com/conradkleinespel/) ## Usage Add `rpassword` as a dependency in Cargo.toml: ```toml [dependencies] rpassword = "4.0" ``` Use `rpassword` within your code: ```rust extern crate rpassword; fn main() { // Prompt for a password on TTY (safest but not default for backwards compatibility) let pass = rpassword::read_password_from_tty(Some("Password: ")).unwrap(); println!("Your password is {}", pass); // Prompt for a password on STDOUT let pass = rpassword::prompt_password_stdout("Password: ").unwrap(); println!("Your password is {}", pass); // Prompt for a password on STDERR let pass = rpassword::prompt_password_stderr("Password: ").unwrap(); println!("Your password is {}", pass); // Read a password without prompt let pass = rpassword::read_password().unwrap(); println!("Your password is {}", pass); } ``` The full API documentation is available at [https://docs.rs/rpassword](https://docs.rs/rpassword). ## Contributors We welcome contribution from everyone. Feel free to open an issue or a pull request at any time. Here's a list of existing `rpassword` contributors: * [@C4K3](https://github.com/C4K3) * [@conradkleinespel](https://github.com/conradkleinespel) * [@DaveLancaster](https://github.com/DaveLancaster) * [@dcuddeback](https://github.com/dcuddeback) * [@Draphar](https://github.com/Draphar) * [@equalsraf](https://github.com/equalsraf) * [@JanLikar](https://github.com/JanLikar) * [@joshuef](https://github.com/joshuef) * [@longshorej](https://github.com/longshorej) * [@petevine](https://github.com/petevine) * [@psych0d0g](https://github.com/psych0d0g) * [@retep998](https://github.com/retep998) * [@steveatinfincia](https://github.com/steveatinfincia) * [@teythoon](https://github.com/teythoon) * [@tov](https://github.com/tov) * [@yandexx](https://github.com/yandexx) Thank you very much for your help! :smiley: :heart: ## License The source code is released under the Apache 2.0 license. rpassword-4.0.5/appveyor.yml010066000017500001751000000006721345626673400144010ustar0000000000000000environment: matrix: - TARGET: x86_64-pc-windows-gnu - TARGET: i686-pc-windows-gnu install: - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-1.33.0-${env:TARGET}.exe" - rust-1.33.0-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - SET PATH=%PATH%;C:\MinGW\bin - rustc -V - cargo -V build: false test_script: - cargo test --verbose rpassword-4.0.5/examples/read-password-tty.rs010066000017500001751000000003361337705123200175460ustar0000000000000000//! This example demonstrates how to read a password from the tty. extern crate rpassword; fn main() { let pass = rpassword::read_password_from_tty(Some("Password: ")).unwrap(); println!("Password: {}", pass); } rpassword-4.0.5/examples/read-password.rs010066000017500001751000000003011347000553400167160ustar0000000000000000//! This example demonstrates how to read a password from STDIN. extern crate rpassword; fn main() { let pass = rpassword::read_password().unwrap(); println!("Password: {}", pass); } rpassword-4.0.5/examples/tests.rs010064000017500001751000000021331332765316000153150ustar0000000000000000// Copyright 2014-2017 The Rpassword Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate rpassword; fn main() { // Password reading functions match rpassword::read_password() { Ok(pass) => println!("{}", pass), Err(_) => println!("error") } match rpassword::prompt_password_stdout("prompt_password_stdout") { Ok(pass) => println!("{}", pass), Err(_) => println!("error") } match rpassword::prompt_password_stderr("prompt_password_stderr") { Ok(pass) => println!("{}", pass), Err(_) => println!("error") } } rpassword-4.0.5/src/lib.rs010066000017500001751000000237271361143743600137120ustar0000000000000000// Copyright 2014-2017 The Rpassword Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[cfg(unix)] extern crate libc; #[cfg(windows)] extern crate winapi; use std::io::Write; mod zero_on_drop; use zero_on_drop::ZeroOnDrop; /// Removes the \n from the read line fn fixes_newline(password: &mut ZeroOnDrop) { // We may not have a newline, e.g. if user sent CTRL-D or if // this is not a TTY. if password.ends_with('\n') { // Remove the \n from the line if present password.pop(); // Remove the \r from the line if present if password.ends_with('\r') { password.pop(); } } } /// Reads a password from STDIN pub fn read_password() -> ::std::io::Result { read_password_with_reader(None::<::std::io::Empty>) } #[cfg(unix)] mod unix { use libc::{c_int, termios, isatty, tcsetattr, TCSANOW, ECHO, ECHONL, STDIN_FILENO}; use std::io::{self, BufRead, Write}; use std::mem; use std::os::unix::io::AsRawFd; /// Turns a C function return into an IO Result fn io_result(ret: c_int) -> ::std::io::Result<()> { match ret { 0 => Ok(()), _ => Err(::std::io::Error::last_os_error()), } } fn safe_tcgetattr(fd: c_int) -> ::std::io::Result { let mut term = mem::MaybeUninit::<::unix::termios>::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } /// Reads a password from stdin pub fn read_password_from_stdin(open_tty: bool) -> ::std::io::Result { let mut password = super::ZeroOnDrop::new(); enum Source { Tty(io::BufReader<::std::fs::File>), Stdin(io::Stdin), } let (tty_fd, mut source) = if open_tty { let tty = ::std::fs::File::open("/dev/tty")?; (tty.as_raw_fd(), Source::Tty(io::BufReader::new(tty))) } else { (STDIN_FILENO, Source::Stdin(io::stdin())) }; let input_is_tty = unsafe { isatty(tty_fd) } == 1; // When we ask for a password in a terminal, we'll want to hide the password as it is // typed by the user if input_is_tty { // Make two copies of the terminal settings. The first one will be modified // and the second one will act as a backup for when we want to set the // terminal back to its original state. let mut term = safe_tcgetattr(tty_fd)?; let term_orig = safe_tcgetattr(tty_fd)?; // Hide the password. This is what makes this function useful. term.c_lflag &= !ECHO; // But don't hide the NL character when the user hits ENTER. term.c_lflag |= ECHONL; // Save the settings for now. io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term) })?; // Read the password. let input = match source { Source::Tty(ref mut tty) => tty.read_line(&mut password), Source::Stdin(ref mut stdin) => stdin.read_line(&mut password), }; // Check the response. match input { Ok(_) => {} Err(err) => { // Reset the terminal and quit. io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term_orig) })?; return Err(err); } }; // Reset the terminal. io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term_orig) })?; } else { // If we don't have a TTY, the input was piped so we bypass // terminal hiding code match source { Source::Tty(mut tty) => tty.read_line(&mut password)?, Source::Stdin(stdin) => stdin.read_line(&mut password)?, }; } super::fixes_newline(&mut password); Ok(password.into_inner()) } /// Displays a prompt on the terminal pub fn display_on_tty(prompt: &str) -> ::std::io::Result<()> { let mut stream = ::std::fs::OpenOptions::new().write(true).open("/dev/tty")?; write!(stream, "{}", prompt)?; stream.flush() } } #[cfg(windows)] mod windows { use std::ptr; use std::io::{self, Write}; use std::os::windows::io::{FromRawHandle, AsRawHandle}; use winapi::um::winnt::{ GENERIC_READ, GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE, }; use winapi::um::fileapi::{CreateFileA, OPEN_EXISTING}; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::STD_INPUT_HANDLE; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::shared::minwindef::LPDWORD; use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}; /// Reads a password from stdin pub fn read_password_from_stdin(open_tty: bool) -> io::Result { let mut password = super::ZeroOnDrop::new(); // Get the stdin handle let handle = if open_tty { unsafe { CreateFileA(b"CONIN$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null_mut(), OPEN_EXISTING, 0, ptr::null_mut()) } } else { unsafe { GetStdHandle(STD_INPUT_HANDLE) } }; if handle == INVALID_HANDLE_VALUE { return Err(::std::io::Error::last_os_error()); } // Get the old mode so we can reset back to it when we are done let mut mode = 0; if unsafe { GetConsoleMode(handle, &mut mode as LPDWORD) } == 0 { return Err(::std::io::Error::last_os_error()); } // We want to be able to read line by line, and we still want backspace to work let new_mode_flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; if unsafe { SetConsoleMode(handle, new_mode_flags) } == 0 { return Err(::std::io::Error::last_os_error()); } // Read the password. let source = io::stdin(); let input = source.read_line(&mut password); let handle = source.as_raw_handle(); // Check the response. let _ = input?; // Set the the mode back to normal if unsafe { SetConsoleMode(handle, mode) } == 0 { return Err(::std::io::Error::last_os_error()); } super::fixes_newline(&mut password); // Newline for windows which otherwise prints on the same line. println!(); Ok(password.into_inner()) } /// Displays a prompt on the terminal pub fn display_on_tty(prompt: &str) -> ::std::io::Result<()> { let handle = unsafe { CreateFileA(b"CONOUT$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, ::std::ptr::null_mut(), OPEN_EXISTING, 0, ::std::ptr::null_mut()) }; if handle == INVALID_HANDLE_VALUE { return Err(::std::io::Error::last_os_error()); } let mut stream = unsafe { ::std::fs::File::from_raw_handle(handle) }; write!(stream, "{}", prompt)?; stream.flush() } } #[cfg(unix)] use unix::{read_password_from_stdin, display_on_tty}; #[cfg(windows)] use windows::{read_password_from_stdin, display_on_tty}; /// Reads a password from anything that implements BufRead pub fn read_password_with_reader(source: Option) -> ::std::io::Result where T: ::std::io::BufRead { match source { Some(mut reader) => { let mut password = ZeroOnDrop::new(); if let Err(err) = reader.read_line(&mut password) { Err(err) } else { fixes_newline(&mut password); Ok(password.into_inner()) } }, None => read_password_from_stdin(false), } } /// Reads a password from the terminal pub fn read_password_from_tty(prompt: Option<&str>) -> ::std::io::Result { if let Some(prompt) = prompt { display_on_tty(prompt)?; } read_password_from_stdin(true) } /// Prompts for a password on STDOUT and reads it from STDIN pub fn prompt_password_stdout(prompt: &str) -> std::io::Result { let mut stdout = std::io::stdout(); write!(stdout, "{}", prompt)?; stdout.flush()?; read_password() } /// Prompts for a password on STDERR and reads it from STDIN pub fn prompt_password_stderr(prompt: &str) -> std::io::Result { let mut stderr = std::io::stderr(); write!(stderr, "{}", prompt)?; stderr.flush()?; read_password() } #[cfg(test)] mod tests { use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input() { let response = ::read_password_with_reader(Some(mock_input_crlf())).unwrap(); assert_eq!(response, "A mocked response."); let response = ::read_password_with_reader(Some(mock_input_lf())).unwrap(); assert_eq!(response, "A mocked response."); } } rpassword-4.0.5/src/zero_on_drop.rs010066000017500001751000000020711361143740700156260ustar0000000000000000use std::{ops, mem, ptr, sync::atomic}; // Holds a string and zeros it when we're done. pub struct ZeroOnDrop { inner: Inner } impl ZeroOnDrop { pub fn new() -> Self { ZeroOnDrop { inner: Inner(String::new()) } } pub fn into_inner(mut self) -> String { mem::replace(&mut self.inner.0, String::new()) } } impl ops::Deref for ZeroOnDrop { type Target = String; fn deref(&self) -> &Self::Target { &self.inner.0 } } impl ops::DerefMut for ZeroOnDrop { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner.0 } } struct Inner(String); impl Drop for Inner { fn drop(&mut self) { self.zero_memory(); } } impl Inner { /// Sets all bytes of a String to 0 fn zero_memory(&mut self) { let default = u8::default(); for c in unsafe { self.0.as_bytes_mut() } { unsafe { ptr::write_volatile(c, default) }; } atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); } } rpassword-4.0.5/tests/no-terminal.rs010066000017500001751000000023011352363750300157240ustar0000000000000000//! This test checks whether or not we can read from a reader when //! stdin is not a terminal. use std::io::Cursor; extern crate rpassword; use rpassword::read_password_with_reader; #[cfg(unix)] extern crate libc; #[cfg(unix)] fn close_stdin() { unsafe { libc::close(libc::STDIN_FILENO); } } #[cfg(windows)] extern crate winapi; #[cfg(windows)] fn close_stdin() { use winapi::um::handleapi::CloseHandle; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::STD_INPUT_HANDLE; unsafe { CloseHandle( GetStdHandle(STD_INPUT_HANDLE) ); } } #[cfg(not(any(unix, windows)))] fn close_stdin() { unimplemented!() } fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input() { close_stdin(); let response = ::read_password_with_reader(Some(mock_input_crlf())).unwrap(); assert_eq!(response, "A mocked response."); let response = ::read_password_with_reader(Some(mock_input_lf())).unwrap(); assert_eq!(response, "A mocked response."); } rpassword-4.0.5/tests/results_pipe_expected_stderr010064000017500001751000000000261332765316000210350ustar0000000000000000prompt_password_stderrrpassword-4.0.5/tests/results_pipe_expected_stdout010064000017500001751000000000341332765316000210530ustar00000000000000001 prompt_password_stdout2 3 rpassword-4.0.5/tests/results_pipe_missing_nl_expected_stderr010064000017500001751000000000261332765316000232570ustar0000000000000000prompt_password_stderrrpassword-4.0.5/tests/results_pipe_missing_nl_expected_stdout010066000017500001751000000000341344452733500233030ustar00000000000000001 prompt_password_stdout2 3 rpassword-4.0.5/tests/tests-unix.sh010075000017500001751000000027421332765316000156200ustar0000000000000000#!/usr/bin/env bash set -e DIR="$( dirname $( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) )" # STDIN comes from a terminal: we can't properly unit test this, so we need to # test by hand. The following test must be made: # - ./target/debug/examples/tests > tests/stdout 2> tests/stderr - press 1, ENTER, 2, ENTER, 3, ENTER, 4, ENTER, 5, ENTER, 6, ENTER # - you should not see 1/2/3 displayed, but you should see 4/5/6 displayed # - the following diffs should be empty # - diff tests/stdout <(printf "1\nprompt_password_stdout2\n3\n4\nprompt_reply_stdout5\n6\n") # - diff tests/stderr <(printf "prompt_password_stderrprompt_reply_stderr") # STDIN comes from a pipe printf "1\n2\n3\n" | $DIR/target/debug/examples/tests > $DIR/tests/results_pipe_actual_stdout 2> $DIR/tests/results_pipe_actual_stderr diff $DIR/tests/results_pipe_expected_stdout $DIR/tests/results_pipe_actual_stdout echo 'pipe stdout OK' diff $DIR/tests/results_pipe_expected_stderr $DIR/tests/results_pipe_actual_stderr echo 'pipe stderr OK' # missing newline, only tested in pipe mode printf "1\n2\n3" | $DIR/target/debug/examples/tests > $DIR/tests/results_pipe_missing_nl_actual_stdout 2> $DIR/tests/results_pipe_missing_nl_actual_stderr diff $DIR/tests/results_pipe_missing_nl_expected_stdout $DIR/tests/results_pipe_missing_nl_actual_stdout echo 'pipe with missing nl stdout OK' diff $DIR/tests/results_pipe_missing_nl_expected_stderr $DIR/tests/results_pipe_missing_nl_actual_stderr echo 'pipe with missing nl stderr OK' rpassword-4.0.5/.cargo_vcs_info.json0000644000000001121361144176400131650ustar00{ "git": { "sha1": "096c3522ddcd809ece27df6e4ac3ee6cfb3175ed" } } rpassword-4.0.5/Cargo.lock0000644000000031611361144176400111470ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "libc" version = "0.2.66" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "rpassword" version = "4.0.5" dependencies = [ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] "checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"