utils.go 19 KB

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