Debian Codegraph @

tds.go

raw symbols SCIP
1 package mssql
2
3 import (
4 "crypto/tls"
5 "crypto/x509"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "golang.org/x/net/context" // use the "x/net/context" for backwards compatibility.
10 "io"
11 "io/ioutil"
12 "net"
13 "net/url"
14 "os"
15 "sort"
16 "strconv"
17 "strings"
18 "time"
19 "unicode"
20 "unicode/utf16"
21 "unicode/utf8"
22 )
23
24 func parseInstances(msg []byte) map[string]map[string]string {
25 results := map[string]map[string]string{}
26 if len(msg) > 3 && msg[0] == 5 {
27 out_s := string(msg[3:])
28 tokens := strings.Split(out_s, ";")
29 instdict := map[string]string{}
30 got_name := false
31 var name string
32 for _, token := range tokens {
33 if got_name {
34 instdict[name] = token
35 got_name = false
36 } else {
37 name = token
38 if len(name) == 0 {
39 if len(instdict) == 0 {
40 break
41 }
42 results[strings.ToUpper(instdict["InstanceName"])] = instdict
43 instdict = map[string]string{}
44 continue
45 }
46 got_name = true
47 }
48 }
49 }
50 return results
51 }
52
53 func getInstances(address string) (map[string]map[string]string, error) {
54 conn, err := net.DialTimeout("udp", address+":1434", 5*time.Second)
55 if err != nil {
56 return nil, err
57 }
58 defer conn.Close()
59 conn.SetDeadline(time.Now().Add(5 * time.Second))
60 _, err = conn.Write([]byte{3})
61 if err != nil {
62 return nil, err
63 }
64 var resp = make([]byte, 16*1024-1)
65 read, err := conn.Read(resp)
66 if err != nil {
67 return nil, err
68 }
69 return parseInstances(resp[:read]), nil
70 }
71
72 // tds versions
73 const (
74 verTDS70 = 0x70000000
75 verTDS71 = 0x71000000
76 verTDS71rev1 = 0x71000001
77 verTDS72 = 0x72090002
78 verTDS73A = 0x730A0003
79 verTDS73 = verTDS73A
80 verTDS73B = 0x730B0003
81 verTDS74 = 0x74000004
82 )
83
84 // packet types
85 // https://msdn.microsoft.com/en-us/library/dd304214.aspx
86 const (
87 packSQLBatch packetType = 1
88 packRPCRequest = 3
89 packReply = 4
90
91 // 2.2.1.7 Attention: https://msdn.microsoft.com/en-us/library/dd341449.aspx
92 // 4.19.2 Out-of-Band Attention Signal: https://msdn.microsoft.com/en-us/library/dd305167.aspx
93 packAttention = 6
94
95 packBulkLoadBCP = 7
96 packTransMgrReq = 14
97 packNormal = 15
98 packLogin7 = 16
99 packSSPIMessage = 17
100 packPrelogin = 18
101 )
102
103 // prelogin fields
104 // http://msdn.microsoft.com/en-us/library/dd357559.aspx
105 const (
106 preloginVERSION = 0
107 preloginENCRYPTION = 1
108 preloginINSTOPT = 2
109 preloginTHREADID = 3
110 preloginMARS = 4
111 preloginTRACEID = 5
112 preloginTERMINATOR = 0xff
113 )
114
115 const (
116 encryptOff = 0 // Encryption is available but off.
117 encryptOn = 1 // Encryption is available and on.
118 encryptNotSup = 2 // Encryption is not available.
119 encryptReq = 3 // Encryption is required.
120 )
121
122 type tdsSession struct {
123 buf *tdsBuffer
124 loginAck loginAckStruct
125 database string
126 partner string
127 columns []columnStruct
128 tranid uint64
129 logFlags uint64
130 log optionalLogger
131 routedServer string
132 routedPort uint16
133 }
134
135 const (
136 logErrors = 1
137 logMessages = 2
138 logRows = 4
139 logSQL = 8
140 logParams = 16
141 logTransaction = 32
142 logDebug = 64
143 )
144
145 type columnStruct struct {
146 UserType uint32
147 Flags uint16
148 ColName string
149 ti typeInfo
150 }
151
152 type KeySlice []uint8
153
154 func (p KeySlice) Len() int { return len(p) }
155 func (p KeySlice) Less(i, j int) bool { return p[i] < p[j] }
156 func (p KeySlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
157
158 // http://msdn.microsoft.com/en-us/library/dd357559.aspx
159 func writePrelogin(w *tdsBuffer, fields map[uint8][]byte) error {
160 var err error
161
162 w.BeginPacket(packPrelogin)
163 offset := uint16(5*len(fields) + 1)
164 keys := make(KeySlice, 0, len(fields))
165 for k, _ := range fields {
166 keys = append(keys, k)
167 }
168 sort.Sort(keys)
169 // writing header
170 for _, k := range keys {
171 err = w.WriteByte(k)
172 if err != nil {
173 return err
174 }
175 err = binary.Write(w, binary.BigEndian, offset)
176 if err != nil {
177 return err
178 }
179 v := fields[k]
180 size := uint16(len(v))
181 err = binary.Write(w, binary.BigEndian, size)
182 if err != nil {
183 return err
184 }
185 offset += size
186 }
187 err = w.WriteByte(preloginTERMINATOR)
188 if err != nil {
189 return err
190 }
191 // writing values
192 for _, k := range keys {
193 v := fields[k]
194 written, err := w.Write(v)
195 if err != nil {
196 return err
197 }
198 if written != len(v) {
199 return errors.New("Write method didn't write the whole value")
200 }
201 }
202 return w.FinishPacket()
203 }
204
205 func readPrelogin(r *tdsBuffer) (map[uint8][]byte, error) {
206 packet_type, err := r.BeginRead()
207 if err != nil {
208 return nil, err
209 }
210 struct_buf, err := ioutil.ReadAll(r)
211 if err != nil {
212 return nil, err
213 }
214 if packet_type != 4 {
215 return nil, errors.New("Invalid respones, expected packet type 4, PRELOGIN RESPONSE")
216 }
217 offset := 0
218 results := map[uint8][]byte{}
219 for true {
220 rec_type := struct_buf[offset]
221 if rec_type == preloginTERMINATOR {
222 break
223 }
224
225 rec_offset := binary.BigEndian.Uint16(struct_buf[offset+1:])
226 rec_len := binary.BigEndian.Uint16(struct_buf[offset+3:])
227 value := struct_buf[rec_offset : rec_offset+rec_len]
228 results[rec_type] = value
229 offset += 5
230 }
231 return results, nil
232 }
233
234 // OptionFlags2
235 // http://msdn.microsoft.com/en-us/library/dd304019.aspx
236 const (
237 fLanguageFatal = 1
238 fODBC = 2
239 fTransBoundary = 4
240 fCacheConnect = 8
241 fIntSecurity = 0x80
242 )
243
244 // TypeFlags
245 const (
246 // 4 bits for fSQLType
247 // 1 bit for fOLEDB
248 fReadOnlyIntent = 32
249 )
250
251 type login struct {
252 TDSVersion uint32
253 PacketSize uint32
254 ClientProgVer uint32
255 ClientPID uint32
256 ConnectionID uint32
257 OptionFlags1 uint8
258 OptionFlags2 uint8
259 TypeFlags uint8
260 OptionFlags3 uint8
261 ClientTimeZone int32
262 ClientLCID uint32
263 HostName string
264 UserName string
265 Password string
266 AppName string
267 ServerName string
268 CtlIntName string
269 Language string
270 Database string
271 ClientID [6]byte
272 SSPI []byte
273 AtchDBFile string
274 ChangePassword string
275 }
276
277 type loginHeader struct {
278 Length uint32
279 TDSVersion uint32
280 PacketSize uint32
281 ClientProgVer uint32
282 ClientPID uint32
283 ConnectionID uint32
284 OptionFlags1 uint8
285 OptionFlags2 uint8
286 TypeFlags uint8
287 OptionFlags3 uint8
288 ClientTimeZone int32
289 ClientLCID uint32
290 HostNameOffset uint16
291 HostNameLength uint16
292 UserNameOffset uint16
293 UserNameLength uint16
294 PasswordOffset uint16
295 PasswordLength uint16
296 AppNameOffset uint16
297 AppNameLength uint16
298 ServerNameOffset uint16
299 ServerNameLength uint16
300 ExtensionOffset uint16
301 ExtensionLenght uint16
302 CtlIntNameOffset uint16
303 CtlIntNameLength uint16
304 LanguageOffset uint16
305 LanguageLength uint16
306 DatabaseOffset uint16
307 DatabaseLength uint16
308 ClientID [6]byte
309 SSPIOffset uint16
310 SSPILength uint16
311 AtchDBFileOffset uint16
312 AtchDBFileLength uint16
313 ChangePasswordOffset uint16
314 ChangePasswordLength uint16
315 SSPILongLength uint32
316 }
317
318 // convert Go string to UTF-16 encoded []byte (littleEndian)
319 // done manually rather than using bytes and binary packages
320 // for performance reasons
321 func str2ucs2(s string) []byte {
322 res := utf16.Encode([]rune(s))
323 ucs2 := make([]byte, 2*len(res))
324 for i := 0; i < len(res); i++ {
325 ucs2[2*i] = byte(res[i])
326 ucs2[2*i+1] = byte(res[i] >> 8)
327 }
328 return ucs2
329 }
330
331 func ucs22str(s []byte) (string, error) {
332 if len(s)%2 != 0 {
333 return "", fmt.Errorf("Illegal UCS2 string length: %d", len(s))
334 }
335 buf := make([]uint16, len(s)/2)
336 for i := 0; i < len(s); i += 2 {
337 buf[i/2] = binary.LittleEndian.Uint16(s[i:])
338 }
339 return string(utf16.Decode(buf)), nil
340 }
341
342 func manglePassword(password string) []byte {
343 var ucs2password []byte = str2ucs2(password)
344 for i, ch := range ucs2password {
345 ucs2password[i] = ((ch<<4)&0xff | (ch >> 4)) ^ 0xA5
346 }
347 return ucs2password
348 }
349
350 // http://msdn.microsoft.com/en-us/library/dd304019.aspx
351 func sendLogin(w *tdsBuffer, login login) error {
352 w.BeginPacket(packLogin7)
353 hostname := str2ucs2(login.HostName)
354 username := str2ucs2(login.UserName)
355 password := manglePassword(login.Password)
356 appname := str2ucs2(login.AppName)
357 servername := str2ucs2(login.ServerName)
358 ctlintname := str2ucs2(login.CtlIntName)
359 language := str2ucs2(login.Language)
360 database := str2ucs2(login.Database)
361 atchdbfile := str2ucs2(login.AtchDBFile)
362 changepassword := str2ucs2(login.ChangePassword)
363 hdr := loginHeader{
364 TDSVersion: login.TDSVersion,
365 PacketSize: login.PacketSize,
366 ClientProgVer: login.ClientProgVer,
367 ClientPID: login.ClientPID,
368 ConnectionID: login.ConnectionID,
369 OptionFlags1: login.OptionFlags1,
370 OptionFlags2: login.OptionFlags2,
371 TypeFlags: login.TypeFlags,
372 OptionFlags3: login.OptionFlags3,
373 ClientTimeZone: login.ClientTimeZone,
374 ClientLCID: login.ClientLCID,
375 HostNameLength: uint16(utf8.RuneCountInString(login.HostName)),
376 UserNameLength: uint16(utf8.RuneCountInString(login.UserName)),
377 PasswordLength: uint16(utf8.RuneCountInString(login.Password)),
378 AppNameLength: uint16(utf8.RuneCountInString(login.AppName)),
379 ServerNameLength: uint16(utf8.RuneCountInString(login.ServerName)),
380 CtlIntNameLength: uint16(utf8.RuneCountInString(login.CtlIntName)),
381 LanguageLength: uint16(utf8.RuneCountInString(login.Language)),
382 DatabaseLength: uint16(utf8.RuneCountInString(login.Database)),
383 ClientID: login.ClientID,
384 SSPILength: uint16(len(login.SSPI)),
385 AtchDBFileLength: uint16(utf8.RuneCountInString(login.AtchDBFile)),
386 ChangePasswordLength: uint16(utf8.RuneCountInString(login.ChangePassword)),
387 }
388 offset := uint16(binary.Size(hdr))
389 hdr.HostNameOffset = offset
390 offset += uint16(len(hostname))
391 hdr.UserNameOffset = offset
392 offset += uint16(len(username))
393 hdr.PasswordOffset = offset
394 offset += uint16(len(password))
395 hdr.AppNameOffset = offset
396 offset += uint16(len(appname))
397 hdr.ServerNameOffset = offset
398 offset += uint16(len(servername))
399 hdr.CtlIntNameOffset = offset
400 offset += uint16(len(ctlintname))
401 hdr.LanguageOffset = offset
402 offset += uint16(len(language))
403 hdr.DatabaseOffset = offset
404 offset += uint16(len(database))
405 hdr.SSPIOffset = offset
406 offset += uint16(len(login.SSPI))
407 hdr.AtchDBFileOffset = offset
408 offset += uint16(len(atchdbfile))
409 hdr.ChangePasswordOffset = offset
410 offset += uint16(len(changepassword))
411 hdr.Length = uint32(offset)
412 var err error
413 err = binary.Write(w, binary.LittleEndian, &hdr)
414 if err != nil {
415 return err
416 }
417 _, err = w.Write(hostname)
418 if err != nil {
419 return err
420 }
421 _, err = w.Write(username)
422 if err != nil {
423 return err
424 }
425 _, err = w.Write(password)
426 if err != nil {
427 return err
428 }
429 _, err = w.Write(appname)
430 if err != nil {
431 return err
432 }
433 _, err = w.Write(servername)
434 if err != nil {
435 return err
436 }
437 _, err = w.Write(ctlintname)
438 if err != nil {
439 return err
440 }
441 _, err = w.Write(language)
442 if err != nil {
443 return err
444 }
445 _, err = w.Write(database)
446 if err != nil {
447 return err
448 }
449 _, err = w.Write(login.SSPI)
450 if err != nil {
451 return err
452 }
453 _, err = w.Write(atchdbfile)
454 if err != nil {
455 return err
456 }
457 _, err = w.Write(changepassword)
458 if err != nil {
459 return err
460 }
461 return w.FinishPacket()
462 }
463
464 func readUcs2(r io.Reader, numchars int) (res string, err error) {
465 buf := make([]byte, numchars*2)
466 _, err = io.ReadFull(r, buf)
467 if err != nil {
468 return "", err
469 }
470 return ucs22str(buf)
471 }
472
473 func readUsVarChar(r io.Reader) (res string, err error) {
474 var numchars uint16
475 err = binary.Read(r, binary.LittleEndian, &numchars)
476 if err != nil {
477 return "", err
478 }
479 return readUcs2(r, int(numchars))
480 }
481
482 func writeUsVarChar(w io.Writer, s string) (err error) {
483 buf := str2ucs2(s)
484 var numchars int = len(buf) / 2
485 if numchars > 0xffff {
486 panic("invalid size for US_VARCHAR")
487 }
488 err = binary.Write(w, binary.LittleEndian, uint16(numchars))
489 if err != nil {
490 return
491 }
492 _, err = w.Write(buf)
493 return
494 }
495
496 func readBVarChar(r io.Reader) (res string, err error) {
497 var numchars uint8
498 err = binary.Read(r, binary.LittleEndian, &numchars)
499 if err != nil {
500 return "", err
501 }
502
503 // A zero length could be returned, return an empty string
504 if numchars == 0 {
505 return "", nil
506 }
507 return readUcs2(r, int(numchars))
508 }
509
510 func writeBVarChar(w io.Writer, s string) (err error) {
511 buf := str2ucs2(s)
512 var numchars int = len(buf) / 2
513 if numchars > 0xff {
514 panic("invalid size for B_VARCHAR")
515 }
516 err = binary.Write(w, binary.LittleEndian, uint8(numchars))
517 if err != nil {
518 return
519 }
520 _, err = w.Write(buf)
521 return
522 }
523
524 func readBVarByte(r io.Reader) (res []byte, err error) {
525 var length uint8
526 err = binary.Read(r, binary.LittleEndian, &length)
527 if err != nil {
528 return
529 }
530 res = make([]byte, length)
531 _, err = io.ReadFull(r, res)
532 return
533 }
534
535 func readUshort(r io.Reader) (res uint16, err error) {
536 err = binary.Read(r, binary.LittleEndian, &res)
537 return
538 }
539
540 func readByte(r io.Reader) (res byte, err error) {
541 var b [1]byte
542 _, err = r.Read(b[:])
543 res = b[0]
544 return
545 }
546
547 // Packet Data Stream Headers
548 // http://msdn.microsoft.com/en-us/library/dd304953.aspx
549 type headerStruct struct {
550 hdrtype uint16
551 data []byte
552 }
553
554 const (
555 dataStmHdrQueryNotif = 1 // query notifications
556 dataStmHdrTransDescr = 2 // MARS transaction descriptor (required)
557 dataStmHdrTraceActivity = 3
558 )
559
560 // Query Notifications Header
561 // http://msdn.microsoft.com/en-us/library/dd304949.aspx
562 type queryNotifHdr struct {
563 notifyId string
564 ssbDeployment string
565 notifyTimeout uint32
566 }
567
568 func (hdr queryNotifHdr) pack() (res []byte) {
569 notifyId := str2ucs2(hdr.notifyId)
570 ssbDeployment := str2ucs2(hdr.ssbDeployment)
571
572 res = make([]byte, 2+len(notifyId)+2+len(ssbDeployment)+4)
573 b := res
574
575 binary.LittleEndian.PutUint16(b, uint16(len(notifyId)))
576 b = b[2:]
577 copy(b, notifyId)
578 b = b[len(notifyId):]
579
580 binary.LittleEndian.PutUint16(b, uint16(len(ssbDeployment)))
581 b = b[2:]
582 copy(b, ssbDeployment)
583 b = b[len(ssbDeployment):]
584
585 binary.LittleEndian.PutUint32(b, hdr.notifyTimeout)
586
587 return res
588 }
589
590 // MARS Transaction Descriptor Header
591 // http://msdn.microsoft.com/en-us/library/dd340515.aspx
592 type transDescrHdr struct {
593 transDescr uint64 // transaction descriptor returned from ENVCHANGE
594 outstandingReqCnt uint32 // outstanding request count
595 }
596
597 func (hdr transDescrHdr) pack() (res []byte) {
598 res = make([]byte, 8+4)
599 binary.LittleEndian.PutUint64(res, hdr.transDescr)
600 binary.LittleEndian.PutUint32(res[8:], hdr.outstandingReqCnt)
601 return res
602 }
603
604 func writeAllHeaders(w io.Writer, headers []headerStruct) (err error) {
605 // Calculating total length.
606 var totallen uint32 = 4
607 for _, hdr := range headers {
608 totallen += 4 + 2 + uint32(len(hdr.data))
609 }
610 // writing
611 err = binary.Write(w, binary.LittleEndian, totallen)
612 if err != nil {
613 return err
614 }
615 for _, hdr := range headers {
616 var headerlen uint32 = 4 + 2 + uint32(len(hdr.data))
617 err = binary.Write(w, binary.LittleEndian, headerlen)
618 if err != nil {
619 return err
620 }
621 err = binary.Write(w, binary.LittleEndian, hdr.hdrtype)
622 if err != nil {
623 return err
624 }
625 _, err = w.Write(hdr.data)
626 if err != nil {
627 return err
628 }
629 }
630 return nil
631 }
632
633 func sendSqlBatch72(buf *tdsBuffer,
634 sqltext string,
635 headers []headerStruct) (err error) {
636 buf.BeginPacket(packSQLBatch)
637
638 if err = writeAllHeaders(buf, headers); err != nil {
639 return
640 }
641
642 _, err = buf.Write(str2ucs2(sqltext))
643 if err != nil {
644 return
645 }
646 return buf.FinishPacket()
647 }
648
649 // 2.2.1.7 Attention: https://msdn.microsoft.com/en-us/library/dd341449.aspx
650 // 4.19.2 Out-of-Band Attention Signal: https://msdn.microsoft.com/en-us/library/dd305167.aspx
651 func sendAttention(buf *tdsBuffer) error {
652 buf.BeginPacket(packAttention)
653 return buf.FinishPacket()
654 }
655
656 type connectParams struct {
657 logFlags uint64
658 port uint64
659 host string
660 instance string
661 database string
662 user string
663 password string
664 dial_timeout time.Duration
665 conn_timeout time.Duration
666 keepAlive time.Duration
667 encrypt bool
668 disableEncryption bool
669 trustServerCertificate bool
670 certificate string
671 hostInCertificate string
672 serverSPN string
673 workstation string
674 appname string
675 typeFlags uint8
676 failOverPartner string
677 failOverPort uint64
678 packetSize uint16
679 }
680
681 func splitConnectionString(dsn string) (res map[string]string) {
682 res = map[string]string{}
683 parts := strings.Split(dsn, ";")
684 for _, part := range parts {
685 if len(part) == 0 {
686 continue
687 }
688 lst := strings.SplitN(part, "=", 2)
689 name := strings.TrimSpace(strings.ToLower(lst[0]))
690 if len(name) == 0 {
691 continue
692 }
693 var value string = ""
694 if len(lst) > 1 {
695 value = strings.TrimSpace(lst[1])
696 }
697 res[name] = value
698 }
699 return res
700 }
701
702 // Splits a URL in the ODBC format
703 func splitConnectionStringOdbc(dsn string) (map[string]string, error) {
704 res := map[string]string{}
705
706 type parserState int
707 const (
708 // Before the start of a key
709 parserStateBeforeKey parserState = iota
710
711 // Inside a key
712 parserStateKey
713
714 // Beginning of a value. May be bare or braced
715 parserStateBeginValue
716
717 // Inside a bare value
718 parserStateBareValue
719
720 // Inside a braced value
721 parserStateBracedValue
722
723 // A closing brace inside a braced value.
724 // May be the end of the value or an escaped closing brace, depending on the next character
725 parserStateBracedValueClosingBrace
726
727 // After a value. Next character should be a semicolon or whitespace.
728 parserStateEndValue
729 )
730
731 var state = parserStateBeforeKey
732
733 var key string
734 var value string
735
736 for i, c := range dsn {
737 switch state {
738 case parserStateBeforeKey:
739 switch {
740 case c == '=':
741 return res, fmt.Errorf("Unexpected character = at index %d. Expected start of key or semi-colon or whitespace.", i)
742 case !unicode.IsSpace(c) && c != ';':
743 state = parserStateKey
744 key += string(c)
745 }
746
747 case parserStateKey:
748 switch c {
749 case '=':
750 key = normalizeOdbcKey(key)
751 if len(key) == 0 {
752 return res, fmt.Errorf("Unexpected end of key at index %d.", i)
753 }
754
755 state = parserStateBeginValue
756
757 case ';':
758 // Key without value
759 key = normalizeOdbcKey(key)
760 if len(key) == 0 {
761 return res, fmt.Errorf("Unexpected end of key at index %d.", i)
762 }
763
764 res[key] = value
765 key = ""
766 value = ""
767 state = parserStateBeforeKey
768
769 default:
770 key += string(c)
771 }
772
773 case parserStateBeginValue:
774 switch {
775 case c == '{':
776 state = parserStateBracedValue
777 case c == ';':
778 // Empty value
779 res[key] = value
780 key = ""
781 state = parserStateBeforeKey
782 case unicode.IsSpace(c):
783 // Ignore whitespace
784 default:
785 state = parserStateBareValue
786 value += string(c)
787 }
788
789 case parserStateBareValue:
790 if c == ';' {
791 res[key] = strings.TrimRightFunc(value, unicode.IsSpace)
792 key = ""
793 value = ""
794 state = parserStateBeforeKey
795 } else {
796 value += string(c)
797 }
798
799 case parserStateBracedValue:
800 if c == '}' {
801 state = parserStateBracedValueClosingBrace
802 } else {
803 value += string(c)
804 }
805
806 case parserStateBracedValueClosingBrace:
807 if c == '}' {
808 // Escaped closing brace
809 value += string(c)
810 state = parserStateBracedValue
811 continue
812 }
813
814 // End of braced value
815 res[key] = value
816 key = ""
817 value = ""
818
819 // This character is the first character past the end,
820 // so it needs to be parsed like the parserStateEndValue state.
821 state = parserStateEndValue
822 switch {
823 case c == ';':
824 state = parserStateBeforeKey
825 case unicode.IsSpace(c):
826 // Ignore whitespace
827 default:
828 return res, fmt.Errorf("Unexpected character %c at index %d. Expected semi-colon or whitespace.", c, i)
829 }
830
831 case parserStateEndValue:
832 switch {
833 case c == ';':
834 state = parserStateBeforeKey
835 case unicode.IsSpace(c):
836 // Ignore whitespace
837 default:
838 return res, fmt.Errorf("Unexpected character %c at index %d. Expected semi-colon or whitespace.", c, i)
839 }
840 }
841 }
842
843 switch state {
844 case parserStateBeforeKey: // Okay
845 case parserStateKey: // Unfinished key. Treat as key without value.
846 key = normalizeOdbcKey(key)
847 if len(key) == 0 {
848 return res, fmt.Errorf("Unexpected end of key at index %d.", len(dsn))
849 }
850 res[key] = value
851 case parserStateBeginValue: // Empty value
852 res[key] = value
853 case parserStateBareValue:
854 res[key] = strings.TrimRightFunc(value, unicode.IsSpace)
855 case parserStateBracedValue:
856 return res, fmt.Errorf("Unexpected end of braced value at index %d.", len(dsn))
857 case parserStateBracedValueClosingBrace: // End of braced value
858 res[key] = value
859 case parserStateEndValue: // Okay
860 }
861
862 return res, nil
863 }
864
865 // Normalizes the given string as an ODBC-format key
866 func normalizeOdbcKey(s string) string {
867 return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace))
868 }
869
870 // Splits a URL of the form sqlserver://username:password@host/instance?param1=value&param2=value
871 func splitConnectionStringURL(dsn string) (map[string]string, error) {
872 res := map[string]string{}
873
874 u, err := url.Parse(dsn)
875 if err != nil {
876 return res, err
877 }
878
879 if u.Scheme != "sqlserver" {
880 return res, fmt.Errorf("scheme %s is not recognized", u.Scheme)
881 }
882
883 if u.User != nil {
884 res["user id"] = u.User.Username()
885 p, exists := u.User.Password()
886 if exists {
887 res["password"] = p
888 }
889 }
890
891 host, port, err := net.SplitHostPort(u.Host)
892 if err != nil {
893 host = u.Host
894 }
895
896 if len(u.Path) > 0 {
897 res["server"] = host + "\\" + u.Path[1:]
898 } else {
899 res["server"] = host
900 }
901
902 if len(port) > 0 {
903 res["port"] = port
904 }
905
906 query := u.Query()
907 for k, v := range query {
908 if len(v) > 1 {
909 return res, fmt.Errorf("key %s provided more than once", k)
910 }
911 res[strings.ToLower(k)] = v[0]
912 }
913
914 return res, nil
915 }
916
917 func parseConnectParams(dsn string) (connectParams, error) {
918 var p connectParams
919
920 var params map[string]string
921 if strings.HasPrefix(dsn, "odbc:") {
922 parameters, err := splitConnectionStringOdbc(dsn[len("odbc:"):])
923 if err != nil {
924 return p, err
925 }
926 params = parameters
927 } else if strings.HasPrefix(dsn, "sqlserver://") {
928 parameters, err := splitConnectionStringURL(dsn)
929 if err != nil {
930 return p, err
931 }
932 params = parameters
933 } else {
934 params = splitConnectionString(dsn)
935 }
936
937 strlog, ok := params["log"]
938 if ok {
939 var err error
940 p.logFlags, err = strconv.ParseUint(strlog, 10, 0)
941 if err != nil {
942 return p, fmt.Errorf("Invalid log parameter '%s': %s", strlog, err.Error())
943 }
944 }
945 server := params["server"]
946 parts := strings.SplitN(server, "\\", 2)
947 p.host = parts[0]
948 if p.host == "." || strings.ToUpper(p.host) == "(LOCAL)" || p.host == "" {
949 p.host = "localhost"
950 }
951 if len(parts) > 1 {
952 p.instance = parts[1]
953 }
954 p.database = params["database"]
955 p.user = params["user id"]
956 p.password = params["password"]
957
958 p.port = 1433
959 strport, ok := params["port"]
960 if ok {
961 var err error
962 p.port, err = strconv.ParseUint(strport, 0, 16)
963 if err != nil {
964 f := "Invalid tcp port '%v': %v"
965 return p, fmt.Errorf(f, strport, err.Error())
966 }
967 }
968
969 // https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option
970 // Default packet size remains at 4096 bytes
971 p.packetSize = 4096
972 strpsize, ok := params["packet size"]
973 if ok {
974 var err error
975 psize, err := strconv.ParseUint(strpsize, 0, 16)
976 if err != nil {
977 f := "Invalid packet size '%v': %v"
978 return p, fmt.Errorf(f, strpsize, err.Error())
979 }
980
981 // Ensure packet size falls within the TDS protocol range of 512 to 32767 bytes
982 // NOTE: Encrypted connections have a maximum size of 16383 bytes. If you request
983 // a higher packet size, the server will respond with an ENVCHANGE request to
984 // alter the packet size to 16383 bytes.
985 p.packetSize = uint16(psize)
986 if p.packetSize < 512 {
987 p.packetSize = 512
988 } else if p.packetSize > 32767 {
989 p.packetSize = 32767
990 }
991 }
992
993 // https://msdn.microsoft.com/en-us/library/dd341108.aspx
994 p.dial_timeout = 15 * time.Second
995 p.conn_timeout = 30 * time.Second
996 strconntimeout, ok := params["connection timeout"]
997 if ok {
998 timeout, err := strconv.ParseUint(strconntimeout, 0, 16)
999 if err != nil {
1000 f := "Invalid connection timeout '%v': %v"
1001 return p, fmt.Errorf(f, strconntimeout, err.Error())
1002 }
1003 p.conn_timeout = time.Duration(timeout) * time.Second
1004 }
1005 strdialtimeout, ok := params["dial timeout"]
1006 if ok {
1007 timeout, err := strconv.ParseUint(strdialtimeout, 0, 16)
1008 if err != nil {
1009 f := "Invalid dial timeout '%v': %v"
1010 return p, fmt.Errorf(f, strdialtimeout, err.Error())
1011 }
1012 p.dial_timeout = time.Duration(timeout) * time.Second
1013 }
1014
1015 // default keep alive should be 30 seconds according to spec:
1016 // https://msdn.microsoft.com/en-us/library/dd341108.aspx
1017 p.keepAlive = 30 * time.Second
1018
1019 keepAlive, ok := params["keepalive"]
1020 if ok {
1021 timeout, err := strconv.ParseUint(keepAlive, 0, 16)
1022 if err != nil {
1023 f := "Invalid keepAlive value '%s': %s"
1024 return p, fmt.Errorf(f, keepAlive, err.Error())
1025 }
1026 p.keepAlive = time.Duration(timeout) * time.Second
1027 }
1028 encrypt, ok := params["encrypt"]
1029 if ok {
1030 if strings.ToUpper(encrypt) == "DISABLE" {
1031 p.disableEncryption = true
1032 } else {
1033 var err error
1034 p.encrypt, err = strconv.ParseBool(encrypt)
1035 if err != nil {
1036 f := "Invalid encrypt '%s': %s"
1037 return p, fmt.Errorf(f, encrypt, err.Error())
1038 }
1039 }
1040 } else {
1041 p.trustServerCertificate = true
1042 }
1043 trust, ok := params["trustservercertificate"]
1044 if ok {
1045 var err error
1046 p.trustServerCertificate, err = strconv.ParseBool(trust)
1047 if err != nil {
1048 f := "Invalid trust server certificate '%s': %s"
1049 return p, fmt.Errorf(f, trust, err.Error())
1050 }
1051 }
1052 p.certificate = params["certificate"]
1053 p.hostInCertificate, ok = params["hostnameincertificate"]
1054 if !ok {
1055 p.hostInCertificate = p.host
1056 }
1057
1058 serverSPN, ok := params["serverspn"]
1059 if ok {
1060 p.serverSPN = serverSPN
1061 } else {
1062 p.serverSPN = fmt.Sprintf("MSSQLSvc/%s:%d", p.host, p.port)
1063 }
1064
1065 workstation, ok := params["workstation id"]
1066 if ok {
1067 p.workstation = workstation
1068 } else {
1069 workstation, err := os.Hostname()
1070 if err == nil {
1071 p.workstation = workstation
1072 }
1073 }
1074
1075 appname, ok := params["app name"]
1076 if !ok {
1077 appname = "go-mssqldb"
1078 }
1079 p.appname = appname
1080
1081 appintent, ok := params["applicationintent"]
1082 if ok {
1083 if appintent == "ReadOnly" {
1084 p.typeFlags |= fReadOnlyIntent
1085 }
1086 }
1087
1088 failOverPartner, ok := params["failoverpartner"]
1089 if ok {
1090 p.failOverPartner = failOverPartner
1091 }
1092
1093 failOverPort, ok := params["failoverport"]
1094 if ok {
1095 var err error
1096 p.failOverPort, err = strconv.ParseUint(failOverPort, 0, 16)
1097 if err != nil {
1098 f := "Invalid tcp port '%v': %v"
1099 return p, fmt.Errorf(f, failOverPort, err.Error())
1100 }
1101 }
1102
1103 return p, nil
1104 }
1105
1106 type Auth interface {
1107 InitialBytes() ([]byte, error)
1108 NextBytes([]byte) ([]byte, error)
1109 Free()
1110 }
1111
1112 // SQL Server AlwaysOn Availability Group Listeners are bound by DNS to a
1113 // list of IP addresses. So if there is more than one, try them all and
1114 // use the first one that allows a connection.
1115 func dialConnection(p connectParams) (conn net.Conn, err error) {
1116 var ips []net.IP
1117 ips, err = net.LookupIP(p.host)
1118 if err != nil {
1119 ip := net.ParseIP(p.host)
1120 if ip == nil {
1121 return nil, err
1122 }
1123 ips = []net.IP{ip}
1124 }
1125 if len(ips) == 1 {
1126 d := createDialer(&p)
1127 addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port)))
1128 conn, err = d.Dial(addr)
1129
1130 } else {
1131 //Try Dials in parallel to avoid waiting for timeouts.
1132 connChan := make(chan net.Conn, len(ips))
1133 errChan := make(chan error, len(ips))
1134 portStr := strconv.Itoa(int(p.port))
1135 for _, ip := range ips {
1136 go func(ip net.IP) {
1137 d := createDialer(&p)
1138 addr := net.JoinHostPort(ip.String(), portStr)
1139 conn, err := d.Dial(addr)
1140 if err == nil {
1141 connChan <- conn
1142 } else {
1143 errChan <- err
1144 }
1145 }(ip)
1146 }
1147 // Wait for either the *first* successful connection, or all the errors
1148 wait_loop:
1149 for i, _ := range ips {
1150 select {
1151 case conn = <-connChan:
1152 // Got a connection to use, close any others
1153 go func(n int) {
1154 for i := 0; i < n; i++ {
1155 select {
1156 case conn := <-connChan:
1157 conn.Close()
1158 case <-errChan:
1159 }
1160 }
1161 }(len(ips) - i - 1)
1162 // Remove any earlier errors we may have collected
1163 err = nil
1164 break wait_loop
1165 case err = <-errChan:
1166 }
1167 }
1168 }
1169 // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection
1170 if conn == nil {
1171 f := "Unable to open tcp connection with host '%v:%v': %v"
1172 return nil, fmt.Errorf(f, p.host, p.port, err.Error())
1173 }
1174
1175 return conn, err
1176 }
1177
1178 func connect(log optionalLogger, p connectParams) (res *tdsSession, err error) {
1179 res = nil
1180 // if instance is specified use instance resolution service
1181 if p.instance != "" {
1182 p.instance = strings.ToUpper(p.instance)
1183 instances, err := getInstances(p.host)
1184 if err != nil {
1185 f := "Unable to get instances from Sql Server Browser on host %v: %v"
1186 return nil, fmt.Errorf(f, p.host, err.Error())
1187 }
1188 strport, ok := instances[p.instance]["tcp"]
1189 if !ok {
1190 f := "No instance matching '%v' returned from host '%v'"
1191 return nil, fmt.Errorf(f, p.instance, p.host)
1192 }
1193 p.port, err = strconv.ParseUint(strport, 0, 16)
1194 if err != nil {
1195 f := "Invalid tcp port returned from Sql Server Browser '%v': %v"
1196 return nil, fmt.Errorf(f, strport, err.Error())
1197 }
1198 }
1199
1200 initiate_connection:
1201 conn, err := dialConnection(p)
1202 if err != nil {
1203 return nil, err
1204 }
1205
1206 toconn := NewTimeoutConn(conn, p.conn_timeout)
1207
1208 outbuf := newTdsBuffer(p.packetSize, toconn)
1209 sess := tdsSession{
1210 buf: outbuf,
1211 log: log,
1212 logFlags: p.logFlags,
1213 }
1214
1215 instance_buf := []byte(p.instance)
1216 instance_buf = append(instance_buf, 0) // zero terminate instance name
1217 var encrypt byte
1218 if p.disableEncryption {
1219 encrypt = encryptNotSup
1220 } else if p.encrypt {
1221 encrypt = encryptOn
1222 } else {
1223 encrypt = encryptOff
1224 }
1225 fields := map[uint8][]byte{
1226 preloginVERSION: {0, 0, 0, 0, 0, 0},
1227 preloginENCRYPTION: {encrypt},
1228 preloginINSTOPT: instance_buf,
1229 preloginTHREADID: {0, 0, 0, 0},
1230 preloginMARS: {0}, // MARS disabled
1231 }
1232
1233 err = writePrelogin(outbuf, fields)
1234 if err != nil {
1235 return nil, err
1236 }
1237
1238 fields, err = readPrelogin(outbuf)
1239 if err != nil {
1240 return nil, err
1241 }
1242
1243 encryptBytes, ok := fields[preloginENCRYPTION]
1244 if !ok {
1245 return nil, fmt.Errorf("Encrypt negotiation failed")
1246 }
1247 encrypt = encryptBytes[0]
1248 if p.encrypt && (encrypt == encryptNotSup || encrypt == encryptOff) {
1249 return nil, fmt.Errorf("Server does not support encryption")
1250 }
1251
1252 if encrypt != encryptNotSup {
1253 var config tls.Config
1254 if p.certificate != "" {
1255 pem, err := ioutil.ReadFile(p.certificate)
1256 if err != nil {
1257 f := "Cannot read certificate '%s': %s"
1258 return nil, fmt.Errorf(f, p.certificate, err.Error())
1259 }
1260 certs := x509.NewCertPool()
1261 certs.AppendCertsFromPEM(pem)
1262 config.RootCAs = certs
1263 }
1264 if p.trustServerCertificate {
1265 config.InsecureSkipVerify = true
1266 }
1267 config.ServerName = p.hostInCertificate
1268 outbuf.transport = conn
1269 toconn.buf = outbuf
1270 tlsConn := tls.Client(toconn, &config)
1271 err = tlsConn.Handshake()
1272 toconn.buf = nil
1273 outbuf.transport = tlsConn
1274 if err != nil {
1275 f := "TLS Handshake failed: %s"
1276 return nil, fmt.Errorf(f, err.Error())
1277 }
1278 if encrypt == encryptOff {
1279 outbuf.afterFirst = func() {
1280 outbuf.transport = toconn
1281 }
1282 }
1283 }
1284
1285 login := login{
1286 TDSVersion: verTDS74,
1287 PacketSize: outbuf.PackageSize(),
1288 Database: p.database,
1289 OptionFlags2: fODBC, // to get unlimited TEXTSIZE
1290 HostName: p.workstation,
1291 ServerName: p.host,
1292 AppName: p.appname,
1293 TypeFlags: p.typeFlags,
1294 }
1295 auth, auth_ok := getAuth(p.user, p.password, p.serverSPN, p.workstation)
1296 if auth_ok {
1297 login.SSPI, err = auth.InitialBytes()
1298 if err != nil {
1299 return nil, err
1300 }
1301 login.OptionFlags2 |= fIntSecurity
1302 defer auth.Free()
1303 } else {
1304 login.UserName = p.user
1305 login.Password = p.password
1306 }
1307 err = sendLogin(outbuf, login)
1308 if err != nil {
1309 return nil, err
1310 }
1311
1312 // processing login response
1313 var sspi_msg []byte
1314 continue_login:
1315 tokchan := make(chan tokenStruct, 5)
1316 go processResponse(context.Background(), &sess, tokchan)
1317 success := false
1318 for tok := range tokchan {
1319 switch token := tok.(type) {
1320 case sspiMsg:
1321 sspi_msg, err = auth.NextBytes(token)
1322 if err != nil {
1323 return nil, err
1324 }
1325 case loginAckStruct:
1326 success = true
1327 sess.loginAck = token
1328 case error:
1329 return nil, fmt.Errorf("Login error: %s", token.Error())
1330 case doneStruct:
1331 if token.isError() {
1332 return nil, fmt.Errorf("Login error: %s", token.getError())
1333 }
1334 }
1335 }
1336 if sspi_msg != nil {
1337 outbuf.BeginPacket(packSSPIMessage)
1338 _, err = outbuf.Write(sspi_msg)
1339 if err != nil {
1340 return nil, err
1341 }
1342 err = outbuf.FinishPacket()
1343 if err != nil {
1344 return nil, err
1345 }
1346 sspi_msg = nil
1347 goto continue_login
1348 }
1349 if !success {
1350 return nil, fmt.Errorf("Login failed")
1351 }
1352 if sess.routedServer != "" {
1353 toconn.Close()
1354 p.host = sess.routedServer
1355 p.port = uint64(sess.routedPort)
1356 goto initiate_connection
1357 }
1358 return &sess, nil
1359 }