utils.go 19 KB

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