-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
464 lines (416 loc) · 10.8 KB
/
Copy pathclient.go
File metadata and controls
464 lines (416 loc) · 10.8 KB
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package ccms
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"iter"
"net"
"net/http"
"unicode"
"github.com/indexdata/ccms/internal/crypto"
"github.com/indexdata/ccms/internal/eout"
"github.com/indexdata/ccms/internal/protocol"
)
// client that connects to a CCMS server
type Client struct {
Host string // server host name
Port string // server port
User string // user name for authentication
Password string // user password
NoTLS bool // disable TLS (insecure)
TLSSkipVerify bool // do not verify server certificate chain and host name (insecure)
}
// response from CCMS server
type Response struct {
resp *jsonResponse
}
// return an initialized response
func NewResponse() *Response {
return &Response{
resp: &jsonResponse{
ErrorIndex: -1,
Results: make([]*jsonResult, 0),
},
}
}
// set error index
func (r *Response) SetError(e int) {
r.resp.ErrorIndex = e
}
// encode the reponse as JSON
func (r *Response) Encode(w http.ResponseWriter) error {
if err := json.NewEncoder(w).Encode(*(r.resp)); err != nil {
return err
}
return nil
}
// return true if an error occurred
func (r *Response) Error() bool {
return r.resp.ErrorIndex != -1
}
// return index of result having an error, or -1 if there was no error
func (r *Response) ErrorIndex() int {
return r.resp.ErrorIndex
}
// return an iterator over results contained in the response
func (r *Response) Results() iter.Seq[Result] {
return func(yield func(Result) bool) {
res := r.resp.Results
for i := range res {
if !yield(Result{
status: res[i].Status,
message: res[i].Message,
fields: res[i].exportFields(),
data: res[i].exportData(),
}) {
return
}
}
}
}
// add a result to the response
func (r *Response) AddResult(result *Result) {
r.resp.Results = append(r.resp.Results, &jsonResult{
Status: result.status,
Message: result.message,
Fields: result.jsonFields(),
Data: result.jsonData(),
})
}
type jsonResponse struct {
ErrorIndex int `json:"errorIndex"` // result index with error, or -1 if no error
Results []*jsonResult `json:"results"` // result for each command
}
// result of a command
type Result struct {
status string // status of command, or "error"
message string // error message
fields []FieldDescription // attribute metadata for query result
data []DataRow // query result data
}
// return an initialized result
func NewResult(status string) *Result {
return &Result{
status: status,
fields: make([]FieldDescription, 0),
data: make([]DataRow, 0),
}
}
// return the result status
func (r *Result) Status() string {
return r.status
}
// return the result message
func (r *Result) Message() string {
return r.message
}
// add a message to this result
func (r *Result) AddMessage(message string) {
r.message = message
}
// return the field metadata in this result
func (r *Result) Fields() []FieldDescription {
return r.fields
}
// add metadata for a field to this result
func (r *Result) AddField(name, dataType string) {
r.fields = append(r.fields, FieldDescription{
name: name,
dataType: dataType,
})
}
// return an iterator over data rows contained in the result
func (r *Result) Data() iter.Seq[DataRow] {
return func(yield func(DataRow) bool) {
data := r.data
for i := range data {
if !yield(DataRow{
values: data[i].values,
}) {
return
}
}
}
}
// add a data row to this result
func (r *Result) AddData(values []any) {
r.data = append(r.data, DataRow{values: values})
}
func (r *Result) jsonFields() []jsonFieldDescription {
fields := make([]jsonFieldDescription, 0)
for i := range r.fields {
fields = append(fields, jsonFieldDescription{
Name: r.fields[i].name,
DataType: r.fields[i].dataType,
})
}
return fields
}
func (r *Result) jsonData() []jsonDataRow {
data := make([]jsonDataRow, 0)
for i := range r.data {
data = append(data, jsonDataRow{
Values: r.data[i].values,
})
}
return data
}
type jsonResult struct {
Status string `json:"status"`
Message string `json:"message,omitempty"`
Fields []jsonFieldDescription `json:"fields,omitempty"`
Data []jsonDataRow `json:"data,omitempty"`
}
func (j *jsonResult) exportFields() []FieldDescription {
fields := make([]FieldDescription, 0)
for i := range j.Fields {
fields = append(fields, FieldDescription{
name: j.Fields[i].Name,
dataType: j.Fields[i].DataType,
})
}
return fields
}
func (j *jsonResult) exportData() []DataRow {
data := make([]DataRow, 0)
for i := range j.Data {
data = append(data, DataRow{values: j.Data[i].Values})
}
return data
}
// metadata for an attribute
type FieldDescription struct {
name string // attribute name
dataType string // data type
}
// return the field name
func (f *FieldDescription) Name() string {
return f.name
}
// return the field data type
func (f *FieldDescription) DataType() string {
return f.dataType
}
type jsonFieldDescription struct {
Name string `json:"name"`
DataType string `json:"type"`
}
// a row of data
type DataRow struct {
values []any // data values
}
//func NewDataRow(values []any) *DataRow {
// return &DataRow{values: values}
//}
// return the data values
func (d *DataRow) Values() []any {
return d.values
}
type jsonDataRow struct {
Values []any `json:"values"`
}
// send one or more commands to the server and return the response;
// same as Send() but also accepts a Validator
func (c *Client) SendValid(cmd string, validator Validator) (*Response, error) {
if validator.err != nil {
return nil, validator.err
}
return c.Send(cmd)
}
// send one or more commands to the server and return the response
func (c *Client) Send(cmd string) (*Response, error) {
if !printable(cmd) {
return nil, errors.New("command \"" + cmd + "\" contains invalid characters")
}
var rq = &protocol.Request{Commands: cmd}
// send the request
var httprs *http.Response
var err error
if httprs, err = sendRequest(c, "POST", "/cmd", rq); err != nil {
return nil, err
}
// check for error response
if httprs.StatusCode != http.StatusOK {
var m string
if m, err = readResponseMessage(httprs); err != nil {
return nil, err
}
return nil, errors.New(m)
}
var resp Response
if err = readResponse(httprs, &resp.resp); err != nil {
return nil, err
}
return &resp, nil
/*
results := make([]Result, 0)
for j := range cmdr.Results {
r := cmdr.Results[j]
//if r.Status == "error" {
// resp := &Result{Status: r.Status, Message: r.Message}
// return resp, nil
//}
//if r.Status == "ping" {
// return &Result{Status: r.Status}, nil
//}
fields := make([]FieldDescription, 0)
for i := range r.Fields {
fd := FieldDescription{Name: r.Fields[i].Name, Type: r.Fields[i].Type}
fields = append(fields, fd)
}
data := make([]DataRow, 0)
for i := range r.Data {
values := make([]any, 0)
for j := range r.Data[i].Values {
values = append(values, r.Data[i].Values[j])
}
dr := DataRow{Values: values}
data = append(data, dr)
}
results = append(results, Result{
Status: r.Status,
Fields: fields,
Data: data,
Message: r.Message,
})
}
resp := &Response{Results: results}
// fmt.Printf("%#v\n", cmdr)
// print confirmation
// eout.Info("enabled: %s", rq.Command)
return resp, nil
*/
}
// return a hashed password for use with the "create user" command
func (c *Client) HashPassword(password string) string {
return crypto.HashPassword(password, nil, nil)
}
func sendRequest(client *Client, method, url string, requestStruct interface{}) (*http.Response, error) {
var rqj []byte
var err error
if rqj, err = json.Marshal(requestStruct); err != nil {
return nil, err
}
var conn *tls.Conn
var transport *http.Transport
if client.Host == "" {
transport = &http.Transport{}
} else {
var tlsConfig = http.DefaultTransport.(*http.Transport).TLSClientConfig
var tlsClientConfig *tls.Config
if client.TLSSkipVerify {
tlsClientConfig = &tls.Config{InsecureSkipVerify: true}
}
transport = &http.Transport{
TLSClientConfig: tlsClientConfig,
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err = tls.Dial(network, addr, tlsConfig)
return conn, err
},
}
}
var httpClient = &http.Client{Transport: transport}
var remote string
var s string
if client.Host != "127.0.0.1" && !client.NoTLS {
s = "s"
}
remote = "http" + s + "://" + client.Host + ":" + client.Port
var httprq *http.Request
if httprq, err = http.NewRequest(method, remote+url, bytes.NewBuffer(rqj)); err != nil {
return nil, err
}
httprq.SetBasicAuth(client.User, crypto.HashPassword(client.Password, nil, nil))
httprq.Header.Set("Content-Type", "application/json")
var hrs *http.Response
if hrs, err = httpClient.Do(httprq); err != nil {
return nil, err
}
if conn != nil {
// verbose output
var v uint16 = conn.ConnectionState().Version
eout.Trace("protocol version: %d,%d", (v>>8)&255, v&255)
var s string
switch v {
case 0x0300:
s = "SSL (deprecated)"
case 0x0301:
s = "TLS 1.0 (deprecated)"
case 0x0302:
s = "TLS 1.1 (deprecated)"
case 0x0303:
s = "TLS 1.2"
case 0x0304:
s = "TLS 1.3"
default:
s = fmt.Sprintf("unknown version: { %d, %d }", (v>>8)&255, v&255)
}
eout.Verbose("TLS/SSL protocol: %s", s)
} else {
eout.Verbose("no TLS/SSL protocol")
}
return hrs, nil
}
func readResponse(httpResponse *http.Response, responseStruct any) error {
var body []byte
var err error
if body, err = ioutil.ReadAll(httpResponse.Body); err != nil {
return err
}
if err = json.Unmarshal(body, responseStruct); err != nil {
return err
}
fixDataTypes(responseStruct.(**jsonResponse))
return nil
}
func readResponseMessage(httpResponse *http.Response) (string, error) {
var m map[string]interface{}
var err error
if m, err = readResponseMap(httpResponse); err != nil {
return "", err
}
return fmt.Sprintf("%v", m["message"]), nil
}
func fixDataTypes(resp **jsonResponse) {
results := (*resp).Results
for i := range results {
fields := results[i].Fields
for j := range results[i].Data {
for k := range results[i].Data[j].Values {
switch fields[k].DataType {
case "bigint":
results[i].Data[j].Values[k] = int64(results[i].Data[j].Values[k].(float64))
default:
}
}
}
}
}
func readResponseMap(httpResponse *http.Response) (map[string]interface{}, error) {
var m map[string]interface{}
var err error
if err = json.NewDecoder(httpResponse.Body).Decode(&m); err != nil {
return nil, fmt.Errorf("decoding server response: %s", err)
}
return m, nil
}
func printable(s string) bool {
for _, r := range s {
switch r {
case '\n':
continue
case '\r':
continue
case '\t':
continue
}
if !unicode.IsPrint(r) {
return false
}
}
return true
}