packets.go 25 KB

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