utils.go 19 KB

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