utils.go 12 KB

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