utils.go 9.0 KB

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