packets.go 26 KB

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