packets.go 26 KB

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