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