2015-03-04 08:31:35 +00:00
|
|
|
// password is a package for reading a password securely from a terminal.
|
|
|
|
// The code in this package disables echo in the terminal so that the
|
|
|
|
// password is not echoed back in plaintext to the user.
|
|
|
|
package password
|
|
|
|
|
|
|
|
import (
|
2015-04-02 00:27:29 +00:00
|
|
|
"errors"
|
2015-03-04 08:31:35 +00:00
|
|
|
"io"
|
|
|
|
"os"
|
2015-04-02 00:27:29 +00:00
|
|
|
"os/signal"
|
2018-12-12 20:06:10 +00:00
|
|
|
"strings"
|
2015-03-04 08:31:35 +00:00
|
|
|
)
|
|
|
|
|
2015-04-02 00:27:29 +00:00
|
|
|
var ErrInterrupted = errors.New("interrupted")
|
|
|
|
|
2015-03-04 08:31:35 +00:00
|
|
|
// Read reads the password from the given os.File. The password
|
2015-04-02 00:27:29 +00:00
|
|
|
// will not be echoed back to the user. Ctrl-C will automatically return
|
|
|
|
// from this function with a blank string and an ErrInterrupted.
|
2015-03-04 08:31:35 +00:00
|
|
|
func Read(f *os.File) (string, error) {
|
2015-04-02 00:27:29 +00:00
|
|
|
ch := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(ch, os.Interrupt)
|
|
|
|
defer signal.Stop(ch)
|
|
|
|
|
|
|
|
// Run the actual read in a go-routine so that we can still detect signals
|
|
|
|
var result string
|
|
|
|
var resultErr error
|
|
|
|
doneCh := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
defer close(doneCh)
|
|
|
|
result, resultErr = read(f)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait on either the read to finish or the signal to come through
|
|
|
|
select {
|
|
|
|
case <-ch:
|
|
|
|
return "", ErrInterrupted
|
|
|
|
case <-doneCh:
|
2018-12-12 20:06:10 +00:00
|
|
|
return removeiTermDelete(result), resultErr
|
2015-04-02 00:27:29 +00:00
|
|
|
}
|
2015-03-04 08:31:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func readline(f *os.File) (string, error) {
|
|
|
|
var buf [1]byte
|
|
|
|
resultBuf := make([]byte, 0, 64)
|
|
|
|
for {
|
|
|
|
n, err := f.Read(buf[:])
|
|
|
|
if err != nil && err != io.EOF {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if n == 0 || buf[0] == '\n' || buf[0] == '\r' {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2015-10-16 23:00:34 +00:00
|
|
|
// ASCII code 3 is what is sent for a Ctrl-C while reading raw.
|
|
|
|
// If we see that, then get the interrupt. We have to do this here
|
|
|
|
// because terminals in raw mode won't catch it at the shell level.
|
|
|
|
if buf[0] == 3 {
|
|
|
|
return "", ErrInterrupted
|
|
|
|
}
|
|
|
|
|
2015-03-04 08:31:35 +00:00
|
|
|
resultBuf = append(resultBuf, buf[0])
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(resultBuf), nil
|
|
|
|
}
|
2018-12-12 20:06:10 +00:00
|
|
|
|
|
|
|
func removeiTermDelete(input string) string {
|
|
|
|
return strings.TrimPrefix(input, "\x20\x7f")
|
|
|
|
}
|