packets.go 25 KB

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