Can I block writing to stdout on keypress? [duplicate] - rust

How can I get password input without showing user input?
fn main() {
println!("Type Your Password");
// I want to hide input here, and do not know how
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
println!("{}", input);
}

Update: you can use the rpassword crate. Quoting from the README:
Add the rpassword crate to your Cargo.toml:
[dependencies]
rpassword = "0.0.4"
Then use the read_password() function:
extern crate rpassword;
use rpassword::read_password;
use std::io::Write;
fn main() {
print!("Type a password: ");
std::io::stdout().flush().unwrap();
let password = read_password().unwrap();
println!("The password is: '{}'", password);
}
Old answer
I suspect your best bet is calling some C functions from rust: either getpass (3) or its recommended alternatives (see
Getting a password in C without using getpass). The tricky thing is that it differs by platform, of course (if you get it working, it'd be handy as a crate).
Depending on your requirements, you could also try using ncurses-rs (crate "ncurses"); I haven't tested it but it looks like example 2 might demo turning off echoing input.

Related

Security measure to implement a password field on rust? [duplicate]

How can I get password input without showing user input?
fn main() {
println!("Type Your Password");
// I want to hide input here, and do not know how
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
println!("{}", input);
}
Update: you can use the rpassword crate. Quoting from the README:
Add the rpassword crate to your Cargo.toml:
[dependencies]
rpassword = "0.0.4"
Then use the read_password() function:
extern crate rpassword;
use rpassword::read_password;
use std::io::Write;
fn main() {
print!("Type a password: ");
std::io::stdout().flush().unwrap();
let password = read_password().unwrap();
println!("The password is: '{}'", password);
}
Old answer
I suspect your best bet is calling some C functions from rust: either getpass (3) or its recommended alternatives (see
Getting a password in C without using getpass). The tricky thing is that it differs by platform, of course (if you get it working, it'd be handy as a crate).
Depending on your requirements, you could also try using ncurses-rs (crate "ncurses"); I haven't tested it but it looks like example 2 might demo turning off echoing input.

Proper way to handle a compile-time relevant text file passed to a procedural macro

I have a requirement to pass to a procedural macro either a text file or the contents of a text file, such that the procedural macro acts based on the contents of that text file at compile time. That is, the text file configures the output of the macro. The use case for this is the file defining a register map which the macro builds into a library.
The second requirement is that the text file is properly handled by Cargo, such that changes to the text file trigger a recompile in the same way as changes to the source file trigger a recompile.
My initial thought was to create a static string using the include_str! macro. This solves the second requirement but I can't see how to pass that to the macro - at that point I only have the identifier of the string to pass in:
use my_macro_lib::my_macro;
static MYSTRING: &'static str = include_str!("myfile");
my_macro!(MYSTRING); // Not the string itself!
I can pass a string to the macro with the name of the file in a string literal, and open the file inside the macro:
my_macro!("myfile");
At which point I have two problems:
It's not obvious how to get the path of the calling function in order to get the path of the file. I initially thought this would be exposed through the token Span, but it seems in general not (perhaps I'm missing something?).
It's not obvious how to make the file make Cargo trigger a recompile on changes. One idea I had to force this was to add an include_str!("myfile") to the output of the macro, which would hopefully result in the compile being made aware of "myfile", but this is a bit mucky.
Is there some way to do what I'm trying to do? Perhaps either by somehow getting the contents of the string inside the macro that was created outside, or reliably getting the path of the calling rust file (then making Cargo treat changes properly).
As an aside, I've read various places that tell me I can't get access to the contents of variables inside the macro, but it seems to me that this is exactly what the quote macro is doing with #variables. How is this working?
So it turns out this is possible in essentially the way I was hoping with the stable compiler.
If we accept that we need to work relative to the crate root, we can define our paths as such.
Helpfully, inside the macro code, std::env::current_dir() will return the current working directory as the root of the crate containing the call site. This means, even if the macro invocation is inside some crate hierarchy, it will still return a path that is meaningful at the location of the macro invocation.
The following example macro does essentially what I need. For brevity, it's not designed to handle errors properly:
extern crate proc_macro;
use quote::quote;
use proc_macro::TokenStream;
use syn::parse::{Parse, ParseStream, Result};
use syn;
use std;
use std::fs::File;
use std::io::Read;
#[derive(Debug)]
struct FileName {
filename: String,
}
impl Parse for FileName {
fn parse(input: ParseStream) -> Result<Self> {
let lit_file: syn::LitStr = input.parse()?;
Ok(Self { filename: lit_file.value() })
}
}
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as FileName);
let cwd = std::env::current_dir().unwrap();
let file_path = cwd.join(&input.filename);
let file_path_str = format!("{}", file_path.display());
println!("path: {}", file_path.display());
let mut file = File::open(file_path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
println!("contents: {:?}", contents);
let result = quote!(
const FILE_STR: &'static str = include_str!(#file_path_str);
pub fn foo() -> bool {
println!("Hello");
true
}
);
TokenStream::from(result)
}
Which can be invoked with
my_macro!("mydir/myfile");
where mydir is a directory in the root of the invoking crate.
This uses the hack of using an include_str!() in the macro output to cause rebuilds on changes to myfile. This is necessary and does what is expected. I would expect this to be optimised out if it's never actually used.
I'd be interested to know if this approach falls over in any situation.
Relevant to my original question, current nightly implements the source_file() method on Span. This might be a better way to implement the above, but I'd rather stick with stable. The tracking issue for this is here.
Edit:
The above implementation fails when the package is in a workspace, at which point the current working directory is the workspace root, not the crate root. This is easy to work around with something like as follows (inserted between cwd and file_path declarations).
let mut cwd = std::env::current_dir().unwrap();
let cargo_path = cwd.join("Cargo.toml");
let mut cargo_file = File::open(cargo_path).unwrap();
let mut cargo_contents = String::new();
cargo_file.read_to_string(&mut cargo_contents).unwrap();
// Use a simple regex to detect the suitable tag in the toml file. Much
// simpler than using the toml crate and probably good enough according to
// the workspace RFC.
let cargo_re = regex::Regex::new(r"(?m)^\[workspace\][ \t]*$").unwrap();
let workspace_path = match cargo_re.find(&cargo_contents) {
Some(val) => std::env::var("CARGO_PKG_NAME"),
None => "".to_string()
};
let file_path = cwd.join(workspace_path).join(input.filename);
let file_path_str = format!("{}", file_path.display());

