packets.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. "bytes"
  12. "crypto/tls"
  13. "database/sql/driver"
  14. "encoding/binary"
  15. "fmt"
  16. "io"
  17. "math"
  18. "time"
  19. )
  20. // Packets documentation:
  21. // http://dev.mysql.com/doc/internals/en/client-server-protocol.html
  22. // Read packet to buffer 'data'
  23. func (mc *mysqlConn) readPacket() (data []byte, err error) {
  24. // Read packet header
  25. data, err = mc.buf.readNext(4)
  26. if err != nil {
  27. errLog.Print(err.Error())
  28. return nil, driver.ErrBadConn
  29. }
  30. // Packet Length [24 bit]
  31. pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16)
  32. if pktLen < 1 {
  33. errLog.Print(errMalformPkt.Error())
  34. return nil, driver.ErrBadConn
  35. }
  36. // Check Packet Sync [8 bit]
  37. if data[3] != mc.sequence {
  38. if data[3] > mc.sequence {
  39. return nil, errPktSyncMul
  40. } else {
  41. return nil, errPktSync
  42. }
  43. }
  44. mc.sequence++
  45. // Read packet body [pktLen bytes]
  46. data, err = mc.buf.readNext(pktLen)
  47. if err == nil {
  48. if pktLen < maxPacketSize {
  49. return data, nil
  50. }
  51. var buf []byte
  52. buf = append(buf, data...)
  53. // More data
  54. data, err = mc.readPacket()
  55. if err == nil {
  56. return append(buf, data...), nil
  57. }
  58. }
  59. errLog.Print(err.Error())
  60. return nil, driver.ErrBadConn
  61. }
  62. // Write packet buffer 'data'
  63. // The packet header must be already included
  64. func (mc *mysqlConn) writePacket(data []byte) error {
  65. if len(data)-4 <= mc.maxWriteSize { // Can send data at once
  66. // Write packet
  67. n, err := mc.netConn.Write(data)
  68. if err == nil && n == len(data) {
  69. mc.sequence++
  70. return nil
  71. }
  72. // Handle error
  73. if err == nil { // n != len(data)
  74. errLog.Print(errMalformPkt.Error())
  75. } else {
  76. errLog.Print(err.Error())
  77. }
  78. return driver.ErrBadConn
  79. }
  80. // Must split packet
  81. return mc.splitPacket(data)
  82. }
  83. func (mc *mysqlConn) splitPacket(data []byte) (err error) {
  84. pktLen := len(data) - 4
  85. if pktLen > mc.maxPacketAllowed {
  86. return errPktTooLarge
  87. }
  88. for pktLen >= maxPacketSize {
  89. data[0] = 0xff
  90. data[1] = 0xff
  91. data[2] = 0xff
  92. data[3] = mc.sequence
  93. // Write packet
  94. n, err := mc.netConn.Write(data[:4+maxPacketSize])
  95. if err == nil && n == 4+maxPacketSize {
  96. mc.sequence++
  97. data = data[maxPacketSize:]
  98. pktLen -= maxPacketSize
  99. continue
  100. }
  101. // Handle error
  102. if err == nil { // n != len(data)
  103. errLog.Print(errMalformPkt.Error())
  104. } else {
  105. errLog.Print(err.Error())
  106. }
  107. return driver.ErrBadConn
  108. }
  109. data[0] = byte(pktLen)
  110. data[1] = byte(pktLen >> 8)
  111. data[2] = byte(pktLen >> 16)
  112. data[3] = mc.sequence
  113. return mc.writePacket(data)
  114. }
  115. /******************************************************************************
  116. * Initialisation Process *
  117. ******************************************************************************/
  118. // Handshake Initialization Packet
  119. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  120. func (mc *mysqlConn) readInitPacket() (err error) {
  121. data, err := mc.readPacket()
  122. if err != nil {
  123. return
  124. }
  125. if data[0] == iERR {
  126. return mc.handleErrorPacket(data)
  127. }
  128. // protocol version [1 byte]
  129. if data[0] < minProtocolVersion {
  130. err = fmt.Errorf(
  131. "Unsupported MySQL Protocol Version %d. Protocol Version %d or higher is required",
  132. data[0],
  133. minProtocolVersion)
  134. }
  135. // server version [null terminated string]
  136. // connection id [4 bytes]
  137. pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
  138. // first part of the password cipher [8 bytes]
  139. mc.cipher = append(mc.cipher, data[pos:pos+8]...)
  140. // (filler) always 0x00 [1 byte]
  141. pos += 8 + 1
  142. // capability flags (lower 2 bytes) [2 bytes]
  143. mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  144. if mc.flags&clientProtocol41 == 0 {
  145. err = errOldProtocol
  146. }
  147. if mc.flags&clientSSL == 0 && mc.cfg.tls != nil {
  148. return errNoTLS
  149. }
  150. pos += 2
  151. if len(data) > pos {
  152. // character set [1 byte]
  153. mc.charset = data[pos]
  154. // status flags [2 bytes]
  155. // capability flags (upper 2 bytes) [2 bytes]
  156. // length of auth-plugin-data [1 byte]
  157. // reserved (all [00]) [10 bytes]
  158. pos += 1 + 2 + 2 + 1 + 10
  159. // second part of the password cipher [12? bytes]
  160. // The documentation is ambiguous about the length.
  161. // The official Python library uses the fixed length 12
  162. // which is not documented but seems to work.
  163. mc.cipher = append(mc.cipher, data[pos:pos+12]...)
  164. // TODO: Verify string termination
  165. // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2)
  166. // \NUL otherwise
  167. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  168. //
  169. //if data[len(data)-1] == 0 {
  170. // return
  171. //}
  172. //return errMalformPkt
  173. }
  174. return
  175. }
  176. // Client Authentication Packet
  177. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::HandshakeResponse
  178. func (mc *mysqlConn) writeAuthPacket() error {
  179. // Adjust client flags based on server support
  180. clientFlags := clientProtocol41 |
  181. clientSecureConn |
  182. clientLongPassword |
  183. clientTransactions |
  184. clientLocalFiles |
  185. mc.flags&clientLongFlag
  186. if _, ok := mc.cfg.params["clientFoundRows"]; ok {
  187. clientFlags |= clientFoundRows
  188. }
  189. // To enable TLS / SSL
  190. if mc.cfg.tls != nil {
  191. clientFlags |= clientSSL
  192. }
  193. // User Password
  194. scrambleBuff := scramblePassword(mc.cipher, []byte(mc.cfg.passwd))
  195. mc.cipher = nil
  196. pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff)
  197. // To specify a db name
  198. if len(mc.cfg.dbname) > 0 {
  199. clientFlags |= clientConnectWithDB
  200. pktLen += len(mc.cfg.dbname) + 1
  201. }
  202. // Calculate packet length and make buffer with that size
  203. data := make([]byte, pktLen+4)
  204. // ClientFlags [32 bit]
  205. data[4] = byte(clientFlags)
  206. data[5] = byte(clientFlags >> 8)
  207. data[6] = byte(clientFlags >> 16)
  208. data[7] = byte(clientFlags >> 24)
  209. // MaxPacketSize [32 bit] (none)
  210. //data[8] = 0x00
  211. //data[9] = 0x00
  212. //data[10] = 0x00
  213. //data[11] = 0x00
  214. // Charset [1 byte]
  215. data[12] = mc.charset
  216. // SSL Connection Request Packet
  217. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::SSLRequest
  218. if mc.cfg.tls != nil {
  219. // Packet header [24bit length + 1 byte sequence]
  220. data[0] = byte((4 + 4 + 1 + 23))
  221. data[1] = byte((4 + 4 + 1 + 23) >> 8)
  222. data[2] = byte((4 + 4 + 1 + 23) >> 16)
  223. data[3] = mc.sequence
  224. // Send TLS / SSL request packet
  225. if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil {
  226. return err
  227. }
  228. // Switch to TLS
  229. tlsConn := tls.Client(mc.netConn, mc.cfg.tls)
  230. if err := tlsConn.Handshake(); err != nil {
  231. return err
  232. }
  233. mc.netConn = tlsConn
  234. mc.buf.rd = tlsConn
  235. }
  236. // Add the packet header [24bit length + 1 byte sequence]
  237. data[0] = byte(pktLen)
  238. data[1] = byte(pktLen >> 8)
  239. data[2] = byte(pktLen >> 16)
  240. data[3] = mc.sequence
  241. // Filler [23 bytes] (all 0x00)
  242. pos := 13 + 23
  243. // User [null terminated string]
  244. if len(mc.cfg.user) > 0 {
  245. pos += copy(data[pos:], mc.cfg.user)
  246. }
  247. //data[pos] = 0x00
  248. pos++
  249. // ScrambleBuffer [length encoded integer]
  250. data[pos] = byte(len(scrambleBuff))
  251. pos += 1 + copy(data[pos+1:], scrambleBuff)
  252. // Databasename [null terminated string]
  253. if len(mc.cfg.dbname) > 0 {
  254. pos += copy(data[pos:], mc.cfg.dbname)
  255. //data[pos] = 0x00
  256. }
  257. // Send Auth packet
  258. return mc.writePacket(data)
  259. }
  260. /******************************************************************************
  261. * Command Packets *
  262. ******************************************************************************/
  263. func (mc *mysqlConn) writeCommandPacket(command byte) error {
  264. // Reset Packet Sequence
  265. mc.sequence = 0
  266. // Send CMD packet
  267. return mc.writePacket([]byte{
  268. // Add the packet header [24bit length + 1 byte sequence]
  269. 0x01, // 1 byte long
  270. 0x00,
  271. 0x00,
  272. 0x00, // mc.sequence
  273. // Add command byte
  274. command,
  275. })
  276. }
  277. func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {
  278. // Reset Packet Sequence
  279. mc.sequence = 0
  280. pktLen := 1 + len(arg)
  281. data := make([]byte, pktLen+4)
  282. // Add the packet header [24bit length + 1 byte sequence]
  283. data[0] = byte(pktLen)
  284. data[1] = byte(pktLen >> 8)
  285. data[2] = byte(pktLen >> 16)
  286. //data[3] = mc.sequence
  287. // Add command byte
  288. data[4] = command
  289. // Add arg
  290. copy(data[5:], arg)
  291. // Send CMD packet
  292. return mc.writePacket(data)
  293. }
  294. func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {
  295. // Reset Packet Sequence
  296. mc.sequence = 0
  297. // Send CMD packet
  298. return mc.writePacket([]byte{
  299. // Add the packet header [24bit length + 1 byte sequence]
  300. 0x05, // 5 bytes long
  301. 0x00,
  302. 0x00,
  303. 0x00, // mc.sequence
  304. // Add command byte
  305. command,
  306. // Add arg [32 bit]
  307. byte(arg),
  308. byte(arg >> 8),
  309. byte(arg >> 16),
  310. byte(arg >> 24),
  311. })
  312. }
  313. /******************************************************************************
  314. * Result Packets *
  315. ******************************************************************************/
  316. // Returns error if Packet is not an 'Result OK'-Packet
  317. func (mc *mysqlConn) readResultOK() error {
  318. data, err := mc.readPacket()
  319. if err == nil {
  320. // packet indicator
  321. switch data[0] {
  322. case iOK:
  323. return mc.handleOkPacket(data)
  324. case iEOF: // someone is using old_passwords
  325. return errOldPassword
  326. default: // Error otherwise
  327. return mc.handleErrorPacket(data)
  328. }
  329. }
  330. return err
  331. }
  332. // Result Set Header Packet
  333. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  334. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  335. data, err := mc.readPacket()
  336. if err == nil {
  337. switch data[0] {
  338. case iOK:
  339. return 0, mc.handleOkPacket(data)
  340. case iERR:
  341. return 0, mc.handleErrorPacket(data)
  342. case iLocalInFile:
  343. return 0, mc.handleInFileRequest(string(data[1:]))
  344. }
  345. // column count
  346. num, _, n := readLengthEncodedInteger(data)
  347. if n-len(data) == 0 {
  348. return int(num), nil
  349. }
  350. return 0, errMalformPkt
  351. }
  352. return 0, err
  353. }
  354. // Error Packet
  355. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  356. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  357. if data[0] != iERR {
  358. return errMalformPkt
  359. }
  360. // 0xff [1 byte]
  361. // Error Number [16 bit uint]
  362. errno := binary.LittleEndian.Uint16(data[1:3])
  363. pos := 3
  364. // SQL State [optional: # + 5bytes string]
  365. //sqlstate := string(data[pos : pos+6])
  366. if data[pos] == 0x23 {
  367. pos = 9
  368. }
  369. // Error Message [string]
  370. return &MySQLError{
  371. Number: errno,
  372. Message: string(data[pos:]),
  373. }
  374. }
  375. // Ok Packet
  376. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  377. func (mc *mysqlConn) handleOkPacket(data []byte) (err error) {
  378. var n, m int
  379. // 0x00 [1 byte]
  380. // Affected rows [Length Coded Binary]
  381. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  382. // Insert id [Length Coded Binary]
  383. mc.insertId, _, m = readLengthEncodedInteger(data[1+n:])
  384. // server_status [2 bytes]
  385. // warning count [2 bytes]
  386. if !mc.strict {
  387. return
  388. } else {
  389. pos := 1 + n + m + 2
  390. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  391. err = mc.getWarnings()
  392. }
  393. }
  394. // message [until end of packet]
  395. return
  396. }
  397. // Read Packets as Field Packets until EOF-Packet or an Error appears
  398. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  399. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  400. var data []byte
  401. var i, pos, n int
  402. var name []byte
  403. columns = make([]mysqlField, count)
  404. for {
  405. data, err = mc.readPacket()
  406. if err != nil {
  407. return
  408. }
  409. // EOF Packet
  410. if data[0] == iEOF && len(data) == 5 {
  411. if i != count {
  412. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  413. }
  414. return
  415. }
  416. // Catalog
  417. pos, err = skipLengthEnodedString(data)
  418. if err != nil {
  419. return
  420. }
  421. // Database [len coded string]
  422. n, err = skipLengthEnodedString(data[pos:])
  423. if err != nil {
  424. return
  425. }
  426. pos += n
  427. // Table [len coded string]
  428. n, err = skipLengthEnodedString(data[pos:])
  429. if err != nil {
  430. return
  431. }
  432. pos += n
  433. // Original table [len coded string]
  434. n, err = skipLengthEnodedString(data[pos:])
  435. if err != nil {
  436. return
  437. }
  438. pos += n
  439. // Name [len coded string]
  440. name, _, n, err = readLengthEnodedString(data[pos:])
  441. if err != nil {
  442. return
  443. }
  444. columns[i].name = string(name)
  445. pos += n
  446. // Original name [len coded string]
  447. n, err = skipLengthEnodedString(data[pos:])
  448. if err != nil {
  449. return
  450. }
  451. // Filler [1 byte]
  452. // Charset [16 bit uint]
  453. // Length [32 bit uint]
  454. pos += n + 1 + 2 + 4
  455. // Field type [byte]
  456. columns[i].fieldType = data[pos]
  457. pos++
  458. // Flags [16 bit uint]
  459. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  460. //pos += 2
  461. // Decimals [8 bit uint]
  462. //pos++
  463. // Default value [len coded binary]
  464. //if pos < len(data) {
  465. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  466. //}
  467. i++
  468. }
  469. return
  470. }
  471. // Read Packets as Field Packets until EOF-Packet or an Error appears
  472. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  473. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  474. data, err := rows.mc.readPacket()
  475. if err != nil {
  476. return
  477. }
  478. // EOF Packet
  479. if data[0] == iEOF && len(data) == 5 {
  480. return io.EOF
  481. }
  482. // RowSet Packet
  483. var n int
  484. var isNull bool
  485. pos := 0
  486. for i := range dest {
  487. // Read bytes and convert to string
  488. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  489. pos += n
  490. if err == nil {
  491. if !isNull {
  492. if !rows.mc.parseTime {
  493. continue
  494. } else {
  495. switch rows.columns[i].fieldType {
  496. case fieldTypeTimestamp, fieldTypeDateTime,
  497. fieldTypeDate, fieldTypeNewDate:
  498. dest[i], err = parseDateTime(string(dest[i].([]byte)), rows.mc.cfg.loc)
  499. if err == nil {
  500. continue
  501. }
  502. default:
  503. continue
  504. }
  505. }
  506. } else {
  507. dest[i] = nil
  508. continue
  509. }
  510. }
  511. return // err
  512. }
  513. return
  514. }
  515. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  516. func (mc *mysqlConn) readUntilEOF() (err error) {
  517. var data []byte
  518. for {
  519. data, err = mc.readPacket()
  520. // No Err and no EOF Packet
  521. if err == nil && (data[0] != iEOF || len(data) != 5) {
  522. continue
  523. }
  524. return // Err or EOF
  525. }
  526. return
  527. }
  528. /******************************************************************************
  529. * Prepared Statements *
  530. ******************************************************************************/
  531. // Prepare Result Packets
  532. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  533. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  534. data, err := stmt.mc.readPacket()
  535. if err == nil {
  536. // Position
  537. pos := 0
  538. // packet indicator [1 byte]
  539. if data[pos] != iOK {
  540. err = stmt.mc.handleErrorPacket(data)
  541. return
  542. }
  543. pos++
  544. // statement id [4 bytes]
  545. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  546. pos += 4
  547. // Column count [16 bit uint]
  548. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  549. pos += 2
  550. // Param count [16 bit uint]
  551. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  552. pos += 2
  553. // Warning count [16 bit uint]
  554. if !stmt.mc.strict {
  555. return
  556. } else {
  557. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  558. err = stmt.mc.getWarnings()
  559. }
  560. }
  561. }
  562. return
  563. }
  564. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-send-long-data
  565. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) (err error) {
  566. maxLen := stmt.mc.maxPacketAllowed - 1
  567. pktLen := maxLen
  568. argLen := len(arg)
  569. data := make([]byte, 4+1+4+2+argLen)
  570. copy(data[4+1+4+2:], arg)
  571. for argLen > 0 {
  572. if 1+4+2+argLen < maxLen {
  573. pktLen = 1 + 4 + 2 + argLen
  574. }
  575. // Add the packet header [24bit length + 1 byte sequence]
  576. data[0] = byte(pktLen)
  577. data[1] = byte(pktLen >> 8)
  578. data[2] = byte(pktLen >> 16)
  579. data[3] = 0x00 // mc.sequence
  580. // Add command byte [1 byte]
  581. data[4] = comStmtSendLongData
  582. // Add stmtID [32 bit]
  583. data[5] = byte(stmt.id)
  584. data[6] = byte(stmt.id >> 8)
  585. data[7] = byte(stmt.id >> 16)
  586. data[8] = byte(stmt.id >> 24)
  587. // Add paramID [16 bit]
  588. data[9] = byte(paramID)
  589. data[10] = byte(paramID >> 8)
  590. // Send CMD packet
  591. err = stmt.mc.writePacket(data[:4+pktLen])
  592. if err == nil {
  593. argLen -= pktLen - (1 + 4 + 2)
  594. data = data[pktLen-(1+4+2):]
  595. continue
  596. }
  597. return err
  598. }
  599. // Reset Packet Sequence
  600. stmt.mc.sequence = 0
  601. return nil
  602. }
  603. // Execute Prepared Statement
  604. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  605. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  606. if len(args) != stmt.paramCount {
  607. return fmt.Errorf(
  608. "Arguments count mismatch (Got: %d Has: %d)",
  609. len(args),
  610. stmt.paramCount)
  611. }
  612. // Reset packet-sequence
  613. stmt.mc.sequence = 0
  614. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  615. paramValues := make([][]byte, stmt.paramCount)
  616. paramTypes := make([]byte, (stmt.paramCount << 1))
  617. bitMask := uint64(0)
  618. var i int
  619. for i = range args {
  620. // build NULL-bitmap
  621. if args[i] == nil {
  622. bitMask += 1 << uint(i)
  623. paramTypes[i<<1] = fieldTypeNULL
  624. continue
  625. }
  626. // cache types and values
  627. switch v := args[i].(type) {
  628. case int64:
  629. paramTypes[i<<1] = fieldTypeLongLong
  630. paramValues[i] = uint64ToBytes(uint64(v))
  631. pktLen += 8
  632. continue
  633. case float64:
  634. paramTypes[i<<1] = fieldTypeDouble
  635. paramValues[i] = uint64ToBytes(math.Float64bits(v))
  636. pktLen += 8
  637. continue
  638. case bool:
  639. paramTypes[i<<1] = fieldTypeTiny
  640. pktLen++
  641. if v {
  642. paramValues[i] = []byte{0x01}
  643. } else {
  644. paramValues[i] = []byte{0x00}
  645. }
  646. continue
  647. case []byte:
  648. paramTypes[i<<1] = fieldTypeString
  649. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  650. paramValues[i] = append(
  651. lengthEncodedIntegerToBytes(uint64(len(v))),
  652. v...,
  653. )
  654. pktLen += len(paramValues[i])
  655. continue
  656. } else {
  657. err := stmt.writeCommandLongData(i, v)
  658. if err == nil {
  659. continue
  660. }
  661. return err
  662. }
  663. case string:
  664. paramTypes[i<<1] = fieldTypeString
  665. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  666. paramValues[i] = append(
  667. lengthEncodedIntegerToBytes(uint64(len(v))),
  668. []byte(v)...,
  669. )
  670. pktLen += len(paramValues[i])
  671. continue
  672. } else {
  673. err := stmt.writeCommandLongData(i, []byte(v))
  674. if err == nil {
  675. continue
  676. }
  677. return err
  678. }
  679. case time.Time:
  680. paramTypes[i<<1] = fieldTypeString
  681. var val []byte
  682. if v.IsZero() {
  683. val = []byte("0000-00-00")
  684. } else {
  685. val = []byte(v.Format(timeFormat))
  686. }
  687. paramValues[i] = append(
  688. lengthEncodedIntegerToBytes(uint64(len(val))),
  689. val...,
  690. )
  691. pktLen += len(paramValues[i])
  692. continue
  693. default:
  694. return fmt.Errorf("Can't convert type: %T", args[i])
  695. }
  696. }
  697. data := make([]byte, pktLen+4)
  698. // packet header [4 bytes]
  699. data[0] = byte(pktLen)
  700. data[1] = byte(pktLen >> 8)
  701. data[2] = byte(pktLen >> 16)
  702. data[3] = stmt.mc.sequence
  703. // command [1 byte]
  704. data[4] = comStmtExecute
  705. // statement_id [4 bytes]
  706. data[5] = byte(stmt.id)
  707. data[6] = byte(stmt.id >> 8)
  708. data[7] = byte(stmt.id >> 16)
  709. data[8] = byte(stmt.id >> 24)
  710. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  711. //data[9] = 0x00
  712. // iteration_count (uint32(1)) [4 bytes]
  713. data[10] = 0x01
  714. //data[11] = 0x00
  715. //data[12] = 0x00
  716. //data[13] = 0x00
  717. if stmt.paramCount > 0 {
  718. // NULL-bitmap [(param_count+7)/8 bytes]
  719. pos := 14 + ((stmt.paramCount + 7) >> 3)
  720. // Convert bitMask to bytes
  721. for i = 14; i < pos; i++ {
  722. data[i] = byte(bitMask >> uint((i-14)<<3))
  723. }
  724. // newParameterBoundFlag 1 [1 byte]
  725. data[pos] = 0x01
  726. pos++
  727. // type of parameters [param_count*2 bytes]
  728. pos += copy(data[pos:], paramTypes)
  729. // values for the parameters [n bytes]
  730. for i = range paramValues {
  731. pos += copy(data[pos:], paramValues[i])
  732. }
  733. }
  734. return stmt.mc.writePacket(data)
  735. }
  736. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  737. func (rows *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  738. data, err := rows.mc.readPacket()
  739. if err != nil {
  740. return
  741. }
  742. // packet indicator [1 byte]
  743. if data[0] != iOK {
  744. // EOF Packet
  745. if data[0] == iEOF && len(data) == 5 {
  746. return io.EOF
  747. } else {
  748. // Error otherwise
  749. return rows.mc.handleErrorPacket(data)
  750. }
  751. }
  752. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  753. pos := 1 + (len(dest)+7+2)>>3
  754. nullBitMap := data[1:pos]
  755. // values [rest]
  756. var n int
  757. var unsigned bool
  758. for i := range dest {
  759. // Field is NULL
  760. // (byte >> bit-pos) % 2 == 1
  761. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  762. dest[i] = nil
  763. continue
  764. }
  765. unsigned = rows.columns[i].flags&flagUnsigned != 0
  766. // Convert to byte-coded string
  767. switch rows.columns[i].fieldType {
  768. case fieldTypeNULL:
  769. dest[i] = nil
  770. continue
  771. // Numeric Types
  772. case fieldTypeTiny:
  773. if unsigned {
  774. dest[i] = int64(data[pos])
  775. } else {
  776. dest[i] = int64(int8(data[pos]))
  777. }
  778. pos++
  779. continue
  780. case fieldTypeShort, fieldTypeYear:
  781. if unsigned {
  782. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  783. } else {
  784. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  785. }
  786. pos += 2
  787. continue
  788. case fieldTypeInt24, fieldTypeLong:
  789. if unsigned {
  790. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  791. } else {
  792. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  793. }
  794. pos += 4
  795. continue
  796. case fieldTypeLongLong:
  797. if unsigned {
  798. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  799. if val > math.MaxInt64 {
  800. dest[i] = uint64ToString(val)
  801. } else {
  802. dest[i] = int64(val)
  803. }
  804. } else {
  805. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  806. }
  807. pos += 8
  808. continue
  809. case fieldTypeFloat:
  810. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  811. pos += 4
  812. continue
  813. case fieldTypeDouble:
  814. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  815. pos += 8
  816. continue
  817. // Length coded Binary Strings
  818. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  819. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  820. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  821. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  822. var isNull bool
  823. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  824. pos += n
  825. if err == nil {
  826. if !isNull {
  827. continue
  828. } else {
  829. dest[i] = nil
  830. continue
  831. }
  832. }
  833. return // err
  834. // Date YYYY-MM-DD
  835. case fieldTypeDate, fieldTypeNewDate:
  836. var num uint64
  837. var isNull bool
  838. num, isNull, n = readLengthEncodedInteger(data[pos:])
  839. pos += n
  840. if isNull {
  841. dest[i] = nil
  842. continue
  843. }
  844. if rows.mc.parseTime {
  845. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  846. } else {
  847. dest[i], err = formatBinaryDate(num, data[pos:])
  848. }
  849. if err == nil {
  850. pos += int(num)
  851. continue
  852. } else {
  853. return err
  854. }
  855. // Time [-][H]HH:MM:SS[.fractal]
  856. case fieldTypeTime:
  857. var num uint64
  858. var isNull bool
  859. num, isNull, n = readLengthEncodedInteger(data[pos:])
  860. pos += n
  861. if num == 0 {
  862. if isNull {
  863. dest[i] = nil
  864. continue
  865. } else {
  866. dest[i] = []byte("00:00:00")
  867. continue
  868. }
  869. }
  870. var sign byte
  871. if data[pos] == 1 {
  872. sign = byte('-')
  873. }
  874. switch num {
  875. case 8:
  876. dest[i] = []byte(fmt.Sprintf(
  877. "%c%02d:%02d:%02d",
  878. sign,
  879. uint16(data[pos+1])*24+uint16(data[pos+5]),
  880. data[pos+6],
  881. data[pos+7],
  882. ))
  883. pos += 8
  884. continue
  885. case 12:
  886. dest[i] = []byte(fmt.Sprintf(
  887. "%c%02d:%02d:%02d.%06d",
  888. sign,
  889. uint16(data[pos+1])*24+uint16(data[pos+5]),
  890. data[pos+6],
  891. data[pos+7],
  892. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  893. ))
  894. pos += 12
  895. continue
  896. default:
  897. return fmt.Errorf("Invalid TIME-packet length %d", num)
  898. }
  899. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  900. case fieldTypeTimestamp, fieldTypeDateTime:
  901. var num uint64
  902. var isNull bool
  903. num, isNull, n = readLengthEncodedInteger(data[pos:])
  904. pos += n
  905. if isNull {
  906. dest[i] = nil
  907. continue
  908. }
  909. if rows.mc.parseTime {
  910. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  911. } else {
  912. dest[i], err = formatBinaryDateTime(num, data[pos:])
  913. }
  914. if err == nil {
  915. pos += int(num)
  916. continue
  917. } else {
  918. return err
  919. }
  920. // Please report if this happens!
  921. default:
  922. return fmt.Errorf("Unknown FieldType %d", rows.columns[i].fieldType)
  923. }
  924. }
  925. return
  926. }