utils.go 11 KB

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