packets.go 26 KB

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