utils.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. var 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 pairs = "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"
  455. if len(src) == 0 {
  456. if justTime {
  457. return zeroDateTime[11 : 11+length], nil
  458. }
  459. return zeroDateTime[:length], nil
  460. }
  461. var dst []byte // return value
  462. var pt, p1, p2, p3 byte // current digit pair
  463. var zOffs byte // offset of value in zeroDateTime
  464. if justTime {
  465. switch length {
  466. case
  467. 8, // time (can be up to 10 when negative and 100+ hours)
  468. 10, 11, 12, 13, 14, 15: // time with fractional seconds
  469. default:
  470. return nil, fmt.Errorf("illegal TIME length %d", length)
  471. }
  472. switch len(src) {
  473. case 8, 12:
  474. default:
  475. return nil, fmt.Errorf("Invalid TIME-packet length %d", len(src))
  476. }
  477. // +2 to enable negative time and 100+ hours
  478. dst = make([]byte, 0, length+2)
  479. if src[0] == 1 {
  480. dst = append(dst, '-')
  481. }
  482. if src[1] != 0 {
  483. hour := uint16(src[1])*24 + uint16(src[5])
  484. pt = byte(hour / 100)
  485. p1 = byte(hour - 100*uint16(pt))
  486. dst = append(dst, '0'+pt)
  487. } else {
  488. p1 = src[5]
  489. }
  490. zOffs = 11
  491. src = src[6:]
  492. } else {
  493. switch length {
  494. case 10, 19, 21, 22, 23, 24, 25, 26:
  495. default:
  496. t := "DATE"
  497. if length > 10 {
  498. t += "TIME"
  499. }
  500. return nil, fmt.Errorf("illegal %s length %d", t, length)
  501. }
  502. switch len(src) {
  503. case 4, 7, 11:
  504. default:
  505. t := "DATE"
  506. if length > 10 {
  507. t += "TIME"
  508. }
  509. return nil, fmt.Errorf("illegal %s-packet length %d", t, len(src))
  510. }
  511. dst = make([]byte, 0, length)
  512. // start with the date
  513. year := binary.LittleEndian.Uint16(src[:2])
  514. pt = byte(year / 100)
  515. p1 = byte(year - 100*uint16(pt))
  516. p2, p3 = src[2], src[3]
  517. dst = append(dst,
  518. pairs[2*pt], pairs[2*pt+1],
  519. pairs[2*p1], pairs[2*p1+1], '-',
  520. pairs[2*p2], pairs[2*p2+1], '-',
  521. pairs[2*p3], pairs[2*p3+1],
  522. )
  523. if length == 10 {
  524. return dst, nil
  525. }
  526. if len(src) == 4 {
  527. return append(dst, zeroDateTime[10:length]...), nil
  528. }
  529. dst = append(dst, ' ')
  530. p1 = src[4] // hour
  531. src = src[5:]
  532. }
  533. // p1 is 2-digit hour, src is after hour
  534. p2, p3 = src[0], src[1]
  535. dst = append(dst,
  536. pairs[2*p1], pairs[2*p1+1], ':',
  537. pairs[2*p2], pairs[2*p2+1], ':',
  538. pairs[2*p3], pairs[2*p3+1],
  539. )
  540. if length <= byte(len(dst)) {
  541. return dst, nil
  542. }
  543. src = src[2:]
  544. if len(src) == 0 {
  545. return append(dst, zeroDateTime[19:zOffs+length]...), nil
  546. }
  547. microsecs := binary.LittleEndian.Uint32(src[:4])
  548. p1 = byte(microsecs / 10000)
  549. microsecs -= 10000 * uint32(p1)
  550. p2 = byte(microsecs / 100)
  551. microsecs -= 100 * uint32(p2)
  552. p3 = byte(microsecs)
  553. switch decimals := zOffs + length - 20; decimals {
  554. default:
  555. return append(dst, '.',
  556. pairs[2*p1], pairs[2*p1+1],
  557. pairs[2*p2], pairs[2*p2+1],
  558. pairs[2*p3], pairs[2*p3+1],
  559. ), nil
  560. case 1:
  561. return append(dst, '.',
  562. pairs[2*p1],
  563. ), nil
  564. case 2:
  565. return append(dst, '.',
  566. pairs[2*p1], pairs[2*p1+1],
  567. ), nil
  568. case 3:
  569. return append(dst, '.',
  570. pairs[2*p1], pairs[2*p1+1],
  571. pairs[2*p2],
  572. ), nil
  573. case 4:
  574. return append(dst, '.',
  575. pairs[2*p1], pairs[2*p1+1],
  576. pairs[2*p2], pairs[2*p2+1],
  577. ), nil
  578. case 5:
  579. return append(dst, '.',
  580. pairs[2*p1], pairs[2*p1+1],
  581. pairs[2*p2], pairs[2*p2+1],
  582. pairs[2*p3],
  583. ), nil
  584. }
  585. }
  586. /******************************************************************************
  587. * Convert from and to bytes *
  588. ******************************************************************************/
  589. func uint64ToBytes(n uint64) []byte {
  590. return []byte{
  591. byte(n),
  592. byte(n >> 8),
  593. byte(n >> 16),
  594. byte(n >> 24),
  595. byte(n >> 32),
  596. byte(n >> 40),
  597. byte(n >> 48),
  598. byte(n >> 56),
  599. }
  600. }
  601. func uint64ToString(n uint64) []byte {
  602. var a [20]byte
  603. i := 20
  604. // U+0030 = 0
  605. // ...
  606. // U+0039 = 9
  607. var q uint64
  608. for n >= 10 {
  609. i--
  610. q = n / 10
  611. a[i] = uint8(n-q*10) + 0x30
  612. n = q
  613. }
  614. i--
  615. a[i] = uint8(n) + 0x30
  616. return a[i:]
  617. }
  618. // treats string value as unsigned integer representation
  619. func stringToInt(b []byte) int {
  620. val := 0
  621. for i := range b {
  622. val *= 10
  623. val += int(b[i] - 0x30)
  624. }
  625. return val
  626. }
  627. // returns the string read as a bytes slice, wheter the value is NULL,
  628. // the number of bytes read and an error, in case the string is longer than
  629. // the input slice
  630. func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  631. // Get length
  632. num, isNull, n := readLengthEncodedInteger(b)
  633. if num < 1 {
  634. return b[n:n], isNull, n, nil
  635. }
  636. n += int(num)
  637. // Check data length
  638. if len(b) >= n {
  639. return b[n-int(num) : n], false, n, nil
  640. }
  641. return nil, false, n, io.EOF
  642. }
  643. // returns the number of bytes skipped and an error, in case the string is
  644. // longer than the input slice
  645. func skipLengthEncodedString(b []byte) (int, error) {
  646. // Get length
  647. num, _, n := readLengthEncodedInteger(b)
  648. if num < 1 {
  649. return n, nil
  650. }
  651. n += int(num)
  652. // Check data length
  653. if len(b) >= n {
  654. return n, nil
  655. }
  656. return n, io.EOF
  657. }
  658. // returns the number read, whether the value is NULL and the number of bytes read
  659. func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  660. switch b[0] {
  661. // 251: NULL
  662. case 0xfb:
  663. return 0, true, 1
  664. // 252: value of following 2
  665. case 0xfc:
  666. return uint64(b[1]) | uint64(b[2])<<8, false, 3
  667. // 253: value of following 3
  668. case 0xfd:
  669. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4
  670. // 254: value of following 8
  671. case 0xfe:
  672. return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  673. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  674. uint64(b[7])<<48 | uint64(b[8])<<56,
  675. false, 9
  676. }
  677. // 0-250: value of first byte
  678. return uint64(b[0]), false, 1
  679. }
  680. // encodes a uint64 value and appends it to the given bytes slice
  681. func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  682. switch {
  683. case n <= 250:
  684. return append(b, byte(n))
  685. case n <= 0xffff:
  686. return append(b, 0xfc, byte(n), byte(n>>8))
  687. case n <= 0xffffff:
  688. return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
  689. }
  690. return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
  691. byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
  692. }