Merge pull request #2221 from classmarkets/2203-password-from-stdin

Fix reading password from stdin
This commit is contained in:
Alexander Neumann 2019-04-22 20:59:59 +02:00
commit 8cab0c121d
2 changed files with 18 additions and 14 deletions

View file

@ -0,0 +1,6 @@
Bugfix: Fix reading passwords from stdin
Passwords for the `init`, `key add`, and `key passwd` commands can now be read from
non-terminal stdin.
https://github.com/restic/restic/issues/2203

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"bufio"
"context" "context"
"fmt" "fmt"
"io" "io"
@ -273,15 +274,10 @@ func resolvePassword(opts GlobalOptions) (string, error) {
// readPassword reads the password from the given reader directly. // readPassword reads the password from the given reader directly.
func readPassword(in io.Reader) (password string, err error) { func readPassword(in io.Reader) (password string, err error) {
buf := make([]byte, 1000) sc := bufio.NewScanner(in)
n, err := io.ReadFull(in, buf) sc.Scan()
buf = buf[:n]
if err != nil && errors.Cause(err) != io.ErrUnexpectedEOF { return sc.Text(), errors.Wrap(err, "Scan")
return "", errors.Wrap(err, "ReadFull")
}
return strings.TrimRight(string(buf), "\r\n"), nil
} }
// readPasswordTerminal reads the password from the given reader which must be a // readPasswordTerminal reads the password from the given reader which must be a
@ -336,13 +332,15 @@ func ReadPasswordTwice(gopts GlobalOptions, prompt1, prompt2 string) (string, er
if err != nil { if err != nil {
return "", err return "", err
} }
pw2, err := ReadPassword(gopts, prompt2) if stdinIsTerminal() {
if err != nil { pw2, err := ReadPassword(gopts, prompt2)
return "", err if err != nil {
} return "", err
}
if pw1 != pw2 { if pw1 != pw2 {
return "", errors.Fatal("passwords do not match") return "", errors.Fatal("passwords do not match")
}
} }
return pw1, nil return pw1, nil