本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

727 lines
17KB

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