Crate gets

source ·
Expand description

gets

Pure Rust implementation of the function in the C standard that is impossible to use without introducing security vulnerabilities.

Example usage

// Stupid warnings! I've programmed for years, I know what I'm doing!
#![allow(warnings)]

// Serde did this, so it's fine, right?
let mut buf: [c_char; 128] = std::mem::uninitialized();

println!("What is your name?");

// Surely nobody would ever input anything longer than 127 bytes?
let ptr = gets(buf.as_mut_ptr());

if ptr.is_null() {
    return;
}

// Surely nobody would ever input invalid UTF-8?
let name = CStr::from_ptr(ptr).to_str().unwrap_unchecked();

println!("Hello, {}!", name);
$ cargo run --example basic
   Compiling gets v0.0.1 (/home/idiot/gets)
    Finished dev [unoptimized + debuginfo] target(s) in 0.15s
     Running `target/debug/examples/basic`
What is your name?
I don't know buffer overflows are a thing
Hello, I don't know buffer overflows are a thing!

$ This seems to be fine, let's run it in production, what could go wrong??
This: command not found

$ cargo run --example basic --release
   Compiling gets v0.0.1 (/home/idiot/gets)
    Finished release [optimized] target(s) in 0.13s
     Running `target/release/examples/basic`
What is your name?
Charles the Third, by the Grace of God of the United Kingdom of Great Britain and Northern Ireland and of His other Realms and Territories King, Head of the Commonwealth, Defender of the Faith
Hello, Charles the Third, by the Grace of God of the United Kingdom of Great Britain and Northern Ireland and of His other Realms and Territories King, Head of the Commonwealth, Defender of the Faith!
Segmentation fault (core dumped)

$ Oh no, it crashed. Maybe I should use location services to increase the buffer size if the user is in Buckingham Palace?
Oh: command not found

Functions

  • gets
    Reads from standard input into the buffer until the next new-line character or end of file is reached. Appends the bytes followed by a null byte to the buffer. The new-line character is discarded.