utils.go 16 KB

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