utils.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. // Time Location
  192. case "loc":
  193. if value, err = url.QueryUnescape(value); err != nil {
  194. return
  195. }
  196. cfg.loc, err = time.LoadLocation(value)
  197. if err != nil {
  198. return
  199. }
  200. // Dial Timeout
  201. case "timeout":
  202. cfg.timeout, err = time.ParseDuration(value)
  203. if err != nil {
  204. return
  205. }
  206. // TLS-Encryption
  207. case "tls":
  208. boolValue, isBool := readBool(value)
  209. if isBool {
  210. if boolValue {
  211. cfg.tls = &tls.Config{}
  212. }
  213. } else {
  214. if strings.ToLower(value) == "skip-verify" {
  215. cfg.tls = &tls.Config{InsecureSkipVerify: true}
  216. } else if tlsConfig, ok := tlsConfigRegister[value]; ok {
  217. cfg.tls = tlsConfig
  218. } else {
  219. return fmt.Errorf("Invalid value / unknown config name: %s", value)
  220. }
  221. }
  222. default:
  223. // lazy init
  224. if cfg.params == nil {
  225. cfg.params = make(map[string]string)
  226. }
  227. if cfg.params[param[0]], err = url.QueryUnescape(value); err != nil {
  228. return
  229. }
  230. }
  231. }
  232. return
  233. }
  234. // Returns the bool value of the input.
  235. // The 2nd return value indicates if the input was a valid bool value
  236. func readBool(input string) (value bool, valid bool) {
  237. switch input {
  238. case "1", "true", "TRUE", "True":
  239. return true, true
  240. case "0", "false", "FALSE", "False":
  241. return false, true
  242. }
  243. // Not a valid bool value
  244. return
  245. }
  246. /******************************************************************************
  247. * Authentication *
  248. ******************************************************************************/
  249. // Encrypt password using 4.1+ method
  250. func scramblePassword(scramble, password []byte) []byte {
  251. if len(password) == 0 {
  252. return nil
  253. }
  254. // stage1Hash = SHA1(password)
  255. crypt := sha1.New()
  256. crypt.Write(password)
  257. stage1 := crypt.Sum(nil)
  258. // scrambleHash = SHA1(scramble + SHA1(stage1Hash))
  259. // inner Hash
  260. crypt.Reset()
  261. crypt.Write(stage1)
  262. hash := crypt.Sum(nil)
  263. // outer Hash
  264. crypt.Reset()
  265. crypt.Write(scramble)
  266. crypt.Write(hash)
  267. scramble = crypt.Sum(nil)
  268. // token = scrambleHash XOR stage1Hash
  269. for i := range scramble {
  270. scramble[i] ^= stage1[i]
  271. }
  272. return scramble
  273. }
  274. // Encrypt password using pre 4.1 (old password) method
  275. // https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c
  276. type myRnd struct {
  277. seed1, seed2 uint32
  278. }
  279. const myRndMaxVal = 0x3FFFFFFF
  280. // Pseudo random number generator
  281. func newMyRnd(seed1, seed2 uint32) *myRnd {
  282. return &myRnd{
  283. seed1: seed1 % myRndMaxVal,
  284. seed2: seed2 % myRndMaxVal,
  285. }
  286. }
  287. // Tested to be equivalent to MariaDB's floating point variant
  288. // http://play.golang.org/p/QHvhd4qved
  289. // http://play.golang.org/p/RG0q4ElWDx
  290. func (r *myRnd) NextByte() byte {
  291. r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal
  292. r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal
  293. return byte(uint64(r.seed1) * 31 / myRndMaxVal)
  294. }
  295. // Generate binary hash from byte string using insecure pre 4.1 method
  296. func pwHash(password []byte) (result [2]uint32) {
  297. var add uint32 = 7
  298. var tmp uint32
  299. result[0] = 1345345333
  300. result[1] = 0x12345671
  301. for _, c := range password {
  302. // skip spaces and tabs in password
  303. if c == ' ' || c == '\t' {
  304. continue
  305. }
  306. tmp = uint32(c)
  307. result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8)
  308. result[1] += (result[1] << 8) ^ result[0]
  309. add += tmp
  310. }
  311. // Remove sign bit (1<<31)-1)
  312. result[0] &= 0x7FFFFFFF
  313. result[1] &= 0x7FFFFFFF
  314. return
  315. }
  316. // Encrypt password using insecure pre 4.1 method
  317. func scrambleOldPassword(scramble, password []byte) []byte {
  318. if len(password) == 0 {
  319. return nil
  320. }
  321. scramble = scramble[:8]
  322. hashPw := pwHash(password)
  323. hashSc := pwHash(scramble)
  324. r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1])
  325. var out [8]byte
  326. for i := range out {
  327. out[i] = r.NextByte() + 64
  328. }
  329. mask := r.NextByte()
  330. for i := range out {
  331. out[i] ^= mask
  332. }
  333. return out[:]
  334. }
  335. /******************************************************************************
  336. * Time related utils *
  337. ******************************************************************************/
  338. // NullTime represents a time.Time that may be NULL.
  339. // NullTime implements the Scanner interface so
  340. // it can be used as a scan destination:
  341. //
  342. // var nt NullTime
  343. // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
  344. // ...
  345. // if nt.Valid {
  346. // // use nt.Time
  347. // } else {
  348. // // NULL value
  349. // }
  350. //
  351. // This NullTime implementation is not driver-specific
  352. type NullTime struct {
  353. Time time.Time
  354. Valid bool // Valid is true if Time is not NULL
  355. }
  356. // Scan implements the Scanner interface.
  357. // The value type must be time.Time or string / []byte (formatted time-string),
  358. // otherwise Scan fails.
  359. func (nt *NullTime) Scan(value interface{}) (err error) {
  360. if value == nil {
  361. nt.Time, nt.Valid = time.Time{}, false
  362. return
  363. }
  364. switch v := value.(type) {
  365. case time.Time:
  366. nt.Time, nt.Valid = v, true
  367. return
  368. case []byte:
  369. nt.Time, err = parseDateTime(string(v), time.UTC)
  370. nt.Valid = (err == nil)
  371. return
  372. case string:
  373. nt.Time, err = parseDateTime(v, time.UTC)
  374. nt.Valid = (err == nil)
  375. return
  376. }
  377. nt.Valid = false
  378. return fmt.Errorf("Can't convert %T to time.Time", value)
  379. }
  380. // Value implements the driver Valuer interface.
  381. func (nt NullTime) Value() (driver.Value, error) {
  382. if !nt.Valid {
  383. return nil, nil
  384. }
  385. return nt.Time, nil
  386. }
  387. func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
  388. base := "0000-00-00 00:00:00.0000000"
  389. switch len(str) {
  390. case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM"
  391. if str == base[:len(str)] {
  392. return
  393. }
  394. t, err = time.Parse(timeFormat[:len(str)], str)
  395. default:
  396. err = fmt.Errorf("Invalid Time-String: %s", str)
  397. return
  398. }
  399. // Adjust location
  400. if err == nil && loc != time.UTC {
  401. y, mo, d := t.Date()
  402. h, mi, s := t.Clock()
  403. t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
  404. }
  405. return
  406. }
  407. func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
  408. switch num {
  409. case 0:
  410. return time.Time{}, nil
  411. case 4:
  412. return time.Date(
  413. int(binary.LittleEndian.Uint16(data[:2])), // year
  414. time.Month(data[2]), // month
  415. int(data[3]), // day
  416. 0, 0, 0, 0,
  417. loc,
  418. ), nil
  419. case 7:
  420. return time.Date(
  421. int(binary.LittleEndian.Uint16(data[:2])), // year
  422. time.Month(data[2]), // month
  423. int(data[3]), // day
  424. int(data[4]), // hour
  425. int(data[5]), // minutes
  426. int(data[6]), // seconds
  427. 0,
  428. loc,
  429. ), nil
  430. case 11:
  431. return time.Date(
  432. int(binary.LittleEndian.Uint16(data[:2])), // year
  433. time.Month(data[2]), // month
  434. int(data[3]), // day
  435. int(data[4]), // hour
  436. int(data[5]), // minutes
  437. int(data[6]), // seconds
  438. int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
  439. loc,
  440. ), nil
  441. }
  442. return nil, fmt.Errorf("Invalid DATETIME-packet length %d", num)
  443. }
  444. // zeroDateTime is used in formatBinaryDateTime to avoid an allocation
  445. // if the DATE or DATETIME has the zero value.
  446. // It must never be changed.
  447. // The current behavior depends on database/sql copying the result.
  448. var zeroDateTime = []byte("0000-00-00 00:00:00.000000")
  449. func formatBinaryDateTime(src []byte, length uint8, justTime bool) (driver.Value, error) {
  450. // length expects the deterministic length of the zero value,
  451. // negative time and 100+ hours are automatically added if needed
  452. const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
  453. const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
  454. if len(src) == 0 {
  455. if justTime {
  456. return zeroDateTime[11 : 11+length], nil
  457. }
  458. return zeroDateTime[:length], nil
  459. }
  460. var dst []byte // return value
  461. var pt, p1, p2, p3 byte // current digit pair
  462. var zOffs byte // offset of value in zeroDateTime
  463. if justTime {
  464. switch length {
  465. case
  466. 8, // time (can be up to 10 when negative and 100+ hours)
  467. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  468. default:
  469. return nil, fmt.Errorf("illegal TIME length %d", length)
  470. }
  471. switch len(src) {
  472. case 8, 12:
  473. default:
  474. return nil, fmt.Errorf("Invalid TIME-packet length %d", len(src))
  475. }
  476. // +2 to enable negative time and 100+ hours
  477. dst = make([]byte, 0, length+2)
  478. if src[0] == 1 {
  479. dst = append(dst, '-')
  480. }
  481. if src[1] != 0 {
  482. hour := uint16(src[1])*24 + uint16(src[5])
  483. pt = byte(hour / 100)
  484. p1 = byte(hour - 100*uint16(pt))
  485. dst = append(dst, digits01[pt])
  486. } else {
  487. p1 = src[5]
  488. }
  489. zOffs = 11
  490. src = src[6:]
  491. } else {
  492. switch length {
  493. case 10, 19, 21, 22, 23, 24, 25, 26:
  494. default:
  495. t := "DATE"
  496. if length > 10 {
  497. t += "TIME"
  498. }
  499. return nil, fmt.Errorf("illegal %s length %d", t, length)
  500. }
  501. switch len(src) {
  502. case 4, 7, 11:
  503. default:
  504. t := "DATE"
  505. if length > 10 {
  506. t += "TIME"
  507. }
  508. return nil, fmt.Errorf("illegal %s-packet length %d", t, len(src))
  509. }
  510. dst = make([]byte, 0, length)
  511. // start with the date
  512. year := binary.LittleEndian.Uint16(src[:2])
  513. pt = byte(year / 100)
  514. p1 = byte(year - 100*uint16(pt))
  515. p2, p3 = src[2], src[3]
  516. dst = append(dst,
  517. digits10[pt], digits01[pt],
  518. digits10[p1], digits01[p1], '-',
  519. digits10[p2], digits01[p2], '-',
  520. digits10[p3], digits01[p3],
  521. )
  522. if length == 10 {
  523. return dst, nil
  524. }
  525. if len(src) == 4 {
  526. return append(dst, zeroDateTime[10:length]...), nil
  527. }
  528. dst = append(dst, ' ')
  529. p1 = src[4] // hour
  530. src = src[5:]
  531. }
  532. // p1 is 2-digit hour, src is after hour
  533. p2, p3 = src[0], src[1]
  534. dst = append(dst,
  535. digits10[p1], digits01[p1], ':',
  536. digits10[p2], digits01[p2], ':',
  537. digits10[p3], digits01[p3],
  538. )
  539. if length <= byte(len(dst)) {
  540. return dst, nil
  541. }
  542. src = src[2:]
  543. if len(src) == 0 {
  544. return append(dst, zeroDateTime[19:zOffs+length]...), nil
  545. }
  546. microsecs := binary.LittleEndian.Uint32(src[:4])
  547. p1 = byte(microsecs / 10000)
  548. microsecs -= 10000 * uint32(p1)
  549. p2 = byte(microsecs / 100)
  550. microsecs -= 100 * uint32(p2)
  551. p3 = byte(microsecs)
  552. switch decimals := zOffs + length - 20; decimals {
  553. default:
  554. return append(dst, '.',
  555. digits10[p1], digits01[p1],
  556. digits10[p2], digits01[p2],
  557. digits10[p3], digits01[p3],
  558. ), nil
  559. case 1:
  560. return append(dst, '.',
  561. digits10[p1],
  562. ), nil
  563. case 2:
  564. return append(dst, '.',
  565. digits10[p1], digits01[p1],
  566. ), nil
  567. case 3:
  568. return append(dst, '.',
  569. digits10[p1], digits01[p1],
  570. digits10[p2],
  571. ), nil
  572. case 4:
  573. return append(dst, '.',
  574. digits10[p1], digits01[p1],
  575. digits10[p2], digits01[p2],
  576. ), nil
  577. case 5:
  578. return append(dst, '.',
  579. digits10[p1], digits01[p1],
  580. digits10[p2], digits01[p2],
  581. digits10[p3],
  582. ), nil
  583. }
  584. }
  585. /******************************************************************************
  586. * Convert from and to bytes *
  587. ******************************************************************************/
  588. func uint64ToBytes(n uint64) []byte {
  589. return []byte{
  590. byte(n),
  591. byte(n >> 8),
  592. byte(n >> 16),
  593. byte(n >> 24),
  594. byte(n >> 32),
  595. byte(n >> 40),
  596. byte(n >> 48),
  597. byte(n >> 56),
  598. }
  599. }
  600. func uint64ToString(n uint64) []byte {
  601. var a [20]byte
  602. i := 20
  603. // U+0030 = 0
  604. // ...
  605. // U+0039 = 9
  606. var q uint64
  607. for n >= 10 {
  608. i--
  609. q = n / 10
  610. a[i] = uint8(n-q*10) + 0x30
  611. n = q
  612. }
  613. i--
  614. a[i] = uint8(n) + 0x30
  615. return a[i:]
  616. }
  617. // treats string value as unsigned integer representation
  618. func stringToInt(b []byte) int {
  619. val := 0
  620. for i := range b {
  621. val *= 10
  622. val += int(b[i] - 0x30)
  623. }
  624. return val
  625. }
  626. // returns the string read as a bytes slice, wheter the value is NULL,
  627. // the number of bytes read and an error, in case the string is longer than
  628. // the input slice
  629. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  630. // Get length
  631. num, isNull, n := readLengthEncodedInteger(b)
  632. if num < 1 {
  633. return b[n:n], isNull, n, nil
  634. }
  635. n += int(num)
  636. // Check data length
  637. if len(b) >= n {
  638. return b[n-int(num) : n], false, n, nil
  639. }
  640. return nil, false, n, io.EOF
  641. }
  642. // returns the number of bytes skipped and an error, in case the string is
  643. // longer than the input slice
  644. func skipLengthEncodedString(b []byte) (int, error) {
  645. // Get length
  646. num, _, n := readLengthEncodedInteger(b)
  647. if num < 1 {
  648. return n, nil
  649. }
  650. n += int(num)
  651. // Check data length
  652. if len(b) >= n {
  653. return n, nil
  654. }
  655. return n, io.EOF
  656. }
  657. // returns the number read, whether the value is NULL and the number of bytes read
  658. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  659. switch b[0] {
  660. // 251: NULL
  661. case 0xfb:
  662. return 0, true, 1
  663. // 252: value of following 2
  664. case 0xfc:
  665. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  666. // 253: value of following 3
  667. case 0xfd:
  668. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  669. // 254: value of following 8
  670. case 0xfe:
  671. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  672. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  673. uint64(b[7])<<48 | uint64(b[8])<<56,
  674. false, 9
  675. }
  676. // 0-250: value of first byte
  677. return uint64(b[0]), false, 1
  678. }
  679. // encodes a uint64 value and appends it to the given bytes slice
  680. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  681. switch {
  682. case n <= 250:
  683. return append(b, byte(n))
  684. case n <= 0xffff:
  685. return append(b, 0xfc, byte(n), byte(n>>8))
  686. case n <= 0xffffff:
  687. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  688. }
  689. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  690. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  691. }