Should I prefer path.display() over debug {:?} formatting?

Is there any performance hit when using the first?
Is it possible that some characters will be displayed improperly when using the second?
As explained in the documentation, Path::display is for safely printing paths that may contain non-Unicode data.
Debug preserves those characters, but is not meant to be presented to the end-user. Also, Debug surrounds the path with quotes.
For example on Linux:
use std::path::Path;
use std::os::unix::ffi::OsStrExt;
use std::ffi::OsStr;
fn main() {
let path = OsStr::from_bytes(b"./foo/bar\xff.txt");
let path = Path::new(path);
println!("{}", path.display()); // ./foo/bar�.txt
println!("{:?}", path); // "./foo/bar\xFF.txt"
}
(Permalink to the playground)

How can I get password input without showing user input?

How can I get password input without showing user input?
fn main() {
println!("Type Your Password");
// I want to hide input here, and do not know how
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
println!("{}", input);
}
Update: you can use the rpassword crate. Quoting from the README:
Add the rpassword crate to your Cargo.toml:
[dependencies]
rpassword = "0.0.4"
Then use the read_password() function:
extern crate rpassword;
use rpassword::read_password;
use std::io::Write;
fn main() {
print!("Type a password: ");
std::io::stdout().flush().unwrap();
let password = read_password().unwrap();
println!("The password is: '{}'", password);
}
Old answer
I suspect your best bet is calling some C functions from rust: either getpass (3) or its recommended alternatives (see
Getting a password in C without using getpass). The tricky thing is that it differs by platform, of course (if you get it working, it'd be handy as a crate).
Depending on your requirements, you could also try using ncurses-rs (crate "ncurses"); I haven't tested it but it looks like example 2 might demo turning off echoing input.

How to send output to stderr?

One uses this to send output to stdout:
println!("some output")
I think there is no corresponding macro to do the same for stderr.
After Rust 1.19
As of Rust 1.19, you can use the eprint and eprintln macros:
fn main() {
eprintln!("This is going to standard error!, {}", "awesome");
}
This was originally proposed in RFC 1896.
Before Rust 1.19
You can see the implementation of println! to dive into exactly how it works, but it was a bit overwhelming when I first read it.
You can format stuff to stderr using similar macros though:
use std::io::Write;
let name = "world";
writeln!(&mut std::io::stderr(), "Hello {}!", name);
This will give you a unused result which must be used warning though, as printing to IO can fail (this is not something we usually think about when printing!). We can see that the existing methods simply panic in this case, so we can update our code to do the same:
use std::io::Write;
let name = "world";
let r = writeln!(&mut std::io::stderr(), "Hello {}!", name);
r.expect("failed printing to stderr");
This is a bit much, so let's wrap it back in a macro:
use std::io::Write;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
r.expect("failed printing to stderr");
} }
);
fn main() {
let name = "world";
println_stderr!("Hello {}!", name)
}
print! and println! are convenience methods for writing to standard output. There are other macros with the same formatting features available for different tasks:
write! and writeln! to write a formatted string to a &mut Writer
format! to just generate a formatted String
To write to the standard error stream, you can use e.g. writeln! like this:
use std::io::Write;
fn main() {
let mut stderr = std::io::stderr();
writeln!(&mut stderr, "Error!").unwrap();
}
It's done so:
use std::io::Write;
fn main() {
std::io::stderr().write(b"some output\n");
}
You can test it by sending the program output to /dev/null to ensure it works (I ignore the warning):
$ rustc foo.rs && ./foo > /dev/null
foo.rs:4:5: 4:42 warning: unused result which must be used, #[warn(unused_must_use)] on by default
foo.rs:4 io::stderr().write(b"some output\n");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
some output
Similarly, one can do the following for stdout:
use std::io::Write;
fn main() {
std::io::stdout().write(b"some output\n");
}
I think this means println! is just a convenience: it's shorter and it also allows some formatting. As an example of the latter, the following displays 0x400:
println!("0x{:x}", 1024u)
While not answering the precise question, maybe it’s of interest that there’s a log crate which specifies an interface for leveled logging that other crates (e.g. env_logger) can fulfill.
The output of such logging will be sent to stderr, and there are additional benefits for users, such as specifying the log level.
This is how using such a logger could look like:
#[macro_use]
extern crate log;
extern crate env_logger;
fn main() {
env_logger::init().unwrap();
error!("this is printed by default");
}
(Example adapted from http://burntsushi.net/rustdoc/env_logger/index.html#example)
Goal
stderr!("Code {}: Danger, Will Robinson! Danger!", 42);
Notes
The other answers generate an unused import warning with the latest nightly, so here's a modern macro that Just Works TM.
Code
macro_rules! stderr {
($($arg:tt)*) => (
use std::io::Write;
match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
Ok(_) => {},
Err(x) => panic!("Unable to write to stderr (file handle closed?): {}", x),
}
)
}

Resources