utils.go 12 KB

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