packets.go 26 KB

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