utils_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "bytes"
  11. "crypto/tls"
  12. "encoding/binary"
  13. "fmt"
  14. "testing"
  15. "time"
  16. )
  17. var testDSNs = []struct {
  18. in string
  19. out string
  20. loc *time.Location
  21. }{
  22. {"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  23. {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC},
  24. {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  25. {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  26. {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  27. {"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC},
  28. {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local},
  29. {"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  30. {"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  31. {"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  32. {"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  33. {"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  34. {"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
  35. }
  36. func TestDSNParser(t *testing.T) {
  37. var cfg *config
  38. var err error
  39. var res string
  40. for i, tst := range testDSNs {
  41. cfg, err = parseDSN(tst.in)
  42. if err != nil {
  43. t.Error(err.Error())
  44. }
  45. // pointer not static
  46. cfg.tls = nil
  47. res = fmt.Sprintf("%+v", cfg)
  48. if res != fmt.Sprintf(tst.out, tst.loc) {
  49. t.Errorf("%d. parseDSN(%q) => %q, want %q", i, tst.in, res, fmt.Sprintf(tst.out, tst.loc))
  50. }
  51. }
  52. }
  53. func TestDSNParserInvalid(t *testing.T) {
  54. var invalidDSNs = []string{
  55. "@net(addr/", // no closing brace
  56. "@tcp(/", // no closing brace
  57. "tcp(/", // no closing brace
  58. "(/", // no closing brace
  59. "net(addr)//", // unescaped
  60. "user:pass@tcp(1.2.3.4:3306)", // no trailing slash
  61. //"/dbname?arg=/some/unescaped/path",
  62. }
  63. for i, tst := range invalidDSNs {
  64. if _, err := parseDSN(tst); err == nil {
  65. t.Errorf("invalid DSN #%d. (%s) didn't error!", i, tst)
  66. }
  67. }
  68. }
  69. func TestDSNWithCustomTLS(t *testing.T) {
  70. baseDSN := "user:password@tcp(localhost:5555)/dbname?tls="
  71. tlsCfg := tls.Config{}
  72. RegisterTLSConfig("utils_test", &tlsCfg)
  73. // Custom TLS is missing
  74. tst := baseDSN + "invalid_tls"
  75. cfg, err := parseDSN(tst)
  76. if err == nil {
  77. t.Errorf("Invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg)
  78. }
  79. tst = baseDSN + "utils_test"
  80. // Custom TLS with a server name
  81. name := "foohost"
  82. tlsCfg.ServerName = name
  83. cfg, err = parseDSN(tst)
  84. if err != nil {
  85. t.Error(err.Error())
  86. } else if cfg.tls.ServerName != name {
  87. t.Errorf("Did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst)
  88. }
  89. // Custom TLS without a server name
  90. name = "localhost"
  91. tlsCfg.ServerName = ""
  92. cfg, err = parseDSN(tst)
  93. if err != nil {
  94. t.Error(err.Error())
  95. } else if cfg.tls.ServerName != name {
  96. t.Errorf("Did not get the correct ServerName (%s) parsing DSN (%s).", name, tst)
  97. }
  98. DeregisterTLSConfig("utils_test")
  99. }
  100. func BenchmarkParseDSN(b *testing.B) {
  101. b.ReportAllocs()
  102. for i := 0; i < b.N; i++ {
  103. for _, tst := range testDSNs {
  104. if _, err := parseDSN(tst.in); err != nil {
  105. b.Error(err.Error())
  106. }
  107. }
  108. }
  109. }
  110. func TestScanNullTime(t *testing.T) {
  111. var scanTests = []struct {
  112. in interface{}
  113. error bool
  114. valid bool
  115. time time.Time
  116. }{
  117. {tDate, false, true, tDate},
  118. {sDate, false, true, tDate},
  119. {[]byte(sDate), false, true, tDate},
  120. {tDateTime, false, true, tDateTime},
  121. {sDateTime, false, true, tDateTime},
  122. {[]byte(sDateTime), false, true, tDateTime},
  123. {tDate0, false, true, tDate0},
  124. {sDate0, false, true, tDate0},
  125. {[]byte(sDate0), false, true, tDate0},
  126. {sDateTime0, false, true, tDate0},
  127. {[]byte(sDateTime0), false, true, tDate0},
  128. {"", true, false, tDate0},
  129. {"1234", true, false, tDate0},
  130. {0, true, false, tDate0},
  131. }
  132. var nt = NullTime{}
  133. var err error
  134. for _, tst := range scanTests {
  135. err = nt.Scan(tst.in)
  136. if (err != nil) != tst.error {
  137. t.Errorf("%v: expected error status %t, got %t", tst.in, tst.error, (err != nil))
  138. }
  139. if nt.Valid != tst.valid {
  140. t.Errorf("%v: expected valid status %t, got %t", tst.in, tst.valid, nt.Valid)
  141. }
  142. if nt.Time != tst.time {
  143. t.Errorf("%v: expected time %v, got %v", tst.in, tst.time, nt.Time)
  144. }
  145. }
  146. }
  147. func TestLengthEncodedInteger(t *testing.T) {
  148. var integerTests = []struct {
  149. num uint64
  150. encoded []byte
  151. }{
  152. {0x0000000000000000, []byte{0x00}},
  153. {0x0000000000000012, []byte{0x12}},
  154. {0x00000000000000fa, []byte{0xfa}},
  155. {0x0000000000000100, []byte{0xfc, 0x00, 0x01}},
  156. {0x0000000000001234, []byte{0xfc, 0x34, 0x12}},
  157. {0x000000000000ffff, []byte{0xfc, 0xff, 0xff}},
  158. {0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}},
  159. {0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}},
  160. {0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}},
  161. {0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}},
  162. {0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}},
  163. {0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
  164. }
  165. for _, tst := range integerTests {
  166. num, isNull, numLen := readLengthEncodedInteger(tst.encoded)
  167. if isNull {
  168. t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num)
  169. }
  170. if num != tst.num {
  171. t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num)
  172. }
  173. if numLen != len(tst.encoded) {
  174. t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen)
  175. }
  176. encoded := appendLengthEncodedInteger(nil, num)
  177. if !bytes.Equal(encoded, tst.encoded) {
  178. t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded)
  179. }
  180. }
  181. }
  182. func TestOldPass(t *testing.T) {
  183. scramble := []byte{9, 8, 7, 6, 5, 4, 3, 2}
  184. vectors := []struct {
  185. pass string
  186. out string
  187. }{
  188. {" pass", "47575c5a435b4251"},
  189. {"pass ", "47575c5a435b4251"},
  190. {"123\t456", "575c47505b5b5559"},
  191. {"C0mpl!ca ted#PASS123", "5d5d554849584a45"},
  192. }
  193. for _, tuple := range vectors {
  194. ours := scrambleOldPassword(scramble, []byte(tuple.pass))
  195. if tuple.out != fmt.Sprintf("%x", ours) {
  196. t.Errorf("Failed old password %q", tuple.pass)
  197. }
  198. }
  199. }
  200. func TestFormatBinaryDateTime(t *testing.T) {
  201. rawDate := [11]byte{}
  202. binary.LittleEndian.PutUint16(rawDate[:2], 1978) // years
  203. rawDate[2] = 12 // months
  204. rawDate[3] = 30 // days
  205. rawDate[4] = 15 // hours
  206. rawDate[5] = 46 // minutes
  207. rawDate[6] = 23 // seconds
  208. binary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds
  209. expect := func(expected string, inlen, outlen uint8) {
  210. actual, _ := formatBinaryDateTime(rawDate[:inlen], outlen, false)
  211. bytes, ok := actual.([]byte)
  212. if !ok {
  213. t.Errorf("formatBinaryDateTime must return []byte, was %T", actual)
  214. }
  215. if string(bytes) != expected {
  216. t.Errorf(
  217. "expected %q, got %q for length in %d, out %d",
  218. bytes, actual, inlen, outlen,
  219. )
  220. }
  221. }
  222. expect("0000-00-00", 0, 10)
  223. expect("0000-00-00 00:00:00", 0, 19)
  224. expect("1978-12-30", 4, 10)
  225. expect("1978-12-30 15:46:23", 7, 19)
  226. expect("1978-12-30 15:46:23.987654", 11, 26)
  227. }
  228. func TestEscapeBackslash(t *testing.T) {
  229. expect := func(expected, value string) {
  230. actual := string(escapeBackslash([]byte{}, []byte(value)))
  231. if actual != expected {
  232. t.Errorf(
  233. "expected %s, got %s",
  234. expected, actual,
  235. )
  236. }
  237. }
  238. expect("foo\\0bar", "foo\x00bar")
  239. expect("foo\\nbar", "foo\nbar")
  240. expect("foo\\rbar", "foo\rbar")
  241. expect("foo\\Zbar", "foo\x1abar")
  242. expect("foo\\\"bar", "foo\"bar")
  243. expect("foo\\\\bar", "foo\\bar")
  244. expect("foo\\'bar", "foo'bar")
  245. }
  246. func TestEscapeQuotes(t *testing.T) {
  247. expect := func(expected, value string) {
  248. actual := string(escapeQuotes([]byte{}, []byte(value)))
  249. if actual != expected {
  250. t.Errorf(
  251. "expected %s, got %s",
  252. expected, actual,
  253. )
  254. }
  255. }
  256. expect("foo\x00bar", "foo\x00bar") // not affected
  257. expect("foo\nbar", "foo\nbar") // not affected
  258. expect("foo\rbar", "foo\rbar") // not affected
  259. expect("foo\x1abar", "foo\x1abar") // not affected
  260. expect("foo''bar", "foo'bar") // affected
  261. expect("foo\"bar", "foo\"bar") // not affected
  262. }