-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.go
311 lines (280 loc) · 7.54 KB
/
tunnel.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"github.com/kardianos/osext"
"github.com/mkideal/cli"
)
// Blazon contains methods to publish final output
type Blazon struct {
response http.ResponseWriter
request *http.Request
callback string
}
func (b Blazon) wrapper(content string) {
if corsEnabled {
b.response.Header().Set("Access-Control-Allow-Origin", b.request.Header.Get("Origin"))
b.response.Header().Set("Vary", "Origin")
b.response.Header().Set("Access-Control-Allow-Credentials", "true")
b.response.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE")
b.response.Header().Set("Access-Control-Max-Age", "3600")
b.response.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, X-Requested-With, remember-me")
}
if b.callback != "" {
b.response.Header().Set("Content-Type", "text/javascript")
jsonp := b.callback + "(" + content + ")"
b.response.Write([]byte(jsonp))
} else {
b.response.Header().Set("Content-Type", "application/json")
b.response.Write([]byte(content))
}
}
func (b Blazon) publish(response string) string {
dix, _ := json.Marshal(map[string]string{
"status": "success",
"response": response})
return string(dix)
}
func (b Blazon) trouble(response string) string {
dix, _ := json.Marshal(map[string]string{
"status": "failure",
"response": response})
return string(dix)
}
// Console contains terminal input and output handlers.
type Console struct {
}
func (c Console) getCommand(cmd *exec.Cmd) string {
return strings.Join(cmd.Args, " ")
}
func (c Console) getError(err error) string {
if err != nil {
return string(err.Error())
}
return ""
}
func (c Console) getOutput(outs []byte) string {
if len(outs) > 0 {
return string(outs)
}
return ""
}
func (c Console) process(input string) string {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("bash", "-c", input)
case "windows":
cmd = exec.Command("cmd", "/C", input)
default:
cmd = exec.Command(input)
}
output, err := cmd.CombinedOutput()
dix := map[string]string{
"cmd": c.getCommand(cmd),
"err": c.getError(err),
"out": c.getOutput(output)}
dixMap, _ := json.Marshal(dix)
return string(dixMap)
}
// WebService contains browser specific commands.
type WebService struct{}
func (ws WebService) handShake(w http.ResponseWriter, r *http.Request) {
qp := r.URL.Query()
callback := qp.Get("callback")
blazon := Blazon{w, r, callback}
dix := map[string]string{
"tunnel": "alive"}
output, _ := json.Marshal(dix)
blazon.wrapper(blazon.publish(string(output)))
}
func (ws WebService) authenticate(w http.ResponseWriter, r *http.Request) {
qp := r.URL.Query()
callback := qp.Get("callback")
blazon := Blazon{w, r, callback}
baUser, baPass, baAuth := r.BasicAuth()
if baAuth {
if userId == baUser && userPw == baPass {
dix := map[string]string{
"user": "authorized"}
output, _ := json.Marshal(dix)
blazon.wrapper(blazon.publish(string(output)))
} else {
blazon.wrapper(blazon.trouble("Credentials are invalid"))
}
} else {
blazon.wrapper(blazon.trouble("Authorization header is missing"))
}
}
// curl -d "token=value&cmd=ls" -X POST http://localhost:9999/terminal
func (ws WebService) terminal(w http.ResponseWriter, r *http.Request) {
qp := r.URL.Query()
callback := qp.Get("callback")
blazon := Blazon{w, r, callback}
baUser, baPass, baAuth := r.BasicAuth()
if baAuth {
if userId == baUser && userPw == baPass {
konsole := Console{}
nextStep := false
command := ""
if callback != "" {
command = qp.Get("cmd")
nextStep = true
} else {
err := r.ParseForm()
if err != nil {
blazon.wrapper(blazon.trouble(string(err.Error())))
} else {
command = r.PostFormValue("cmd")
nextStep = true
}
}
if nextStep {
if command != "" {
output := konsole.process(command)
blazon.wrapper(blazon.publish(output))
} else {
blazon.wrapper(blazon.trouble("Command is missing"))
}
}
} else {
blazon.wrapper(blazon.trouble("Credentials are invalid"))
}
} else {
blazon.wrapper(blazon.trouble("Authorization header is missing"))
}
}
// Server is an application server
type Server struct {
docRoot string
url string
}
func (s Server) waitServer() bool {
tries := 20
for tries > 0 {
resp, err := http.Get(s.url)
if err == nil {
resp.Body.Close()
return true
}
time.Sleep(100 * time.Millisecond)
tries--
}
return false
}
func (s Server) startBrowser() bool {
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], s.url)...)
return cmd.Start() == nil
}
func (s Server) probeDocRoot() string {
serverRoot, err := osext.ExecutableFolder()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if appRoot == true {
s.docRoot = serverRoot
if docPath != "" {
s.docRoot += docPath
}
} else {
if docPath != "" {
s.docRoot = docPath
} else {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
s.docRoot = pwd
}
}
return s.docRoot
}
func (s Server) initialize() {
httpAddr := hostIP + ":" + strconv.Itoa(portNum)
s.url = "http://" + httpAddr
s.docRoot = s.probeDocRoot()
timestamp := time.Now()
fmt.Println(appName, "configuration \n Root \t", s.docRoot, "\n URL \t", s.url, "\n Time \t", timestamp.Format(time.RFC1123), "\n")
go func() {
fmt.Println(appName, "status: STARTED")
if s.waitServer() && openBrowser && s.startBrowser() {
fmt.Println("A browser window should open. If not, visit the link.")
} else {
fmt.Println("Please open your web browser and visit the link.")
}
fmt.Println("Please hit 'ctrl + C' to STOP the server.")
}()
ws := WebService{}
if docPath != "" {
http.Handle("/", http.FileServer(http.Dir(s.docRoot)))
} else {
http.HandleFunc("/", ws.handShake)
}
http.HandleFunc("/authenticate", ws.authenticate)
http.HandleFunc("/terminal", ws.terminal)
http.ListenAndServe(httpAddr, nil)
}
var (
appName = "Tunnel"
version = "2.0.1"
docPath = ""
hostIP = "127.0.0.1"
portNum = 9999
appRoot = false
openBrowser = false
corsEnabled = true
userId = "admin"
userPw = "123456"
)
type argT struct {
cli.Helper
Port int `cli:"p,port" usage:"set custom port number" dft:"9999"`
Host string `cli:"u,host" usage:"set host IP or server address" dft:"127.0.0.1"`
DocPath string `cli:"d,docpath" usage:"set document directory's path" dft:""`
Browser bool `cli:"b,browser" usage:"open browser on server start" dft:"false"`
AppRoot bool `cli:"a,approot" usage:"serve from application's root" dft:"false"`
Cors bool `cli:"x,cors" usage:"allows cross domain requests" dft:"false"`
User string `cli:"i,user" usage:"username of account" dft:"admin"`
Pass string `cli:"c,pass" usage:"password of account" dft:"123456"`
}
func main() {
today := time.Now()
fmt.Printf("\n%s (Version %s) \nCopyright (c) 2017-%s Abhishek Kumar. \nLicensed under MIT License. \n\n", appName, version, strconv.Itoa(today.Year()))
mode := false
cli.Run(new(argT), func(ctx *cli.Context) error {
argv := ctx.Argv().(*argT)
docPath = argv.DocPath
hostIP = argv.Host
portNum = argv.Port
openBrowser = argv.Browser
appRoot = argv.AppRoot
corsEnabled = argv.Cors
userId = argv.User
userPw = argv.Pass
mode = true
return nil
})
if mode {
server := Server{}
server.initialize()
}
fmt.Println("\nDone!\n")
}