utils.go 16 KB

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