utils.go 20 KB

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