-
Notifications
You must be signed in to change notification settings - Fork 288
/
terminal.go
204 lines (188 loc) · 5.13 KB
/
terminal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// terminal
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"github.com/decred/dcrd/dcrjson"
"golang.org/x/crypto/ssh/terminal"
)
func execute(quit chan bool, protected *bool, cfg *config, line string) {
switch line {
case "h":
fallthrough
case "help":
fmt.Printf("[h]elp print this message\n")
fmt.Printf("[l]ist list all available commands\n")
fmt.Printf("[p]rotect toggle protected mode (for passwords)\n")
fmt.Printf("[q]uit/ctrl+d exit\n")
fmt.Printf("Enter commands with arguments to execute them.\n")
case "l":
fallthrough
case "list":
listCommands()
case "q":
fallthrough
case "quit":
quit <- true
case "p":
fallthrough
case "protect":
if *protected {
*protected = false
return
}
*protected = true
return
default:
args := strings.Split(line, " ")
if len(args) < 1 {
usage("No command specified")
return
}
// Ensure the specified method identifies a valid registered command and
// is one of the usable types.
listCmdMessageLocal := "Enter [l]ist to list commands"
method := args[0]
usageFlags, err := dcrjson.MethodUsageFlags(method)
if err != nil {
fmt.Fprintf(os.Stderr, "Unrecognized command '%s'\n", method)
fmt.Fprintln(os.Stderr, listCmdMessageLocal)
return
}
if usageFlags&unusableFlags != 0 {
fmt.Fprintf(os.Stderr, "The '%s' command can only be used via "+
"websockets\n", method)
fmt.Fprintln(os.Stderr, listCmdMessageLocal)
return
}
// Convert remaining command line args to a slice of interface values
// to be passed along as parameters to new command creation function.
//
// Since some commands, such as submitblock, can involve data which is
// too large for the Operating System to allow as a normal command line
// parameter, support using '-' as an argument to allow the argument
// to be read from a stdin pipe.
bio := bufio.NewReader(os.Stdin)
params := make([]interface{}, 0, len(args[1:]))
for _, arg := range args[1:] {
if arg == "-" {
param, err := bio.ReadString('\n')
if err != nil && err != io.EOF {
fmt.Fprintf(os.Stderr, "Failed to read data "+
"from stdin: %v\n", err)
return
}
if err == io.EOF && len(param) == 0 {
fmt.Fprintln(os.Stderr, "Not enough lines "+
"provided on stdin")
return
}
param = strings.TrimRight(param, "\r\n")
params = append(params, param)
continue
}
params = append(params, arg)
}
// Attempt to create the appropriate command using the arguments
// provided by the user.
cmd, err := dcrjson.NewCmd(method, params...)
if err != nil {
// Show the error along with its error code when it's a
// dcrjson.Error as it reallistcally will always be since the
// NewCmd function is only supposed to return errors of that
// type.
if jerr, ok := err.(dcrjson.Error); ok {
fmt.Fprintf(os.Stderr, "%s command: %v (code: %s)\n",
method, err, jerr.Code)
commandUsage(method)
return
}
// The error is not a dcrjson.Error and this really should not
// happen. Nevertheless, fallback to just showing the error
// if it should happen due to a bug in the package.
fmt.Fprintf(os.Stderr, "%s command: %v\n", method, err)
commandUsage(method)
return
}
// Marshal the command into a JSON-RPC byte slice in preparation for
// sending it to the RPC server.
marshalledJSON, err := dcrjson.MarshalCmd(1, cmd)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// Send the JSON-RPC request to the server using the user-specified
// connection configuration.
result, err := sendPostRequest(marshalledJSON, cfg)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// Choose how to display the result based on its type.
strResult := string(result)
if strings.HasPrefix(strResult, "{") || strings.HasPrefix(strResult, "[") {
var dst bytes.Buffer
if err := json.Indent(&dst, result, "", " "); err != nil {
fmt.Fprintf(os.Stderr, "Failed to format result: %v",
err)
return
}
fmt.Println(dst.String())
return
} else if strings.HasPrefix(strResult, `"`) {
var str string
if err := json.Unmarshal(result, &str); err != nil {
fmt.Fprintf(os.Stderr, "Failed to unmarshal result: %v",
err)
return
}
fmt.Println(str)
return
} else if strResult != "null" {
fmt.Println(strResult)
}
}
}
func startTerminal(c *config) {
fmt.Printf("Starting terminal mode.\n")
fmt.Printf("Enter h for [h]elp.\n")
fmt.Printf("Enter q for [q]uit.\n")
done := make(chan bool)
initState, err := terminal.GetState(0)
protected := false
if err != nil {
fmt.Printf("error getting terminal state: %v\n", err.Error())
return
}
go func() {
terminal.MakeRaw(int(os.Stdin.Fd()))
n := terminal.NewTerminal(os.Stdin, "> ")
for {
var ln string
var err error
if !protected {
ln, err = n.ReadLine()
if err != nil {
done <- true
}
} else {
ln, err = n.ReadPassword(">*")
if err != nil {
done <- true
}
}
execute(done, &protected, c, ln)
}
}()
select {
case <-done:
fmt.Printf("exiting...\n")
terminal.Restore(0, initState)
close(done)
}
}