packets.go 24 KB

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