utils.go 11 KB

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