utils.go 19 KB

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