utils.go 9.0 KB

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