utils.go 16 KB

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