utils.go 19 KB

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