-
Notifications
You must be signed in to change notification settings - Fork 2
/
httplistener.go
242 lines (208 loc) · 6.14 KB
/
httplistener.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"github.com/jaracil/ei"
. "github.com/jaracil/nexus/log"
"github.com/sirupsen/logrus"
"github.com/tylerb/graceful"
"golang.org/x/net/context"
"golang.org/x/net/websocket"
)
type httpwsHandler struct{}
func (*httpwsHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
Log.WithFields(logrus.Fields{
"remote": req.RemoteAddr,
}).Warn("Unencrypted connection!!")
}
if headerContains(req.Header["Connection"], "upgrade") {
if headerContains(req.Header["Upgrade"], "websocket") {
// WebSocket
wsrv := &websocket.Server{}
wsrv.Handler = func(ws *websocket.Conn) {
nc := NewNexusConn(ws)
if req.TLS != nil {
nc.proto = "wss"
} else {
nc.proto = "ws"
}
ws.Config().Origin = &url.URL{Scheme: nc.proto, Host: req.RemoteAddr}
Log.WithFields(logrus.Fields{
"remote": ws.RemoteAddr().String(),
"origin": req.Header.Get("Origin"),
}).Infoln("New WebSocket connection")
nc.handle()
}
if wsrv.Header == nil {
wsrv.Header = make(map[string][]string)
}
wsrv.Header["Access-Control-Allow-Origin"] = []string{"*"}
wsrv.ServeHTTP(res, req)
} else {
Log.WithFields(logrus.Fields{
"unsupported": req.Header["Upgrade"],
}).Warn("Connection dropped for requesting an upgrade to an unsupported protocol")
res.WriteHeader(http.StatusBadRequest)
}
} else {
// HTTP Bridge
// CORS pre-flight headers
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Header().Set("Access-Control-Allow-Methods", "POST, GET")
res.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization")
switch req.Method {
case "POST", "GET":
// continue
default:
return
}
netCli, netSrv := net.Pipe()
netCliBuf := bufio.NewReaderSize(netCli, opts.MaxMessageSize)
ns := NewNexusConn(netSrv)
if req.TLS != nil {
ns.proto = "https"
} else {
ns.proto = "http"
}
defer ns.close()
defer netCli.Close()
Log.WithFields(logrus.Fields{
"remote": req.RemoteAddr,
}).Infoln("New HTTP connection")
go ns.handle()
if user, pass, loginData := req.BasicAuth(); loginData {
fmt.Fprintf(netCli, `{"jsonrpc":"2.0", "id":1, "method":"sys.login", "params":{"user":"%s", "pass":"%s"}}`, user, pass)
resSlice, _, err := netCliBuf.ReadLine()
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Error reading login response [%s]"}}`, err.Error())))
return
}
loginRes := ei.M{}
if err := json.Unmarshal(resSlice, &loginRes); err != nil {
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Error unmarshaling login response [%s]"}}`, err.Error())))
return
}
if ei.N(loginRes).M("id").IntZ() != 1 {
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Error on login response id"}}`)))
return
}
if !ei.N(loginRes).M("result").M("ok").BoolZ() {
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write([]byte(`{"jsonrpc":"2.0","id":1,"error":{"code":-32010,"message":"Permission denied [login fail]"}}`))
return
}
}
if _, err := io.Copy(netCli, req.Body); err != nil {
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Error sending body request [%s]"}}`, err.Error())))
return
}
if resSlice, err := netCliBuf.ReadBytes('\n'); err == nil {
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(resSlice)
} else {
res.WriteHeader(http.StatusInternalServerError)
res.Write([]byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Error reading request response [%s]"}}`, err.Error())))
}
}
}
func httpListener(u *url.URL, ctx context.Context) {
defer Log.WithFields(logrus.Fields{
"listener": u,
}).Warnln("HTTP listener finished")
server := graceful.Server{
Server: &http.Server{Addr: u.Host, Handler: http.Handler(&httpwsHandler{})},
Timeout: 0,
}
go func() {
select {
case <-ctx.Done():
server.Stop(0)
}
}()
Log.WithFields(logrus.Fields{
"address": u.String(),
}).Infoln("New HTTP listener started")
err := server.ListenAndServe()
if ctx.Err() != nil {
return
}
if err != nil {
Log.WithFields(logrus.Fields{
"error": err.Error(),
}).Errorln("HTTP listener error")
exit("http listener goroutine error")
return
}
}
func httpsListener(u *url.URL, ctx context.Context) {
defer Log.WithFields(logrus.Fields{
"listener": u,
}).Warnln("HTTPS listener finished")
server := graceful.Server{
Server: &http.Server{Addr: u.Host, Handler: http.Handler(&httpwsHandler{})},
Timeout: 0,
}
go func() {
select {
case <-ctx.Done():
server.Stop(0)
}
}()
Log.WithFields(logrus.Fields{
"address": u.String(),
}).Infoln("New HTTPS listener started")
err := server.ListenAndServeTLS(opts.SSL.Cert, opts.SSL.Key)
if ctx.Err() != nil {
return
}
if err != nil {
Log.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("HTTPS listener error")
exit("https listener goroutine error")
return
}
}
func healthCheckListener(u *url.URL, ctx context.Context) {
defer Log.WithFields(logrus.Fields{
"listener": u,
}).Warnln("Health listener finished")
server := graceful.Server{
Server: &http.Server{Addr: u.Host, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
})},
Timeout: 0,
}
go func() {
select {
case <-ctx.Done():
server.Stop(0)
}
}()
Log.WithFields(logrus.Fields{
"address": u.String(),
}).Infoln("New health listener started")
err := server.ListenAndServe()
if ctx.Err() != nil {
return
}
if err != nil {
Log.WithFields(logrus.Fields{
"error": err.Error(),
}).Errorln("HealthCheck listener error")
exit("healthCheck listener goroutine error")
return
}
}