utils.go 11 KB

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