forked from fajran/go-monetdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapi.go
361 lines (296 loc) · 7.44 KB
/
mapi.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package monetdb
import (
"bytes"
"crypto"
_ "crypto/md5"
_ "crypto/sha1"
_ "crypto/sha512"
"encoding/binary"
"fmt"
"hash"
"io"
"net"
"strconv"
"strings"
)
const (
mapi_MAX_PACKAGE_LENGTH = (1024 * 8) - 2
mapi_MSG_PROMPT = ""
mapi_MSG_INFO = "#"
mapi_MSG_ERROR = "!"
mapi_MSG_Q = "&"
mapi_MSG_QTABLE = "&1"
mapi_MSG_QUPDATE = "&2"
mapi_MSG_QSCHEMA = "&3"
mapi_MSG_QTRANS = "&4"
mapi_MSG_QPREPARE = "&5"
mapi_MSG_QBLOCK = "&6"
mapi_MSG_HEADER = "%"
mapi_MSG_TUPLE = "["
mapi_MSG_REDIRECT = "^"
mapi_MSG_OK = "=OK"
)
// MAPI connection is established.
const MAPI_STATE_READY = 1
// MAPI connection is NOT established.
const MAPI_STATE_INIT = 0
var (
mapi_MSG_MORE = string([]byte{1, 2, 10})
)
// MapiConn is a MonetDB's MAPI connection handle.
//
// The values in the handle are initially set according to the values
// that are provided when calling NewMapi. However, they may change
// depending on how the MonetDB server redirects the connection.
// The final values are available after the connection is made by
// calling the Connect() function.
//
// The State value can be either MAPI_STATE_INIT or MAPI_STATE_READY.
type MapiConn struct {
Hostname string
Port int
Username string
Password string
Database string
Language string
State int
conn *net.TCPConn
}
// NewMapi returns a MonetDB's MAPI connection handle.
//
// To establish the connection, call the Connect() function.
func NewMapi(hostname string, port int, username, password, database, language string) *MapiConn {
return &MapiConn{
Hostname: hostname,
Port: port,
Username: username,
Password: password,
Database: database,
Language: language,
State: MAPI_STATE_INIT,
}
}
// Disconnect closes the connection.
func (c *MapiConn) Disconnect() {
c.State = MAPI_STATE_INIT
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
}
// Cmd sends a MAPI command to MonetDB.
func (c *MapiConn) Cmd(operation string) (string, error) {
if c.State != MAPI_STATE_READY {
return "", fmt.Errorf("Database not connected")
}
if err := c.putBlock([]byte(operation)); err != nil {
return "", err
}
r, err := c.getBlock()
if err != nil {
return "", err
}
resp := string(r)
if len(resp) == 0 {
return "", nil
} else if strings.HasPrefix(resp, mapi_MSG_OK) {
return strings.TrimSpace(resp[3:]), nil
} else if resp == mapi_MSG_MORE {
// tell server it isn't going to get more
return c.Cmd("")
} else if strings.HasPrefix(resp, mapi_MSG_Q) || strings.HasPrefix(resp, mapi_MSG_HEADER) || strings.HasPrefix(resp, mapi_MSG_TUPLE) {
return resp, nil
} else if strings.HasPrefix(resp, mapi_MSG_ERROR) {
return "", fmt.Errorf("Operational error: %s", resp[1:])
} else {
return "", fmt.Errorf("Unknown state: %s", resp)
}
}
// Connect starts a MAPI connection to MonetDB server.
func (c *MapiConn) Connect() error {
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
addr := fmt.Sprintf("%s:%d", c.Hostname, c.Port)
raddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return err
}
conn, err := net.DialTCP("tcp", nil, raddr)
if err != nil {
return err
}
conn.SetKeepAlive(false)
conn.SetNoDelay(true)
c.conn = conn
err = c.login()
if err != nil {
return err
}
return nil
}
// login starts the login sequence
func (c *MapiConn) login() error {
return c.tryLogin(0)
}
// tryLogin performs the login activity
func (c *MapiConn) tryLogin(iteration int) error {
challenge, err := c.getBlock()
if err != nil {
return err
}
response, err := c.challengeResponse(challenge)
if err != nil {
return err
}
c.putBlock([]byte(response))
bprompt, err := c.getBlock()
if err != nil {
return nil
}
prompt := strings.TrimSpace(string(bprompt))
if len(prompt) == 0 {
// Empty response, server is happy
} else if prompt == mapi_MSG_OK {
// pass
} else if strings.HasPrefix(prompt, mapi_MSG_INFO) {
// TODO log info
} else if strings.HasPrefix(prompt, mapi_MSG_ERROR) {
// TODO log error
return fmt.Errorf("Database error: %s", prompt[1:])
} else if strings.HasPrefix(prompt, mapi_MSG_REDIRECT) {
t := strings.Split(prompt, " ")
r := strings.Split(t[0][1:], ":")
if r[1] == "merovingian" {
// restart auth
if iteration <= 10 {
c.tryLogin(iteration + 1)
} else {
return fmt.Errorf("Maximal number of redirects reached (10)")
}
} else if r[1] == "monetdb" {
c.Hostname = r[2][2:]
t = strings.Split(r[3], "/")
port, _ := strconv.ParseInt(t[0], 10, 32)
c.Port = int(port)
c.Database = t[1]
c.conn.Close()
c.Connect()
} else {
return fmt.Errorf("Unknown redirect: %s", prompt)
}
} else {
return fmt.Errorf("Unknown state: %s", prompt)
}
c.State = MAPI_STATE_READY
return nil
}
// challengeResponse produces a response given a challenge
func (c *MapiConn) challengeResponse(challenge []byte) (string, error) {
t := strings.Split(string(challenge), ":")
salt := t[0]
protocol := t[2]
hashes := t[3]
algo := t[5]
if protocol != "9" {
return "", fmt.Errorf("We only speak protocol v9")
}
var h hash.Hash
if algo == "SHA512" {
h = crypto.SHA512.New()
} else {
// TODO support more algorithm
return "", fmt.Errorf("Unsupported algorithm: %s", algo)
}
io.WriteString(h, c.Password)
p := fmt.Sprintf("%x", h.Sum(nil))
shashes := "," + hashes + ","
var pwhash string
if strings.Contains(shashes, ",SHA1,") {
h = crypto.SHA1.New()
io.WriteString(h, p)
io.WriteString(h, salt)
pwhash = fmt.Sprintf("{SHA1}%x", h.Sum(nil))
} else if strings.Contains(shashes, ",MD5,") {
h = crypto.MD5.New()
io.WriteString(h, p)
io.WriteString(h, salt)
pwhash = fmt.Sprintf("{MD5}%x", h.Sum(nil))
} else {
return "", fmt.Errorf("Unsupported hash algorithm required for login %s", hashes)
}
r := fmt.Sprintf("BIG:%s:%s:%s:%s:", c.Username, pwhash, c.Language, c.Database)
return r, nil
}
// getBlock retrieves a block of message
func (c *MapiConn) getBlock() ([]byte, error) {
r := new(bytes.Buffer)
last := 0
for last != 1 {
flag, err := c.getBytes(2)
if err != nil {
return nil, err
}
var unpacked uint16
buf := bytes.NewBuffer(flag)
err = binary.Read(buf, binary.LittleEndian, &unpacked)
if err != nil {
return nil, err
}
length := unpacked >> 1
last = int(unpacked & 1)
d, err := c.getBytes(int(length))
if err != nil {
return nil, err
}
r.Write(d)
}
return r.Bytes(), nil
}
// getBytes reads the given amount of bytes
func (c *MapiConn) getBytes(count int) ([]byte, error) {
r := make([]byte, count)
b := make([]byte, count)
read := 0
for read < count {
n, err := c.conn.Read(b)
if err != nil {
return nil, err
}
copy(r[read:], b[:n])
read += n
}
return r, nil
}
// putBlock sends the given data as one or more blocks
func (c *MapiConn) putBlock(b []byte) error {
pos := 0
last := 0
for last != 1 {
end := pos + mapi_MAX_PACKAGE_LENGTH
if end > len(b) {
end = len(b)
}
data := b[pos:end]
length := len(data)
if length < mapi_MAX_PACKAGE_LENGTH {
last = 1
}
var packed uint16
packed = uint16((length << 1) + last)
flag := new(bytes.Buffer)
binary.Write(flag, binary.LittleEndian, packed)
if _, err := c.conn.Write(flag.Bytes()); err != nil {
return err
}
if _, err := c.conn.Write(data); err != nil {
return err
}
pos += length
}
return nil
}