utils.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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/tls"
  12. "database/sql/driver"
  13. "encoding/binary"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "net"
  18. "net/url"
  19. "strings"
  20. "time"
  21. )
  22. var (
  23. tlsConfigRegister map[string]*tls.Config // Register for custom tls.Configs
  24. errInvalidDSNUnescaped = errors.New("Invalid DSN: Did you forget to escape a param value?")
  25. errInvalidDSNAddr = errors.New("Invalid DSN: Network Address not terminated (missing closing brace)")
  26. errInvalidDSNNoSlash = errors.New("Invalid DSN: Missing the slash separating the database name")
  27. )
  28. func init() {
  29. tlsConfigRegister = make(map[string]*tls.Config)
  30. }
  31. // RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.
  32. // Use the key as a value in the DSN where tls=value.
  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" {
  56. return fmt.Errorf("Key '%s' is reserved", key)
  57. }
  58. tlsConfigRegister[key] = config
  59. return nil
  60. }
  61. // DeregisterTLSConfig removes the tls.Config associated with key.
  62. func DeregisterTLSConfig(key string) {
  63. delete(tlsConfigRegister, key)
  64. }
  65. // parseDSN parses the DSN string to a config
  66. func parseDSN(dsn string) (cfg *config, err error) {
  67. // New config with some default values
  68. cfg = &config{
  69. loc: time.UTC,
  70. collation: defaultCollation,
  71. }
  72. // TODO: use strings.IndexByte when we can depend on Go 1.2
  73. // [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]
  74. // Find the last '/' (since the password or the net addr might contain a '/')
  75. foundSlash := false
  76. for i := len(dsn) - 1; i >= 0; i-- {
  77. if dsn[i] == '/' {
  78. foundSlash = true
  79. var j, k int
  80. // left part is empty if i <= 0
  81. if i > 0 {
  82. // [username[:password]@][protocol[(address)]]
  83. // Find the last '@' in dsn[:i]
  84. for j = i; j >= 0; j-- {
  85. if dsn[j] == '@' {
  86. // username[:password]
  87. // Find the first ':' in dsn[:j]
  88. for k = 0; k < j; k++ {
  89. if dsn[k] == ':' {
  90. cfg.passwd = dsn[k+1 : j]
  91. break
  92. }
  93. }
  94. cfg.user = dsn[:k]
  95. break
  96. }
  97. }
  98. // [protocol[(address)]]
  99. // Find the first '(' in dsn[j+1:i]
  100. for k = j + 1; k < i; k++ {
  101. if dsn[k] == '(' {
  102. // dsn[i-1] must be == ')' if an address is specified
  103. if dsn[i-1] != ')' {
  104. if strings.ContainsRune(dsn[k+1:i], ')') {
  105. return nil, errInvalidDSNUnescaped
  106. }
  107. return nil, errInvalidDSNAddr
  108. }
  109. cfg.addr = dsn[k+1 : i-1]
  110. break
  111. }
  112. }
  113. cfg.net = dsn[j+1 : k]
  114. }
  115. // dbname[?param1=value1&...&paramN=valueN]
  116. // Find the first '?' in dsn[i+1:]
  117. for j = i + 1; j < len(dsn); j++ {
  118. if dsn[j] == '?' {
  119. if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
  120. return
  121. }
  122. break
  123. }
  124. }
  125. cfg.dbname = dsn[i+1 : j]
  126. break
  127. }
  128. }
  129. if !foundSlash && len(dsn) > 0 {
  130. return nil, errInvalidDSNNoSlash
  131. }
  132. // Set default network if empty
  133. if cfg.net == "" {
  134. cfg.net = "tcp"
  135. }
  136. // Set default address if empty
  137. if cfg.addr == "" {
  138. switch cfg.net {
  139. case "tcp":
  140. cfg.addr = "127.0.0.1:3306"
  141. case "unix":
  142. cfg.addr = "/tmp/mysql.sock"
  143. default:
  144. return nil, errors.New("Default addr for network '" + cfg.net + "' unknown")
  145. }
  146. }
  147. return
  148. }
  149. // parseDSNParams parses the DSN "query string"
  150. // Values must be url.QueryEscape'ed
  151. func parseDSNParams(cfg *config, params string) (err error) {
  152. for _, v := range strings.Split(params, "&") {
  153. param := strings.SplitN(v, "=", 2)
  154. if len(param) != 2 {
  155. continue
  156. }
  157. // cfg params
  158. switch value := param[1]; param[0] {
  159. // Enable client side placeholder substitution
  160. case "interpolateParams":
  161. var isBool bool
  162. cfg.interpolateParams, isBool = readBool(value)
  163. if !isBool {
  164. return fmt.Errorf("Invalid Bool value: %s", value)
  165. }
  166. // Disable INFILE whitelist / enable all files
  167. case "allowAllFiles":
  168. var isBool bool
  169. cfg.allowAllFiles, isBool = readBool(value)
  170. if !isBool {
  171. return fmt.Errorf("Invalid Bool value: %s", value)
  172. }
  173. // Use old authentication mode (pre MySQL 4.1)
  174. case "allowOldPasswords":
  175. var isBool bool
  176. cfg.allowOldPasswords, isBool = readBool(value)
  177. if !isBool {
  178. return fmt.Errorf("Invalid Bool value: %s", value)
  179. }
  180. // Switch "rowsAffected" mode
  181. case "clientFoundRows":
  182. var isBool bool
  183. cfg.clientFoundRows, isBool = readBool(value)
  184. if !isBool {
  185. return fmt.Errorf("Invalid Bool value: %s", value)
  186. }
  187. // Collation
  188. case "collation":
  189. collation, ok := collations[value]
  190. if !ok {
  191. // Note possibility for false negatives:
  192. // could be triggered although the collation is valid if the
  193. // collations map does not contain entries the server supports.
  194. err = errors.New("unknown collation")
  195. return
  196. }
  197. cfg.collation = collation
  198. break
  199. case "columnsWithAlias":
  200. var isBool bool
  201. cfg.columnsWithAlias, isBool = readBool(value)
  202. if !isBool {
  203. return fmt.Errorf("Invalid Bool value: %s", value)
  204. }
  205. // Time Location
  206. case "loc":
  207. if value, err = url.QueryUnescape(value); err != nil {
  208. return
  209. }
  210. cfg.loc, err = time.LoadLocation(value)
  211. if err != nil {
  212. return
  213. }
  214. // Dial Timeout
  215. case "timeout":
  216. cfg.timeout, err = time.ParseDuration(value)
  217. if err != nil {
  218. return
  219. }
  220. // TLS-Encryption
  221. case "tls":
  222. boolValue, isBool := readBool(value)
  223. if isBool {
  224. if boolValue {
  225. cfg.tls = &tls.Config{}
  226. }
  227. } else {
  228. if strings.ToLower(value) == "skip-verify" {
  229. cfg.tls = &tls.Config{InsecureSkipVerify: true}
  230. } else if tlsConfig, ok := tlsConfigRegister[value]; ok {
  231. if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
  232. host, _, err := net.SplitHostPort(cfg.addr)
  233. if err == nil {
  234. tlsConfig.ServerName = host
  235. }
  236. }
  237. cfg.tls = tlsConfig
  238. } else {
  239. return fmt.Errorf("Invalid value / unknown config name: %s", value)
  240. }
  241. }
  242. default:
  243. // lazy init
  244. if cfg.params == nil {
  245. cfg.params = make(map[string]string)
  246. }
  247. if cfg.params[param[0]], err = url.QueryUnescape(value); err != nil {
  248. return
  249. }
  250. }
  251. }
  252. return
  253. }
  254. // Returns the bool value of the input.
  255. // The 2nd return value indicates if the input was a valid bool value
  256. func readBool(input string) (value bool, valid bool) {
  257. switch input {
  258. case "1", "true", "TRUE", "True":
  259. return true, true
  260. case "0", "false", "FALSE", "False":
  261. return false, true
  262. }
  263. // Not a valid bool value
  264. return
  265. }
  266. /******************************************************************************
  267. * Authentication *
  268. ******************************************************************************/
  269. // Encrypt password using 4.1+ method
  270. func scramblePassword(scramble, password []byte) []byte {
  271. if len(password) == 0 {
  272. return nil
  273. }
  274. // stage1Hash = SHA1(password)
  275. crypt := sha1.New()
  276. crypt.Write(password)
  277. stage1 := crypt.Sum(nil)
  278. // scrambleHash = SHA1(scramble + SHA1(stage1Hash))
  279. // inner Hash
  280. crypt.Reset()
  281. crypt.Write(stage1)
  282. hash := crypt.Sum(nil)
  283. // outer Hash
  284. crypt.Reset()
  285. crypt.Write(scramble)
  286. crypt.Write(hash)
  287. scramble = crypt.Sum(nil)
  288. // token = scrambleHash XOR stage1Hash
  289. for i := range scramble {
  290. scramble[i] ^= stage1[i]
  291. }
  292. return scramble
  293. }
  294. // Encrypt password using pre 4.1 (old password) method
  295. // https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c
  296. type myRnd struct {
  297. seed1, seed2 uint32
  298. }
  299. const myRndMaxVal = 0x3FFFFFFF
  300. // Pseudo random number generator
  301. func newMyRnd(seed1, seed2 uint32) *myRnd {
  302. return &myRnd{
  303. seed1: seed1 % myRndMaxVal,
  304. seed2: seed2 % myRndMaxVal,
  305. }
  306. }
  307. // Tested to be equivalent to MariaDB's floating point variant
  308. // http://play.golang.org/p/QHvhd4qved
  309. // http://play.golang.org/p/RG0q4ElWDx
  310. func (r *myRnd) NextByte() byte {
  311. r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal
  312. r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal
  313. return byte(uint64(r.seed1) * 31 / myRndMaxVal)
  314. }
  315. // Generate binary hash from byte string using insecure pre 4.1 method
  316. func pwHash(password []byte) (result [2]uint32) {
  317. var add uint32 = 7
  318. var tmp uint32
  319. result[0] = 1345345333
  320. result[1] = 0x12345671
  321. for _, c := range password {
  322. // skip spaces and tabs in password
  323. if c == ' ' || c == '\t' {
  324. continue
  325. }
  326. tmp = uint32(c)
  327. result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8)
  328. result[1] += (result[1] << 8) ^ result[0]
  329. add += tmp
  330. }
  331. // Remove sign bit (1<<31)-1)
  332. result[0] &= 0x7FFFFFFF
  333. result[1] &= 0x7FFFFFFF
  334. return
  335. }
  336. // Encrypt password using insecure pre 4.1 method
  337. func scrambleOldPassword(scramble, password []byte) []byte {
  338. if len(password) == 0 {
  339. return nil
  340. }
  341. scramble = scramble[:8]
  342. hashPw := pwHash(password)
  343. hashSc := pwHash(scramble)
  344. r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1])
  345. var out [8]byte
  346. for i := range out {
  347. out[i] = r.NextByte() + 64
  348. }
  349. mask := r.NextByte()
  350. for i := range out {
  351. out[i] ^= mask
  352. }
  353. return out[:]
  354. }
  355. /******************************************************************************
  356. * Time related utils *
  357. ******************************************************************************/
  358. // NullTime represents a time.Time that may be NULL.
  359. // NullTime implements the Scanner interface so
  360. // it can be used as a scan destination:
  361. //
  362. // var nt NullTime
  363. // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
  364. // ...
  365. // if nt.Valid {
  366. // // use nt.Time
  367. // } else {
  368. // // NULL value
  369. // }
  370. //
  371. // This NullTime implementation is not driver-specific
  372. type NullTime struct {
  373. Time time.Time
  374. Valid bool // Valid is true if Time is not NULL
  375. }
  376. // Scan implements the Scanner interface.
  377. // The value type must be time.Time or string / []byte (formatted time-string),
  378. // otherwise Scan fails.
  379. func (nt *NullTime) Scan(value interface{}) (err error) {
  380. if value == nil {
  381. nt.Time, nt.Valid = time.Time{}, false
  382. return
  383. }
  384. switch v := value.(type) {
  385. case time.Time:
  386. nt.Time, nt.Valid = v, true
  387. return
  388. case []byte:
  389. nt.Time, err = parseDateTime(string(v), time.UTC)
  390. nt.Valid = (err == nil)
  391. return
  392. case string:
  393. nt.Time, err = parseDateTime(v, time.UTC)
  394. nt.Valid = (err == nil)
  395. return
  396. }
  397. nt.Valid = false
  398. return fmt.Errorf("Can't convert %T to time.Time", value)
  399. }
  400. // Value implements the driver Valuer interface.
  401. func (nt NullTime) Value() (driver.Value, error) {
  402. if !nt.Valid {
  403. return nil, nil
  404. }
  405. return nt.Time, nil
  406. }
  407. func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
  408. base := "0000-00-00 00:00:00.0000000"
  409. switch len(str) {
  410. case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM"
  411. if str == base[:len(str)] {
  412. return
  413. }
  414. t, err = time.Parse(timeFormat[:len(str)], str)
  415. default:
  416. err = fmt.Errorf("Invalid Time-String: %s", str)
  417. return
  418. }
  419. // Adjust location
  420. if err == nil && loc != time.UTC {
  421. y, mo, d := t.Date()
  422. h, mi, s := t.Clock()
  423. t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
  424. }
  425. return
  426. }
  427. func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
  428. switch num {
  429. case 0:
  430. return time.Time{}, nil
  431. case 4:
  432. return time.Date(
  433. int(binary.LittleEndian.Uint16(data[:2])), // year
  434. time.Month(data[2]), // month
  435. int(data[3]), // day
  436. 0, 0, 0, 0,
  437. loc,
  438. ), nil
  439. case 7:
  440. return time.Date(
  441. int(binary.LittleEndian.Uint16(data[:2])), // year
  442. time.Month(data[2]), // month
  443. int(data[3]), // day
  444. int(data[4]), // hour
  445. int(data[5]), // minutes
  446. int(data[6]), // seconds
  447. 0,
  448. loc,
  449. ), nil
  450. case 11:
  451. return time.Date(
  452. int(binary.LittleEndian.Uint16(data[:2])), // year
  453. time.Month(data[2]), // month
  454. int(data[3]), // day
  455. int(data[4]), // hour
  456. int(data[5]), // minutes
  457. int(data[6]), // seconds
  458. int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
  459. loc,
  460. ), nil
  461. }
  462. return nil, fmt.Errorf("Invalid DATETIME-packet length %d", num)
  463. }
  464. // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
  465. // if the DATE or DATETIME has the zero value.
  466. // It must never be changed.
  467. // The current behavior depends on database/sql copying the result.
  468. var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
  469. func formatBinaryDateTime(src []byte, length uint8, justTime bool) (driver.Value, error) {
  470. // length expects the deterministic length of the zero value,
  471. // negative time and 100+ hours are automatically added if needed
  472. const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
  473. const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
  474. if len(src) == 0 {
  475. if justTime {
  476. return zeroDateTime[11 : 11+length], nil
  477. }
  478. return zeroDateTime[:length], nil
  479. }
  480. var dst []byte // return value
  481. var pt, p1, p2, p3 byte // current digit pair
  482. var zOffs byte // offset of value in zeroDateTime
  483. if justTime {
  484. switch length {
  485. case
  486. 8, // time (can be up to 10 when negative and 100+ hours)
  487. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  488. default:
  489. return nil, fmt.Errorf("illegal TIME length %d", length)
  490. }
  491. switch len(src) {
  492. case 8, 12:
  493. default:
  494. return nil, fmt.Errorf("Invalid TIME-packet length %d", len(src))
  495. }
  496. // +2 to enable negative time and 100+ hours
  497. dst = make([]byte, 0, length+2)
  498. if src[0] == 1 {
  499. dst = append(dst, '-')
  500. }
  501. if src[1] != 0 {
  502. hour := uint16(src[1])*24 + uint16(src[5])
  503. pt = byte(hour / 100)
  504. p1 = byte(hour - 100*uint16(pt))
  505. dst = append(dst, digits01[pt])
  506. } else {
  507. p1 = src[5]
  508. }
  509. zOffs = 11
  510. src = src[6:]
  511. } else {
  512. switch length {
  513. case 10, 19, 21, 22, 23, 24, 25, 26:
  514. default:
  515. t := "DATE"
  516. if length > 10 {
  517. t += "TIME"
  518. }
  519. return nil, fmt.Errorf("illegal %s length %d", t, length)
  520. }
  521. switch len(src) {
  522. case 4, 7, 11:
  523. default:
  524. t := "DATE"
  525. if length > 10 {
  526. t += "TIME"
  527. }
  528. return nil, fmt.Errorf("illegal %s-packet length %d", t, len(src))
  529. }
  530. dst = make([]byte, 0, length)
  531. // start with the date
  532. year := binary.LittleEndian.Uint16(src[:2])
  533. pt = byte(year / 100)
  534. p1 = byte(year - 100*uint16(pt))
  535. p2, p3 = src[2], src[3]
  536. dst = append(dst,
  537. digits10[pt], digits01[pt],
  538. digits10[p1], digits01[p1], '-',
  539. digits10[p2], digits01[p2], '-',
  540. digits10[p3], digits01[p3],
  541. )
  542. if length == 10 {
  543. return dst, nil
  544. }
  545. if len(src) == 4 {
  546. return append(dst, zeroDateTime[10:length]...), nil
  547. }
  548. dst = append(dst, ' ')
  549. p1 = src[4] // hour
  550. src = src[5:]
  551. }
  552. // p1 is 2-digit hour, src is after hour
  553. p2, p3 = src[0], src[1]
  554. dst = append(dst,
  555. digits10[p1], digits01[p1], ':',
  556. digits10[p2], digits01[p2], ':',
  557. digits10[p3], digits01[p3],
  558. )
  559. if length <= byte(len(dst)) {
  560. return dst, nil
  561. }
  562. src = src[2:]
  563. if len(src) == 0 {
  564. return append(dst, zeroDateTime[19:zOffs+length]...), nil
  565. }
  566. microsecs := binary.LittleEndian.Uint32(src[:4])
  567. p1 = byte(microsecs / 10000)
  568. microsecs -= 10000 * uint32(p1)
  569. p2 = byte(microsecs / 100)
  570. microsecs -= 100 * uint32(p2)
  571. p3 = byte(microsecs)
  572. switch decimals := zOffs + length - 20; decimals {
  573. default:
  574. return append(dst, '.',
  575. digits10[p1], digits01[p1],
  576. digits10[p2], digits01[p2],
  577. digits10[p3], digits01[p3],
  578. ), nil
  579. case 1:
  580. return append(dst, '.',
  581. digits10[p1],
  582. ), nil
  583. case 2:
  584. return append(dst, '.',
  585. digits10[p1], digits01[p1],
  586. ), nil
  587. case 3:
  588. return append(dst, '.',
  589. digits10[p1], digits01[p1],
  590. digits10[p2],
  591. ), nil
  592. case 4:
  593. return append(dst, '.',
  594. digits10[p1], digits01[p1],
  595. digits10[p2], digits01[p2],
  596. ), nil
  597. case 5:
  598. return append(dst, '.',
  599. digits10[p1], digits01[p1],
  600. digits10[p2], digits01[p2],
  601. digits10[p3],
  602. ), nil
  603. }
  604. }
  605. /******************************************************************************
  606. * Convert from and to bytes *
  607. ******************************************************************************/
  608. func uint64ToBytes(n uint64) []byte {
  609. return []byte{
  610. byte(n),
  611. byte(n >> 8),
  612. byte(n >> 16),
  613. byte(n >> 24),
  614. byte(n >> 32),
  615. byte(n >> 40),
  616. byte(n >> 48),
  617. byte(n >> 56),
  618. }
  619. }
  620. func uint64ToString(n uint64) []byte {
  621. var a [20]byte
  622. i := 20
  623. // U+0030 = 0
  624. // ...
  625. // U+0039 = 9
  626. var q uint64
  627. for n >= 10 {
  628. i--
  629. q = n / 10
  630. a[i] = uint8(n-q*10) + 0x30
  631. n = q
  632. }
  633. i--
  634. a[i] = uint8(n) + 0x30
  635. return a[i:]
  636. }
  637. // treats string value as unsigned integer representation
  638. func stringToInt(b []byte) int {
  639. val := 0
  640. for i := range b {
  641. val *= 10
  642. val += int(b[i] - 0x30)
  643. }
  644. return val
  645. }
  646. // returns the string read as a bytes slice, wheter the value is NULL,
  647. // the number of bytes read and an error, in case the string is longer than
  648. // the input slice
  649. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  650. // Get length
  651. num, isNull, n := readLengthEncodedInteger(b)
  652. if num < 1 {
  653. return b[n:n], isNull, n, nil
  654. }
  655. n += int(num)
  656. // Check data length
  657. if len(b) >= n {
  658. return b[n-int(num) : n], false, n, nil
  659. }
  660. return nil, false, n, io.EOF
  661. }
  662. // returns the number of bytes skipped and an error, in case the string is
  663. // longer than the input slice
  664. func skipLengthEncodedString(b []byte) (int, error) {
  665. // Get length
  666. num, _, n := readLengthEncodedInteger(b)
  667. if num < 1 {
  668. return n, nil
  669. }
  670. n += int(num)
  671. // Check data length
  672. if len(b) >= n {
  673. return n, nil
  674. }
  675. return n, io.EOF
  676. }
  677. // returns the number read, whether the value is NULL and the number of bytes read
  678. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  679. switch b[0] {
  680. // 251: NULL
  681. case 0xfb:
  682. return 0, true, 1
  683. // 252: value of following 2
  684. case 0xfc:
  685. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  686. // 253: value of following 3
  687. case 0xfd:
  688. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  689. // 254: value of following 8
  690. case 0xfe:
  691. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  692. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  693. uint64(b[7])<<48 | uint64(b[8])<<56,
  694. false, 9
  695. }
  696. // 0-250: value of first byte
  697. return uint64(b[0]), false, 1
  698. }
  699. // encodes a uint64 value and appends it to the given bytes slice
  700. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  701. switch {
  702. case n <= 250:
  703. return append(b, byte(n))
  704. case n <= 0xffff:
  705. return append(b, 0xfc, byte(n), byte(n>>8))
  706. case n <= 0xffffff:
  707. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  708. }
  709. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  710. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  711. }
  712. // Escape string with backslashes (\)
  713. // This escapes the contents of a string (provided as []byte) by adding backslashes before special
  714. // characters, and turning others into specific escape sequences, such as
  715. // turning newlines into \n and null bytes into \0.
  716. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
  717. func escapeBackslash(buf, v []byte) []byte {
  718. pos := len(buf)
  719. end := pos + len(v)*2
  720. if cap(buf) < end {
  721. n := make([]byte, pos+end)
  722. copy(n, buf)
  723. buf = n
  724. }
  725. buf = buf[0:end]
  726. for _, c := range v {
  727. switch c {
  728. case '\x00':
  729. buf[pos] = '\\'
  730. buf[pos+1] = '0'
  731. pos += 2
  732. case '\n':
  733. buf[pos] = '\\'
  734. buf[pos+1] = 'n'
  735. pos += 2
  736. case '\r':
  737. buf[pos] = '\\'
  738. buf[pos+1] = 'r'
  739. pos += 2
  740. case '\x1a':
  741. buf[pos] = '\\'
  742. buf[pos+1] = 'Z'
  743. pos += 2
  744. case '\'':
  745. buf[pos] = '\\'
  746. buf[pos+1] = '\''
  747. pos += 2
  748. case '"':
  749. buf[pos] = '\\'
  750. buf[pos+1] = '"'
  751. pos += 2
  752. case '\\':
  753. buf[pos] = '\\'
  754. buf[pos+1] = '\\'
  755. pos += 2
  756. default:
  757. buf[pos] = c
  758. pos += 1
  759. }
  760. }
  761. return buf[:pos]
  762. }
  763. // Escape apostrophes by doubling them up
  764. // This escapes the contents of a string by doubling up any apostrophes that
  765. // it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
  766. // effect on the server.
  767. // https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
  768. func escapeQuotes(buf, v []byte) []byte {
  769. pos := len(buf)
  770. end := pos + len(v)*2
  771. if cap(buf) < end {
  772. n := make([]byte, pos+end)
  773. copy(n, buf)
  774. buf = n
  775. }
  776. buf = buf[0:end]
  777. for _, c := range v {
  778. if c == '\'' {
  779. buf[pos] = '\''
  780. buf[pos+1] = '\''
  781. pos += 2
  782. } else {
  783. buf[pos] = c
  784. pos++
  785. }
  786. }
  787. return buf[:pos]
  788. }