utils.go 14 KB

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