packets.go 26 KB

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