utils.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2012 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. "crypto/tls"
  11. "database/sql"
  12. "database/sql/driver"
  13. "encoding/binary"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. )
  23. // Registry for custom tls.Configs
  24. var (
  25. tlsConfigLock sync.RWMutex
  26. tlsConfigRegistry map[string]*tls.Config
  27. )
  28. // RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.
  29. // Use the key as a value in the DSN where tls=value.
  30. //
  31. // Note: The provided tls.Config is exclusively owned by the driver after
  32. // registering it.
  33. //
  34. // rootCertPool := x509.NewCertPool()
  35. // pem, err := ioutil.ReadFile("/path/ca-cert.pem")
  36. // if err != nil {
  37. // log.Fatal(err)
  38. // }
  39. // if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
  40. // log.Fatal("Failed to append PEM.")
  41. // }
  42. // clientCert := make([]tls.Certificate, 0, 1)
  43. // certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem")
  44. // if err != nil {
  45. // log.Fatal(err)
  46. // }
  47. // clientCert = append(clientCert, certs)
  48. // mysql.RegisterTLSConfig("custom", &tls.Config{
  49. // RootCAs: rootCertPool,
  50. // Certificates: clientCert,
  51. // })
  52. // db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom")
  53. //
  54. func RegisterTLSConfig(key string, config *tls.Config) error {
  55. if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" || strings.ToLower(key) == "preferred" {
  56. return fmt.Errorf("key '%s' is reserved", key)
  57. }
  58. tlsConfigLock.Lock()
  59. if tlsConfigRegistry == nil {
  60. tlsConfigRegistry = make(map[string]*tls.Config)
  61. }
  62. tlsConfigRegistry[key] = config
  63. tlsConfigLock.Unlock()
  64. return nil
  65. }
  66. // DeregisterTLSConfig removes the tls.Config associated with key.
  67. func DeregisterTLSConfig(key string) {
  68. tlsConfigLock.Lock()
  69. if tlsConfigRegistry != nil {
  70. delete(tlsConfigRegistry, key)
  71. }
  72. tlsConfigLock.Unlock()
  73. }
  74. func getTLSConfigClone(key string) (config *tls.Config) {
  75. tlsConfigLock.RLock()
  76. if v, ok := tlsConfigRegistry[key]; ok {
  77. config = v.Clone()
  78. }
  79. tlsConfigLock.RUnlock()
  80. return
  81. }
  82. // Returns the bool value of the input.
  83. // The 2nd return value indicates if the input was a valid bool value
  84. func readBool(input string) (value bool, valid bool) {
  85. switch input {
  86. case "1", "true", "TRUE", "True":
  87. return true, true
  88. case "0", "false", "FALSE", "False":
  89. return false, true
  90. }
  91. // Not a valid bool value
  92. return
  93. }
  94. /******************************************************************************
  95. * Time related utils *
  96. ******************************************************************************/
  97. func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
  98. base := "0000-00-00 00:00:00.0000000"
  99. switch len(str) {
  100. case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM"
  101. if str == base[:len(str)] {
  102. return
  103. }
  104. t, err = time.Parse(timeFormat[:len(str)], str)
  105. default:
  106. err = fmt.Errorf("invalid time string: %s", str)
  107. return
  108. }
  109. // Adjust location
  110. if err == nil && loc != time.UTC {
  111. y, mo, d := t.Date()
  112. h, mi, s := t.Clock()
  113. t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
  114. }
  115. return
  116. }
  117. func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
  118. switch num {
  119. case 0:
  120. return time.Time{}, nil
  121. case 4:
  122. return time.Date(
  123. int(binary.LittleEndian.Uint16(data[:2])), // year
  124. time.Month(data[2]), // month
  125. int(data[3]), // day
  126. 0, 0, 0, 0,
  127. loc,
  128. ), nil
  129. case 7:
  130. return time.Date(
  131. int(binary.LittleEndian.Uint16(data[:2])), // year
  132. time.Month(data[2]), // month
  133. int(data[3]), // day
  134. int(data[4]), // hour
  135. int(data[5]), // minutes
  136. int(data[6]), // seconds
  137. 0,
  138. loc,
  139. ), nil
  140. case 11:
  141. return time.Date(
  142. int(binary.LittleEndian.Uint16(data[:2])), // year
  143. time.Month(data[2]), // month
  144. int(data[3]), // day
  145. int(data[4]), // hour
  146. int(data[5]), // minutes
  147. int(data[6]), // seconds
  148. int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
  149. loc,
  150. ), nil
  151. }
  152. return nil, fmt.Errorf("invalid DATETIME packet length %d", num)
  153. }
  154. // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
  155. // if the DATE or DATETIME has the zero value.
  156. // It must never be changed.
  157. // The current behavior depends on database/sql copying the result.
  158. var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
  159. const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
  160. const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
  161. func appendMicrosecs(dst, src []byte, decimals int) []byte {
  162. if decimals <= 0 {
  163. return dst
  164. }
  165. if len(src) == 0 {
  166. return append(dst, ".000000"[:decimals+1]...)
  167. }
  168. microsecs := binary.LittleEndian.Uint32(src[:4])
  169. p1 := byte(microsecs / 10000)
  170. microsecs -= 10000 * uint32(p1)
  171. p2 := byte(microsecs / 100)
  172. microsecs -= 100 * uint32(p2)
  173. p3 := byte(microsecs)
  174. switch decimals {
  175. default:
  176. return append(dst, '.',
  177. digits10[p1], digits01[p1],
  178. digits10[p2], digits01[p2],
  179. digits10[p3], digits01[p3],
  180. )
  181. case 1:
  182. return append(dst, '.',
  183. digits10[p1],
  184. )
  185. case 2:
  186. return append(dst, '.',
  187. digits10[p1], digits01[p1],
  188. )
  189. case 3:
  190. return append(dst, '.',
  191. digits10[p1], digits01[p1],
  192. digits10[p2],
  193. )
  194. case 4:
  195. return append(dst, '.',
  196. digits10[p1], digits01[p1],
  197. digits10[p2], digits01[p2],
  198. )
  199. case 5:
  200. return append(dst, '.',
  201. digits10[p1], digits01[p1],
  202. digits10[p2], digits01[p2],
  203. digits10[p3],
  204. )
  205. }
  206. }
  207. func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {
  208. // length expects the deterministic length of the zero value,
  209. // negative time and 100+ hours are automatically added if needed
  210. if len(src) == 0 {
  211. return zeroDateTime[:length], nil
  212. }
  213. var dst []byte // return value
  214. var p1, p2, p3 byte // current digit pair
  215. switch length {
  216. case 10, 19, 21, 22, 23, 24, 25, 26:
  217. default:
  218. t := "DATE"
  219. if length > 10 {
  220. t += "TIME"
  221. }
  222. return nil, fmt.Errorf("illegal %s length %d", t, length)
  223. }
  224. switch len(src) {
  225. case 4, 7, 11:
  226. default:
  227. t := "DATE"
  228. if length > 10 {
  229. t += "TIME"
  230. }
  231. return nil, fmt.Errorf("illegal %s packet length %d", t, len(src))
  232. }
  233. dst = make([]byte, 0, length)
  234. // start with the date
  235. year := binary.LittleEndian.Uint16(src[:2])
  236. pt := year / 100
  237. p1 = byte(year - 100*uint16(pt))
  238. p2, p3 = src[2], src[3]
  239. dst = append(dst,
  240. digits10[pt], digits01[pt],
  241. digits10[p1], digits01[p1], '-',
  242. digits10[p2], digits01[p2], '-',
  243. digits10[p3], digits01[p3],
  244. )
  245. if length == 10 {
  246. return dst, nil
  247. }
  248. if len(src) == 4 {
  249. return append(dst, zeroDateTime[10:length]...), nil
  250. }
  251. dst = append(dst, ' ')
  252. p1 = src[4] // hour
  253. src = src[5:]
  254. // p1 is 2-digit hour, src is after hour
  255. p2, p3 = src[0], src[1]
  256. dst = append(dst,
  257. digits10[p1], digits01[p1], ':',
  258. digits10[p2], digits01[p2], ':',
  259. digits10[p3], digits01[p3],
  260. )
  261. return appendMicrosecs(dst, src[2:], int(length)-20), nil
  262. }
  263. func formatBinaryTime(src []byte, length uint8) (driver.Value, error) {
  264. // length expects the deterministic length of the zero value,
  265. // negative time and 100+ hours are automatically added if needed
  266. if len(src) == 0 {
  267. return zeroDateTime[11 : 11+length], nil
  268. }
  269. var dst []byte // return value
  270. switch length {
  271. case
  272. 8, // time (can be up to 10 when negative and 100+ hours)
  273. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  274. default:
  275. return nil, fmt.Errorf("illegal TIME length %d", length)
  276. }
  277. switch len(src) {
  278. case 8, 12:
  279. default:
  280. return nil, fmt.Errorf("invalid TIME packet length %d", len(src))
  281. }
  282. // +2 to enable negative time and 100+ hours
  283. dst = make([]byte, 0, length+2)
  284. if src[0] == 1 {
  285. dst = append(dst, '-')
  286. }
  287. days := binary.LittleEndian.Uint32(src[1:5])
  288. hours := int64(days)*24 + int64(src[5])
  289. if hours >= 100 {
  290. dst = strconv.AppendInt(dst, hours, 10)
  291. } else {
  292. dst = append(dst, digits10[hours], digits01[hours])
  293. }
  294. min, sec := src[6], src[7]
  295. dst = append(dst, ':',
  296. digits10[min], digits01[min], ':',
  297. digits10[sec], digits01[sec],
  298. )
  299. return appendMicrosecs(dst, src[8:], int(length)-9), nil
  300. }
  301. /******************************************************************************
  302. * Convert from and to bytes *
  303. ******************************************************************************/
  304. func uint64ToBytes(n uint64) []byte {
  305. return []byte{
  306. byte(n),
  307. byte(n >> 8),
  308. byte(n >> 16),
  309. byte(n >> 24),
  310. byte(n >> 32),
  311. byte(n >> 40),
  312. byte(n >> 48),
  313. byte(n >> 56),
  314. }
  315. }
  316. func uint64ToString(n uint64) []byte {
  317. var a [20]byte
  318. i := 20
  319. // U+0030 = 0
  320. // ...
  321. // U+0039 = 9
  322. var q uint64
  323. for n >= 10 {
  324. i--
  325. q = n / 10
  326. a[i] = uint8(n-q*10) + 0x30
  327. n = q
  328. }
  329. i--
  330. a[i] = uint8(n) + 0x30
  331. return a[i:]
  332. }
  333. // treats string value as unsigned integer representation
  334. func stringToInt(b []byte) int {
  335. val := 0
  336. for i := range b {
  337. val *= 10
  338. val += int(b[i] - 0x30)
  339. }
  340. return val
  341. }
  342. // returns the string read as a bytes slice, wheter the value is NULL,
  343. // the number of bytes read and an error, in case the string is longer than
  344. // the input slice
  345. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  346. // Get length
  347. num, isNull, n := readLengthEncodedInteger(b)
  348. if num < 1 {
  349. return b[n:n], isNull, n, nil
  350. }
  351. n += int(num)
  352. // Check data length
  353. if len(b) >= n {
  354. return b[n-int(num) : n : n], false, n, nil
  355. }
  356. return nil, false, n, io.EOF
  357. }
  358. // returns the number of bytes skipped and an error, in case the string is
  359. // longer than the input slice
  360. func skipLengthEncodedString(b []byte) (int, error) {
  361. // Get length
  362. num, _, n := readLengthEncodedInteger(b)
  363. if num < 1 {
  364. return n, nil
  365. }
  366. n += int(num)
  367. // Check data length
  368. if len(b) >= n {
  369. return n, nil
  370. }
  371. return n, io.EOF
  372. }
  373. // returns the number read, whether the value is NULL and the number of bytes read
  374. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  375. // See issue #349
  376. if len(b) == 0 {
  377. return 0, true, 1
  378. }
  379. switch b[0] {
  380. // 251: NULL
  381. case 0xfb:
  382. return 0, true, 1
  383. // 252: value of following 2
  384. case 0xfc:
  385. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  386. // 253: value of following 3
  387. case 0xfd:
  388. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  389. // 254: value of following 8
  390. case 0xfe:
  391. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  392. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  393. uint64(b[7])<<48 | uint64(b[8])<<56,
  394. false, 9
  395. }
  396. // 0-250: value of first byte
  397. return uint64(b[0]), false, 1
  398. }
  399. // encodes a uint64 value and appends it to the given bytes slice
  400. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  401. switch {
  402. case n <= 250:
  403. return append(b, byte(n))
  404. case n <= 0xffff:
  405. return append(b, 0xfc, byte(n), byte(n>>8))
  406. case n <= 0xffffff:
  407. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  408. }
  409. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  410. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  411. }
  412. // reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize.
  413. // If cap(buf) is not enough, reallocate new buffer.
  414. func reserveBuffer(buf []byte, appendSize int) []byte {
  415. newSize := len(buf) + appendSize
  416. if cap(buf) < newSize {
  417. // Grow buffer exponentially
  418. newBuf := make([]byte, len(buf)*2+appendSize)
  419. copy(newBuf, buf)
  420. buf = newBuf
  421. }
  422. return buf[:newSize]
  423. }
  424. // escapeBytesBackslash escapes []byte with backslashes (\)
  425. // This escapes the contents of a string (provided as []byte) by adding backslashes before special
  426. // characters, and turning others into specific escape sequences, such as
  427. // turning newlines into \n and null bytes into \0.
  428. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
  429. func escapeBytesBackslash(buf, v []byte) []byte {
  430. pos := len(buf)
  431. buf = reserveBuffer(buf, len(v)*2)
  432. for _, c := range v {
  433. switch c {
  434. case '\x00':
  435. buf[pos] = '\\'
  436. buf[pos+1] = '0'
  437. pos += 2
  438. case '\n':
  439. buf[pos] = '\\'
  440. buf[pos+1] = 'n'
  441. pos += 2
  442. case '\r':
  443. buf[pos] = '\\'
  444. buf[pos+1] = 'r'
  445. pos += 2
  446. case '\x1a':
  447. buf[pos] = '\\'
  448. buf[pos+1] = 'Z'
  449. pos += 2
  450. case '\'':
  451. buf[pos] = '\\'
  452. buf[pos+1] = '\''
  453. pos += 2
  454. case '"':
  455. buf[pos] = '\\'
  456. buf[pos+1] = '"'
  457. pos += 2
  458. case '\\':
  459. buf[pos] = '\\'
  460. buf[pos+1] = '\\'
  461. pos += 2
  462. default:
  463. buf[pos] = c
  464. pos++
  465. }
  466. }
  467. return buf[:pos]
  468. }
  469. // escapeStringBackslash is similar to escapeBytesBackslash but for string.
  470. func escapeStringBackslash(buf []byte, v string) []byte {
  471. pos := len(buf)
  472. buf = reserveBuffer(buf, len(v)*2)
  473. for i := 0; i < len(v); i++ {
  474. c := v[i]
  475. switch c {
  476. case '\x00':
  477. buf[pos] = '\\'
  478. buf[pos+1] = '0'
  479. pos += 2
  480. case '\n':
  481. buf[pos] = '\\'
  482. buf[pos+1] = 'n'
  483. pos += 2
  484. case '\r':
  485. buf[pos] = '\\'
  486. buf[pos+1] = 'r'
  487. pos += 2
  488. case '\x1a':
  489. buf[pos] = '\\'
  490. buf[pos+1] = 'Z'
  491. pos += 2
  492. case '\'':
  493. buf[pos] = '\\'
  494. buf[pos+1] = '\''
  495. pos += 2
  496. case '"':
  497. buf[pos] = '\\'
  498. buf[pos+1] = '"'
  499. pos += 2
  500. case '\\':
  501. buf[pos] = '\\'
  502. buf[pos+1] = '\\'
  503. pos += 2
  504. default:
  505. buf[pos] = c
  506. pos++
  507. }
  508. }
  509. return buf[:pos]
  510. }
  511. // escapeBytesQuotes escapes apostrophes in []byte by doubling them up.
  512. // This escapes the contents of a string by doubling up any apostrophes that
  513. // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
  514. // effect on the server.
  515. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
  516. func escapeBytesQuotes(buf, v []byte) []byte {
  517. pos := len(buf)
  518. buf = reserveBuffer(buf, len(v)*2)
  519. for _, c := range v {
  520. if c == '\'' {
  521. buf[pos] = '\''
  522. buf[pos+1] = '\''
  523. pos += 2
  524. } else {
  525. buf[pos] = c
  526. pos++
  527. }
  528. }
  529. return buf[:pos]
  530. }
  531. // escapeStringQuotes is similar to escapeBytesQuotes but for string.
  532. func escapeStringQuotes(buf []byte, v string) []byte {
  533. pos := len(buf)
  534. buf = reserveBuffer(buf, len(v)*2)
  535. for i := 0; i < len(v); i++ {
  536. c := v[i]
  537. if c == '\'' {
  538. buf[pos] = '\''
  539. buf[pos+1] = '\''
  540. pos += 2
  541. } else {
  542. buf[pos] = c
  543. pos++
  544. }
  545. }
  546. return buf[:pos]
  547. }
  548. /******************************************************************************
  549. * Sync utils *
  550. ******************************************************************************/
  551. // noCopy may be embedded into structs which must not be copied
  552. // after the first use.
  553. //
  554. // See https://github.com/golang/go/issues/8005#issuecomment-190753527
  555. // for details.
  556. type noCopy struct{}
  557. // Lock is a no-op used by -copylocks checker from `go vet`.
  558. func (*noCopy) Lock() {}
  559. // atomicBool is a wrapper around uint32 for usage as a boolean value with
  560. // atomic access.
  561. type atomicBool struct {
  562. _noCopy noCopy
  563. value uint32
  564. }
  565. // IsSet returns whether the current boolean value is true
  566. func (ab *atomicBool) IsSet() bool {
  567. return atomic.LoadUint32(&ab.value) > 0
  568. }
  569. // Set sets the value of the bool regardless of the previous value
  570. func (ab *atomicBool) Set(value bool) {
  571. if value {
  572. atomic.StoreUint32(&ab.value, 1)
  573. } else {
  574. atomic.StoreUint32(&ab.value, 0)
  575. }
  576. }
  577. // TrySet sets the value of the bool and returns whether the value changed
  578. func (ab *atomicBool) TrySet(value bool) bool {
  579. if value {
  580. return atomic.SwapUint32(&ab.value, 1) == 0
  581. }
  582. return atomic.SwapUint32(&ab.value, 0) > 0
  583. }
  584. // atomicError is a wrapper for atomically accessed error values
  585. type atomicError struct {
  586. _noCopy noCopy
  587. value atomic.Value
  588. }
  589. // Set sets the error value regardless of the previous value.
  590. // The value must not be nil
  591. func (ae *atomicError) Set(value error) {
  592. ae.value.Store(value)
  593. }
  594. // Value returns the current error value
  595. func (ae *atomicError) Value() error {
  596. if v := ae.value.Load(); v != nil {
  597. // this will panic if the value doesn't implement the error interface
  598. return v.(error)
  599. }
  600. return nil
  601. }
  602. func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {
  603. dargs := make([]driver.Value, len(named))
  604. for n, param := range named {
  605. if len(param.Name) > 0 {
  606. // TODO: support the use of Named Parameters #561
  607. return nil, errors.New("mysql: driver does not support the use of Named Parameters")
  608. }
  609. dargs[n] = param.Value
  610. }
  611. return dargs, nil
  612. }
  613. func mapIsolationLevel(level driver.IsolationLevel) (string, error) {
  614. switch sql.IsolationLevel(level) {
  615. case sql.LevelRepeatableRead:
  616. return "REPEATABLE READ", nil
  617. case sql.LevelReadCommitted:
  618. return "READ COMMITTED", nil
  619. case sql.LevelReadUncommitted:
  620. return "READ UNCOMMITTED", nil
  621. case sql.LevelSerializable:
  622. return "SERIALIZABLE", nil
  623. default:
  624. return "", fmt.Errorf("mysql: unsupported isolation level: %v", level)
  625. }
  626. }