packets.go 25 KB

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