utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 := rootCAs.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(clientCerts, 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. } else if tlsConfig, ok := tlsConfigMap[value]; ok {
  177. cfg.tls = tlsConfig
  178. }
  179. default:
  180. cfg.params[param[0]] = value
  181. }
  182. }
  183. }
  184. }
  185. // Set default network if empty
  186. if cfg.net == "" {
  187. cfg.net = "tcp"
  188. }
  189. // Set default adress if empty
  190. if cfg.addr == "" {
  191. cfg.addr = "127.0.0.1:3306"
  192. }
  193. // Set default location if not set
  194. if cfg.loc == nil {
  195. cfg.loc = time.UTC
  196. }
  197. return
  198. }
  199. // Encrypt password using 4.1+ method
  200. // http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#4.1_and_later
  201. func scramblePassword(scramble, password []byte) []byte {
  202. if len(password) == 0 {
  203. return nil
  204. }
  205. // stage1Hash = SHA1(password)
  206. crypt := sha1.New()
  207. crypt.Write(password)
  208. stage1 := crypt.Sum(nil)
  209. // scrambleHash = SHA1(scramble + SHA1(stage1Hash))
  210. // inner Hash
  211. crypt.Reset()
  212. crypt.Write(stage1)
  213. hash := crypt.Sum(nil)
  214. // outer Hash
  215. crypt.Reset()
  216. crypt.Write(scramble)
  217. crypt.Write(hash)
  218. scramble = crypt.Sum(nil)
  219. // token = scrambleHash XOR stage1Hash
  220. for i := range scramble {
  221. scramble[i] ^= stage1[i]
  222. }
  223. return scramble
  224. }
  225. func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
  226. switch len(str) {
  227. case 10: // YYYY-MM-DD
  228. if str == "0000-00-00" {
  229. return
  230. }
  231. t, err = time.Parse(timeFormat[:10], str)
  232. case 19: // YYYY-MM-DD HH:MM:SS
  233. if str == "0000-00-00 00:00:00" {
  234. return
  235. }
  236. t, err = time.Parse(timeFormat, str)
  237. default:
  238. err = fmt.Errorf("Invalid Time-String: %s", str)
  239. return
  240. }
  241. // Adjust location
  242. if err == nil && loc != time.UTC {
  243. y, mo, d := t.Date()
  244. h, mi, s := t.Clock()
  245. t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
  246. }
  247. return
  248. }
  249. func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
  250. switch num {
  251. case 0:
  252. return time.Time{}, nil
  253. case 4:
  254. return time.Date(
  255. int(binary.LittleEndian.Uint16(data[:2])), // year
  256. time.Month(data[2]), // month
  257. int(data[3]), // day
  258. 0, 0, 0, 0,
  259. loc,
  260. ), nil
  261. case 7:
  262. return time.Date(
  263. int(binary.LittleEndian.Uint16(data[:2])), // year
  264. time.Month(data[2]), // month
  265. int(data[3]), // day
  266. int(data[4]), // hour
  267. int(data[5]), // minutes
  268. int(data[6]), // seconds
  269. 0,
  270. loc,
  271. ), nil
  272. case 11:
  273. return time.Date(
  274. int(binary.LittleEndian.Uint16(data[:2])), // year
  275. time.Month(data[2]), // month
  276. int(data[3]), // day
  277. int(data[4]), // hour
  278. int(data[5]), // minutes
  279. int(data[6]), // seconds
  280. int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds
  281. loc,
  282. ), nil
  283. }
  284. return nil, fmt.Errorf("Invalid DATETIME-packet length %d", num)
  285. }
  286. func formatBinaryDate(num uint64, data []byte) (driver.Value, error) {
  287. switch num {
  288. case 0:
  289. return []byte("0000-00-00"), nil
  290. case 4:
  291. return []byte(fmt.Sprintf(
  292. "%04d-%02d-%02d",
  293. binary.LittleEndian.Uint16(data[:2]),
  294. data[2],
  295. data[3],
  296. )), nil
  297. }
  298. return nil, fmt.Errorf("Invalid DATE-packet length %d", num)
  299. }
  300. func formatBinaryDateTime(num uint64, data []byte) (driver.Value, error) {
  301. switch num {
  302. case 0:
  303. return []byte("0000-00-00 00:00:00"), nil
  304. case 4:
  305. return []byte(fmt.Sprintf(
  306. "%04d-%02d-%02d 00:00:00",
  307. binary.LittleEndian.Uint16(data[:2]),
  308. data[2],
  309. data[3],
  310. )), nil
  311. case 7:
  312. return []byte(fmt.Sprintf(
  313. "%04d-%02d-%02d %02d:%02d:%02d",
  314. binary.LittleEndian.Uint16(data[:2]),
  315. data[2],
  316. data[3],
  317. data[4],
  318. data[5],
  319. data[6],
  320. )), nil
  321. case 11:
  322. return []byte(fmt.Sprintf(
  323. "%04d-%02d-%02d %02d:%02d:%02d.%06d",
  324. binary.LittleEndian.Uint16(data[:2]),
  325. data[2],
  326. data[3],
  327. data[4],
  328. data[5],
  329. data[6],
  330. binary.LittleEndian.Uint32(data[7:11]),
  331. )), nil
  332. }
  333. return nil, fmt.Errorf("Invalid DATETIME-packet length %d", num)
  334. }
  335. func readBool(value string) bool {
  336. switch strings.ToLower(value) {
  337. case "true":
  338. return true
  339. case "1":
  340. return true
  341. }
  342. return false
  343. }
  344. /******************************************************************************
  345. * Convert from and to bytes *
  346. ******************************************************************************/
  347. func uint64ToBytes(n uint64) []byte {
  348. return []byte{
  349. byte(n),
  350. byte(n >> 8),
  351. byte(n >> 16),
  352. byte(n >> 24),
  353. byte(n >> 32),
  354. byte(n >> 40),
  355. byte(n >> 48),
  356. byte(n >> 56),
  357. }
  358. }
  359. func uint64ToString(n uint64) []byte {
  360. var a [20]byte
  361. i := 20
  362. // U+0030 = 0
  363. // ...
  364. // U+0039 = 9
  365. var q uint64
  366. for n >= 10 {
  367. i--
  368. q = n / 10
  369. a[i] = uint8(n-q*10) + 0x30
  370. n = q
  371. }
  372. i--
  373. a[i] = uint8(n) + 0x30
  374. return a[i:]
  375. }
  376. // treats string value as unsigned integer representation
  377. func stringToInt(b []byte) int {
  378. val := 0
  379. for i := range b {
  380. val *= 10
  381. val += int(b[i] - 0x30)
  382. }
  383. return val
  384. }
  385. func readLengthEnodedString(b []byte) ([]byte, bool, int, error) {
  386. // Get length
  387. num, isNull, n := readLengthEncodedInteger(b)
  388. if num < 1 {
  389. return nil, isNull, n, nil
  390. }
  391. n += int(num)
  392. // Check data length
  393. if len(b) >= n {
  394. return b[n-int(num) : n], false, n, nil
  395. }
  396. return nil, false, n, io.EOF
  397. }
  398. func skipLengthEnodedString(b []byte) (int, error) {
  399. // Get length
  400. num, _, n := readLengthEncodedInteger(b)
  401. if num < 1 {
  402. return n, nil
  403. }
  404. n += int(num)
  405. // Check data length
  406. if len(b) >= n {
  407. return n, nil
  408. }
  409. return n, io.EOF
  410. }
  411. func readLengthEncodedInteger(b []byte) (num uint64, isNull bool, n int) {
  412. switch b[0] {
  413. // 251: NULL
  414. case 0xfb:
  415. n = 1
  416. isNull = true
  417. return
  418. // 252: value of following 2
  419. case 0xfc:
  420. num = uint64(b[1]) | uint64(b[2])<<8
  421. n = 3
  422. return
  423. // 253: value of following 3
  424. case 0xfd:
  425. num = uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16
  426. n = 4
  427. return
  428. // 254: value of following 8
  429. case 0xfe:
  430. num = uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
  431. uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
  432. uint64(b[7])<<48 | uint64(b[8])<<54
  433. n = 9
  434. return
  435. }
  436. // 0-250: value of first byte
  437. num = uint64(b[0])
  438. n = 1
  439. return
  440. }
  441. func lengthEncodedIntegerToBytes(n uint64) []byte {
  442. switch {
  443. case n <= 250:
  444. return []byte{byte(n)}
  445. case n <= 0xffff:
  446. return []byte{0xfc, byte(n), byte(n >> 8)}
  447. case n <= 0xffffff:
  448. return []byte{0xfd, byte(n), byte(n >> 8), byte(n >> 16)}
  449. }
  450. return nil
  451. }