/
client.go
293 lines (256 loc) · 7.05 KB
/
client.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
package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"fmt"
"github.com/antonholmquist/jason"
"github.com/julienschmidt/httprouter"
"io/ioutil"
"math"
"math/rand"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// Client methods (one per "slave", communicates with the server)
type Client struct {
Id string
Hostname string
AuthToken string
ConnectedServerInstanceId string // ID of the server to which it is connected
mux sync.RWMutex
}
// Start client
func (s *Client) Start() bool {
log.Printf("Starting client %s from seed %s with tags %v", s.Id, conf.EndpointURI, conf.GetTags())
// Ping server to register
s.PingServer()
// Get auth token from server
s.AuthServer()
// Is the client enabled?
if conf.isClientEnabled() {
// Start webserver
go func() {
log.Printf("Starting client server %s", s.Id)
router := httprouter.New()
router.GET("/ping", Ping)
log.Printf("Failed to start client server %s %v", s.Id, http.ListenAndServe(fmt.Sprintf(":%d", conf.ClientPort), router))
}()
} else {
if conf.Debug {
log.Printf("Client server of %s disabled", s.Id)
}
}
// Register with server
go func() {
c := time.Tick(time.Duration(CLIENT_PING_INTERVAL) * time.Second)
for _ = range c {
s.PingServer()
// Should we reload auth?
var reloadAuth bool = false
s.mux.RLock()
if len(s.AuthToken) < 1 {
reloadAuth = true
}
s.mux.RUnlock()
if reloadAuth {
s.AuthServer()
}
}
}()
// Long poll commands
go func() {
for {
s.PollCmds()
}
}()
return true
}
// Fetch commands
func (s *Client) PollCmds() {
bytes, err := s._get(fmt.Sprintf("client/%s/cmds", url.QueryEscape(s.Id)))
if err == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
// Re-auth
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
return
}
// List commands
cmds, _ := obj.GetObjectArray("cmds")
for _, cmd := range cmds {
id, _ := cmd.GetString("Id")
command, _ := cmd.GetString("Command")
signature, _ := cmd.GetString("Signature")
templateId, _ := cmd.GetString("TemplateId")
timeout, _ := cmd.GetInt64("Timeout")
cmd := newCmd(command, int(timeout))
cmd.ClientId = client.Id
cmd.TemplateId = templateId
cmd.Id = id
cmd.Signature = signature
cmd.Execute(s)
}
}
} else {
// In case of fast error back off a bit
time.Sleep(1 * time.Second)
}
}
// Auth server, token is used for verifying commands
// @todo This function needs more logging in failure scenarios
func (s *Client) AuthServer() {
b, e := s._req("POST", fmt.Sprintf("client/%s/auth", url.QueryEscape(s.Id)), nil)
if e == nil {
obj, jerr := jason.NewObjectFromBytes(b)
if jerr == nil {
// Get signature
token, et := obj.GetString("token")
if et != nil || len(token) < 1 {
return
}
// Get token signatur
tokenSignature, ets := obj.GetString("token_signature")
if ets != nil || len(tokenSignature) < 1 {
return
}
// Verify token signature with our secure token
hasher := sha256.New()
hasher.Write([]byte(token))
hasher.Write([]byte(conf.Token))
expectedTokenSignature := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
// The same?
if tokenSignature != expectedTokenSignature {
log.Println("ERROR! Token signature from server is invalid, communication between server and client might be tampered with")
return
}
// Store token if it is valid
s.mux.Lock()
s.AuthToken = token
s.mux.Unlock()
log.Printf("Client authenticated with server")
}
}
}
// Ping server
func (s *Client) PingServer() {
bytes, e := s._get(fmt.Sprintf("client/%s/ping?tags=%s&hostname=%s", url.QueryEscape(s.Id), url.QueryEscape(strings.Join(conf.GetTags(), ",")), url.QueryEscape(s.Hostname)))
if e == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
serverInstanceId, _ := obj.GetString("server_instance_id")
// Ping failed, re-authenticate
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
} else {
// Only log a connect if the instance ID changed
if len(s.ConnectedServerInstanceId) == 0 || s.ConnectedServerInstanceId != serverInstanceId {
s.ConnectedServerInstanceId = serverInstanceId
log.Println(fmt.Sprintf("Client registered with server %s", s.ConnectedServerInstanceId))
}
}
}
}
}
// Get
func (s *Client) _get(uri string) ([]byte, error) {
return s._req("GET", uri, make([]byte, 0))
}
// Generic request method with retry handling
func (s *Client) _req(method string, uri string, data []byte) ([]byte, error) {
var bytes []byte = nil
var err error = nil
for i := 0; i < 10; i++ {
bytes, err = s._reqUnsafe(method, uri, data)
if err == nil && bytes != nil && len(bytes) > 0 {
return bytes, err
}
// Sleep a bit before the retry and apply ~25ms jitter
var sleep float64 = 25 + float64(rand.Intn(50)) + (math.Pow(float64(i), 2) * 10000)
time.Sleep(time.Duration(sleep) * time.Millisecond)
}
if err != nil {
log.Printf("Failed request after retries to %s with error: %s", uri, err)
}
return bytes, err
}
// Generic request method
func (s *Client) _reqUnsafe(method string, uri string, data []byte) ([]byte, error) {
// Transport
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
}, // Ignore certificate as this is self generated and invalid
}
// For some reasons connections were not closed, this helps
defer tr.CloseIdleConnections()
// Client
client := &http.Client{
Transport: tr,
}
// Sanitize urls
uri = fmt.Sprintf("/%s", strings.TrimLeft(uri, "/"))
// Append random string to uri
var randStr, _ = secureRandomString(32)
if !strings.Contains(uri, "?") {
uri = fmt.Sprintf("%s?_rand=%s", uri, randStr)
} else {
uri = fmt.Sprintf("%s&_rand=%s", uri, randStr)
}
url := conf.ServerRequest(uri)
// Log
if conf.Debug {
log.Printf("%s %s (req bytes %d)", method, url, len(data))
}
// Req
var buf *bytes.Buffer
if data != nil && len(data) > 0 {
buf = bytes.NewBuffer(data)
} else {
buf = bytes.NewBuffer(make([]byte, 0))
}
req, reqErr := http.NewRequest(method, url, buf)
if reqErr != nil {
return nil, reqErr
}
// Signed token
hasher := sha256.New()
hasher.Write([]byte(uri))
hasher.Write([]byte(conf.Token))
signedToken := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
// Auth token
req.Header.Add("X-Auth", signedToken)
if conf.Debug {
log.Println("Sending X-Auth: " + signedToken)
}
// Execute
resp, respErr := client.Do(req)
if respErr != nil {
return nil, respErr
}
// Read body
defer resp.Body.Close()
body, bodyErr := ioutil.ReadAll(resp.Body)
if bodyErr != nil {
return nil, bodyErr
}
return body, nil
}
// Create new client
func newClient() *Client {
return &Client{
Id: conf.Hostname,
Hostname: conf.Hostname,
}
}