packets.go 26 KB

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