utils.go 17 KB

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