Vendor temporarily
This commit is contained in:
1 parent
dd8e532d18
commit
1c02ed9115
4708 files changed
+1226392
-12
No files matched your search
+20
@@ -0,0 +1,20 @@
|
||||
Original version Copyright © 2010 Fazlul Shahriar <fshahriar@gmail.com>. Newer
|
||||
portions Copyright © 2014 Blake Gentry <blakesgentry@gmail.com>.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+510
@@ -0,0 +1,510 @@
|
||||
package netrc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type tkType int
|
||||
|
||||
const (
|
||||
tkMachine tkType = iota
|
||||
tkDefault
|
||||
tkLogin
|
||||
tkPassword
|
||||
tkAccount
|
||||
tkMacdef
|
||||
tkComment
|
||||
tkWhitespace
|
||||
)
|
||||
|
||||
var keywords = map[string]tkType{
|
||||
"machine": tkMachine,
|
||||
"default": tkDefault,
|
||||
"login": tkLogin,
|
||||
"password": tkPassword,
|
||||
"account": tkAccount,
|
||||
"macdef": tkMacdef,
|
||||
"#": tkComment,
|
||||
}
|
||||
|
||||
type Netrc struct {
|
||||
tokens []*token
|
||||
machines []*Machine
|
||||
macros Macros
|
||||
updateLock sync.Mutex
|
||||
}
|
||||
|
||||
// FindMachine returns the Machine in n named by name. If a machine named by
|
||||
// name exists, it is returned. If no Machine with name name is found and there
|
||||
// is a ``default'' machine, the ``default'' machine is returned. Otherwise, nil
|
||||
// is returned.
|
||||
func (n *Netrc) FindMachine(name string) (m *Machine) {
|
||||
// TODO(bgentry): not safe for concurrency
|
||||
var def *Machine
|
||||
for _, m = range n.machines {
|
||||
if m.Name == name {
|
||||
return m
|
||||
}
|
||||
if m.IsDefault() {
|
||||
def = m
|
||||
}
|
||||
}
|
||||
if def == nil {
|
||||
return nil
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// MarshalText implements the encoding.TextMarshaler interface to encode a
|
||||
// Netrc into text format.
|
||||
func (n *Netrc) MarshalText() (text []byte, err error) {
|
||||
// TODO(bgentry): not safe for concurrency
|
||||
for i := range n.tokens {
|
||||
switch n.tokens[i].kind {
|
||||
case tkComment, tkDefault, tkWhitespace: // always append these types
|
||||
text = append(text, n.tokens[i].rawkind...)
|
||||
default:
|
||||
if n.tokens[i].value != "" { // skip empty-value tokens
|
||||
text = append(text, n.tokens[i].rawkind...)
|
||||
}
|
||||
}
|
||||
if n.tokens[i].kind == tkMacdef {
|
||||
text = append(text, ' ')
|
||||
text = append(text, n.tokens[i].macroName...)
|
||||
}
|
||||
text = append(text, n.tokens[i].rawvalue...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (n *Netrc) NewMachine(name, login, password, account string) *Machine {
|
||||
n.updateLock.Lock()
|
||||
defer n.updateLock.Unlock()
|
||||
|
||||
prefix := "\n"
|
||||
if len(n.tokens) == 0 {
|
||||
prefix = ""
|
||||
}
|
||||
m := &Machine{
|
||||
Name: name,
|
||||
Login: login,
|
||||
Password: password,
|
||||
Account: account,
|
||||
|
||||
nametoken: &token{
|
||||
kind: tkMachine,
|
||||
rawkind: []byte(prefix + "machine"),
|
||||
value: name,
|
||||
rawvalue: []byte(" " + name),
|
||||
},
|
||||
logintoken: &token{
|
||||
kind: tkLogin,
|
||||
rawkind: []byte("\n\tlogin"),
|
||||
value: login,
|
||||
rawvalue: []byte(" " + login),
|
||||
},
|
||||
passtoken: &token{
|
||||
kind: tkPassword,
|
||||
rawkind: []byte("\n\tpassword"),
|
||||
value: password,
|
||||
rawvalue: []byte(" " + password),
|
||||
},
|
||||
accounttoken: &token{
|
||||
kind: tkAccount,
|
||||
rawkind: []byte("\n\taccount"),
|
||||
value: account,
|
||||
rawvalue: []byte(" " + account),
|
||||
},
|
||||
}
|
||||
n.insertMachineTokensBeforeDefault(m)
|
||||
for i := range n.machines {
|
||||
if n.machines[i].IsDefault() {
|
||||
n.machines = append(append(n.machines[:i], m), n.machines[i:]...)
|
||||
return m
|
||||
}
|
||||
}
|
||||
n.machines = append(n.machines, m)
|
||||
return m
|
||||
}
|
||||
|
||||
func (n *Netrc) insertMachineTokensBeforeDefault(m *Machine) {
|
||||
newtokens := []*token{m.nametoken}
|
||||
if m.logintoken.value != "" {
|
||||
newtokens = append(newtokens, m.logintoken)
|
||||
}
|
||||
if m.passtoken.value != "" {
|
||||
newtokens = append(newtokens, m.passtoken)
|
||||
}
|
||||
if m.accounttoken.value != "" {
|
||||
newtokens = append(newtokens, m.accounttoken)
|
||||
}
|
||||
for i := range n.tokens {
|
||||
if n.tokens[i].kind == tkDefault {
|
||||
// found the default, now insert tokens before it
|
||||
n.tokens = append(n.tokens[:i], append(newtokens, n.tokens[i:]...)...)
|
||||
return
|
||||
}
|
||||
}
|
||||
// didn't find a default, just add the newtokens to the end
|
||||
n.tokens = append(n.tokens, newtokens...)
|
||||
return
|
||||
}
|
||||
|
||||
func (n *Netrc) RemoveMachine(name string) {
|
||||
n.updateLock.Lock()
|
||||
defer n.updateLock.Unlock()
|
||||
|
||||
for i := range n.machines {
|
||||
if n.machines[i] != nil && n.machines[i].Name == name {
|
||||
m := n.machines[i]
|
||||
for _, t := range []*token{
|
||||
m.nametoken, m.logintoken, m.passtoken, m.accounttoken,
|
||||
} {
|
||||
n.removeToken(t)
|
||||
}
|
||||
n.machines = append(n.machines[:i], n.machines[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Netrc) removeToken(t *token) {
|
||||
if t != nil {
|
||||
for i := range n.tokens {
|
||||
if n.tokens[i] == t {
|
||||
n.tokens = append(n.tokens[:i], n.tokens[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Machine contains information about a remote machine.
|
||||
type Machine struct {
|
||||
Name string
|
||||
Login string
|
||||
Password string
|
||||
Account string
|
||||
|
||||
nametoken *token
|
||||
logintoken *token
|
||||
passtoken *token
|
||||
accounttoken *token
|
||||
}
|
||||
|
||||
// IsDefault returns true if the machine is a "default" token, denoted by an
|
||||
// empty name.
|
||||
func (m *Machine) IsDefault() bool {
|
||||
return m.Name == ""
|
||||
}
|
||||
|
||||
// UpdatePassword sets the password for the Machine m.
|
||||
func (m *Machine) UpdatePassword(newpass string) {
|
||||
m.Password = newpass
|
||||
updateTokenValue(m.passtoken, newpass)
|
||||
}
|
||||
|
||||
// UpdateLogin sets the login for the Machine m.
|
||||
func (m *Machine) UpdateLogin(newlogin string) {
|
||||
m.Login = newlogin
|
||||
updateTokenValue(m.logintoken, newlogin)
|
||||
}
|
||||
|
||||
// UpdateAccount sets the login for the Machine m.
|
||||
func (m *Machine) UpdateAccount(newaccount string) {
|
||||
m.Account = newaccount
|
||||
updateTokenValue(m.accounttoken, newaccount)
|
||||
}
|
||||
|
||||
func updateTokenValue(t *token, value string) {
|
||||
oldvalue := t.value
|
||||
t.value = value
|
||||
newraw := make([]byte, len(t.rawvalue))
|
||||
copy(newraw, t.rawvalue)
|
||||
t.rawvalue = append(
|
||||
bytes.TrimSuffix(newraw, []byte(oldvalue)),
|
||||
[]byte(value)...,
|
||||
)
|
||||
}
|
||||
|
||||
// Macros contains all the macro definitions in a netrc file.
|
||||
type Macros map[string]string
|
||||
|
||||
type token struct {
|
||||
kind tkType
|
||||
macroName string
|
||||
value string
|
||||
rawkind []byte
|
||||
rawvalue []byte
|
||||
}
|
||||
|
||||
// Error represents a netrc file parse error.
|
||||
type Error struct {
|
||||
LineNum int // Line number
|
||||
Msg string // Error message
|
||||
}
|
||||
|
||||
// Error returns a string representation of error e.
|
||||
func (e *Error) Error() string {
|
||||
return fmt.Sprintf("line %d: %s", e.LineNum, e.Msg)
|
||||
}
|
||||
|
||||
func (e *Error) BadDefaultOrder() bool {
|
||||
return e.Msg == errBadDefaultOrder
|
||||
}
|
||||
|
||||
const errBadDefaultOrder = "default token must appear after all machine tokens"
|
||||
|
||||
// scanLinesKeepPrefix is a split function for a Scanner that returns each line
|
||||
// of text. The returned token may include newlines if they are before the
|
||||
// first non-space character. The returned line may be empty. The end-of-line
|
||||
// marker is one optional carriage return followed by one mandatory newline. In
|
||||
// regular expression notation, it is `\r?\n`. The last non-empty line of
|
||||
// input will be returned even if it has no newline.
|
||||
func scanLinesKeepPrefix(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||
if atEOF && len(data) == 0 {
|
||||
return 0, nil, nil
|
||||
}
|
||||
// Skip leading spaces.
|
||||
start := 0
|
||||
for width := 0; start < len(data); start += width {
|
||||
var r rune
|
||||
r, width = utf8.DecodeRune(data[start:])
|
||||
if !unicode.IsSpace(r) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if i := bytes.IndexByte(data[start:], '\n'); i >= 0 {
|
||||
// We have a full newline-terminated line.
|
||||
return start + i, data[0 : start+i], nil
|
||||
}
|
||||
// If we're at EOF, we have a final, non-terminated line. Return it.
|
||||
if atEOF {
|
||||
return len(data), data, nil
|
||||
}
|
||||
// Request more data.
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
// scanWordsKeepPrefix is a split function for a Scanner that returns each
|
||||
// space-separated word of text, with prefixing spaces included. It will never
|
||||
// return an empty string. The definition of space is set by unicode.IsSpace.
|
||||
//
|
||||
// Adapted from bufio.ScanWords().
|
||||
func scanTokensKeepPrefix(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||
// Skip leading spaces.
|
||||
start := 0
|
||||
for width := 0; start < len(data); start += width {
|
||||
var r rune
|
||||
r, width = utf8.DecodeRune(data[start:])
|
||||
if !unicode.IsSpace(r) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if atEOF && len(data) == 0 || start == len(data) {
|
||||
return len(data), data, nil
|
||||
}
|
||||
if len(data) > start && data[start] == '#' {
|
||||
return scanLinesKeepPrefix(data, atEOF)
|
||||
}
|
||||
// Scan until space, marking end of word.
|
||||
for width, i := 0, start; i < len(data); i += width {
|
||||
var r rune
|
||||
r, width = utf8.DecodeRune(data[i:])
|
||||
if unicode.IsSpace(r) {
|
||||
return i, data[:i], nil
|
||||
}
|
||||
}
|
||||
// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
|
||||
if atEOF && len(data) > start {
|
||||
return len(data), data, nil
|
||||
}
|
||||
// Request more data.
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func newToken(rawb []byte) (*token, error) {
|
||||
_, tkind, err := bufio.ScanWords(rawb, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ok bool
|
||||
t := token{rawkind: rawb}
|
||||
t.kind, ok = keywords[string(tkind)]
|
||||
if !ok {
|
||||
trimmed := strings.TrimSpace(string(tkind))
|
||||
if trimmed == "" {
|
||||
t.kind = tkWhitespace // whitespace-only, should happen only at EOF
|
||||
return &t, nil
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "#") {
|
||||
t.kind = tkComment // this is a comment
|
||||
return &t, nil
|
||||
}
|
||||
return &t, fmt.Errorf("keyword expected; got " + string(tkind))
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func scanValue(scanner *bufio.Scanner, pos int) ([]byte, string, int, error) {
|
||||
if scanner.Scan() {
|
||||
raw := scanner.Bytes()
|
||||
pos += bytes.Count(raw, []byte{'\n'})
|
||||
return raw, strings.TrimSpace(string(raw)), pos, nil
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, "", pos, &Error{pos, err.Error()}
|
||||
}
|
||||
return nil, "", pos, nil
|
||||
}
|
||||
|
||||
func parse(r io.Reader, pos int) (*Netrc, error) {
|
||||
b, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nrc := Netrc{machines: make([]*Machine, 0, 20), macros: make(Macros, 10)}
|
||||
|
||||
defaultSeen := false
|
||||
var currentMacro *token
|
||||
var m *Machine
|
||||
var t *token
|
||||
scanner := bufio.NewScanner(bytes.NewReader(b))
|
||||
scanner.Split(scanTokensKeepPrefix)
|
||||
|
||||
for scanner.Scan() {
|
||||
rawb := scanner.Bytes()
|
||||
if len(rawb) == 0 {
|
||||
break
|
||||
}
|
||||
pos += bytes.Count(rawb, []byte{'\n'})
|
||||
t, err = newToken(rawb)
|
||||
if err != nil {
|
||||
if currentMacro == nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
currentMacro.rawvalue = append(currentMacro.rawvalue, rawb...)
|
||||
continue
|
||||
}
|
||||
|
||||
if currentMacro != nil && bytes.Contains(rawb, []byte{'\n', '\n'}) {
|
||||
// if macro rawvalue + rawb would contain \n\n, then macro def is over
|
||||
currentMacro.value = strings.TrimLeft(string(currentMacro.rawvalue), "\r\n")
|
||||
nrc.macros[currentMacro.macroName] = currentMacro.value
|
||||
currentMacro = nil
|
||||
}
|
||||
|
||||
switch t.kind {
|
||||
case tkMacdef:
|
||||
if _, t.macroName, pos, err = scanValue(scanner, pos); err != nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
currentMacro = t
|
||||
case tkDefault:
|
||||
if defaultSeen {
|
||||
return nil, &Error{pos, "multiple default token"}
|
||||
}
|
||||
if m != nil {
|
||||
nrc.machines, m = append(nrc.machines, m), nil
|
||||
}
|
||||
m = new(Machine)
|
||||
m.Name = ""
|
||||
defaultSeen = true
|
||||
case tkMachine:
|
||||
if defaultSeen {
|
||||
return nil, &Error{pos, errBadDefaultOrder}
|
||||
}
|
||||
if m != nil {
|
||||
nrc.machines, m = append(nrc.machines, m), nil
|
||||
}
|
||||
m = new(Machine)
|
||||
if t.rawvalue, m.Name, pos, err = scanValue(scanner, pos); err != nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
t.value = m.Name
|
||||
m.nametoken = t
|
||||
case tkLogin:
|
||||
if m == nil || m.Login != "" {
|
||||
return nil, &Error{pos, "unexpected token login "}
|
||||
}
|
||||
if t.rawvalue, m.Login, pos, err = scanValue(scanner, pos); err != nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
t.value = m.Login
|
||||
m.logintoken = t
|
||||
case tkPassword:
|
||||
if m == nil || m.Password != "" {
|
||||
return nil, &Error{pos, "unexpected token password"}
|
||||
}
|
||||
if t.rawvalue, m.Password, pos, err = scanValue(scanner, pos); err != nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
t.value = m.Password
|
||||
m.passtoken = t
|
||||
case tkAccount:
|
||||
if m == nil || m.Account != "" {
|
||||
return nil, &Error{pos, "unexpected token account"}
|
||||
}
|
||||
if t.rawvalue, m.Account, pos, err = scanValue(scanner, pos); err != nil {
|
||||
return nil, &Error{pos, err.Error()}
|
||||
}
|
||||
t.value = m.Account
|
||||
m.accounttoken = t
|
||||
}
|
||||
|
||||
nrc.tokens = append(nrc.tokens, t)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if m != nil {
|
||||
nrc.machines, m = append(nrc.machines, m), nil
|
||||
}
|
||||
return &nrc, nil
|
||||
}
|
||||
|
||||
// ParseFile opens the file at filename and then passes its io.Reader to
|
||||
// Parse().
|
||||
func ParseFile(filename string) (*Netrc, error) {
|
||||
fd, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fd.Close()
|
||||
return Parse(fd)
|
||||
}
|
||||
|
||||
// Parse parses from the the Reader r as a netrc file and returns the set of
|
||||
// machine information and macros defined in it. The ``default'' machine,
|
||||
// which is intended to be used when no machine name matches, is identified
|
||||
// by an empty machine name. There can be only one ``default'' machine.
|
||||
//
|
||||
// If there is a parsing error, an Error is returned.
|
||||
func Parse(r io.Reader) (*Netrc, error) {
|
||||
return parse(r, 1)
|
||||
}
|
||||
|
||||
// FindMachine parses the netrc file identified by filename and returns the
|
||||
// Machine named by name. If a problem occurs parsing the file at filename, an
|
||||
// error is returned. If a machine named by name exists, it is returned. If no
|
||||
// Machine with name name is found and there is a ``default'' machine, the
|
||||
// ``default'' machine is returned. Otherwise, nil is returned.
|
||||
func FindMachine(filename, name string) (m *Machine, err error) {
|
||||
n, err := ParseFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n.FindMachine(name), nil
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
example/example
|
||||
example/example.exe
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Blake Gentry
|
||||
|
||||
This license applies to the non-Windows portions of this library. The Windows
|
||||
portion maintains its own Apache 2.0 license.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
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
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [2013] [the CloudFoundry Authors]
|
||||
|
||||
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.
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# Speakeasy
|
||||
|
||||
This package provides cross-platform Go (#golang) helpers for taking user input
|
||||
from the terminal while not echoing the input back (similar to `getpasswd`). The
|
||||
package uses syscalls to avoid any dependence on cgo, and is therefore
|
||||
compatible with cross-compiling.
|
||||
|
||||
[][godoc]
|
||||
|
||||
## Unicode
|
||||
|
||||
Multi-byte unicode characters work successfully on Mac OS X. On Windows,
|
||||
however, this may be problematic (as is UTF in general on Windows). Other
|
||||
platforms have not been tested.
|
||||
|
||||
## License
|
||||
|
||||
The code herein was not written by me, but was compiled from two separate open
|
||||
source packages. Unix portions were imported from [gopass][gopass], while
|
||||
Windows portions were imported from the [CloudFoundry Go CLI][cf-cli]'s
|
||||
[Windows terminal helpers][cf-ui-windows].
|
||||
|
||||
The [license for the windows portion](./LICENSE_WINDOWS) has been copied exactly
|
||||
from the source (though I attempted to fill in the correct owner in the
|
||||
boilerplate copyright notice).
|
||||
|
||||
[cf-cli]: https://github.com/cloudfoundry/cli "CloudFoundry Go CLI"
|
||||
[cf-ui-windows]: https://github.com/cloudfoundry/cli/blob/master/src/cf/terminal/ui_windows.go "CloudFoundry Go CLI Windows input helpers"
|
||||
[godoc]: https://godoc.org/github.com/bgentry/speakeasy "speakeasy on Godoc.org"
|
||||
[gopass]: https://code.google.com/p/gopass "gopass"
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package speakeasy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Ask the user to enter a password with input hidden. prompt is a string to
|
||||
// display before the user's input. Returns the provided password, or an error
|
||||
// if the command failed.
|
||||
func Ask(prompt string) (password string, err error) {
|
||||
return FAsk(os.Stdout, prompt)
|
||||
}
|
||||
|
||||
// FAsk is the same as Ask, except it is possible to specify the file to write
|
||||
// the prompt to. If 'nil' is passed as the writer, no prompt will be written.
|
||||
func FAsk(wr io.Writer, prompt string) (password string, err error) {
|
||||
if wr != nil && prompt != "" {
|
||||
fmt.Fprint(wr, prompt) // Display the prompt.
|
||||
}
|
||||
password, err = getPassword()
|
||||
|
||||
// Carriage return after the user input.
|
||||
if wr != nil {
|
||||
fmt.Fprintln(wr, "")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func readline() (value string, err error) {
|
||||
var valb []byte
|
||||
var n int
|
||||
b := make([]byte, 1)
|
||||
for {
|
||||
// read one byte at a time so we don't accidentally read extra bytes
|
||||
n, err = os.Stdin.Read(b)
|
||||
if err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
if n == 0 || b[0] == '\n' {
|
||||
break
|
||||
}
|
||||
valb = append(valb, b[0])
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(string(valb), "\r"), nil
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
// based on https://code.google.com/p/gopass
|
||||
// Author: johnsiilver@gmail.com (John Doak)
|
||||
//
|
||||
// Original code is based on code by RogerV in the golang-nuts thread:
|
||||
// https://groups.google.com/group/golang-nuts/browse_thread/thread/40cc41e9d9fc9247
|
||||
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
||||
|
||||
package speakeasy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const sttyArg0 = "/bin/stty"
|
||||
|
||||
var (
|
||||
sttyArgvEOff = []string{"stty", "-echo"}
|
||||
sttyArgvEOn = []string{"stty", "echo"}
|
||||
)
|
||||
|
||||
// getPassword gets input hidden from the terminal from a user. This is
|
||||
// accomplished by turning off terminal echo, reading input from the user and
|
||||
// finally turning on terminal echo.
|
||||
func getPassword() (password string, err error) {
|
||||
sig := make(chan os.Signal, 10)
|
||||
brk := make(chan bool)
|
||||
|
||||
// File descriptors for stdin, stdout, and stderr.
|
||||
fd := []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()}
|
||||
|
||||
// Setup notifications of termination signals to channel sig, create a process to
|
||||
// watch for these signals so we can turn back on echo if need be.
|
||||
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT,
|
||||
syscall.SIGTERM)
|
||||
go catchSignal(fd, sig, brk)
|
||||
|
||||
// Turn off the terminal echo.
|
||||
pid, err := echoOff(fd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Turn on the terminal echo and stop listening for signals.
|
||||
defer signal.Stop(sig)
|
||||
defer close(brk)
|
||||
defer echoOn(fd)
|
||||
|
||||
syscall.Wait4(pid, nil, 0, nil)
|
||||
|
||||
line, err := readline()
|
||||
if err == nil {
|
||||
password = strings.TrimSpace(line)
|
||||
} else {
|
||||
err = fmt.Errorf("failed during password entry: %s", err)
|
||||
}
|
||||
|
||||
return password, err
|
||||
}
|
||||
|
||||
// echoOff turns off the terminal echo.
|
||||
func echoOff(fd []uintptr) (int, error) {
|
||||
pid, err := syscall.ForkExec(sttyArg0, sttyArgvEOff, &syscall.ProcAttr{Dir: "", Files: fd})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed turning off console echo for password entry:\n\t%s", err)
|
||||
}
|
||||
return pid, nil
|
||||
}
|
||||
|
||||
// echoOn turns back on the terminal echo.
|
||||
func echoOn(fd []uintptr) {
|
||||
// Turn on the terminal echo.
|
||||
pid, e := syscall.ForkExec(sttyArg0, sttyArgvEOn, &syscall.ProcAttr{Dir: "", Files: fd})
|
||||
if e == nil {
|
||||
syscall.Wait4(pid, nil, 0, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// catchSignal tries to catch SIGKILL, SIGQUIT and SIGINT so that we can turn
|
||||
// terminal echo back on before the program ends. Otherwise the user is left
|
||||
// with echo off on their terminal.
|
||||
func catchSignal(fd []uintptr, sig chan os.Signal, brk chan bool) {
|
||||
select {
|
||||
case <-sig:
|
||||
echoOn(fd)
|
||||
os.Exit(-1)
|
||||
case <-brk:
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
// +build windows
|
||||
|
||||
package speakeasy
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// SetConsoleMode function can be used to change value of ENABLE_ECHO_INPUT:
|
||||
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx
|
||||
const ENABLE_ECHO_INPUT = 0x0004
|
||||
|
||||
func getPassword() (password string, err error) {
|
||||
var oldMode uint32
|
||||
|
||||
err = syscall.GetConsoleMode(syscall.Stdin, &oldMode)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var newMode uint32 = (oldMode &^ ENABLE_ECHO_INPUT)
|
||||
|
||||
err = setConsoleMode(syscall.Stdin, newMode)
|
||||
defer setConsoleMode(syscall.Stdin, oldMode)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return readline()
|
||||
}
|
||||
|
||||
func setConsoleMode(console syscall.Handle, mode uint32) (err error) {
|
||||
dll := syscall.MustLoadDLL("kernel32")
|
||||
proc := dll.MustFindProc("SetConsoleMode")
|
||||
r, _, err := proc.Call(uintptr(console), uintptr(mode))
|
||||
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user