utils.go 16 KB

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