packets.go 26 KB

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