packets.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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() (cipher []byte, err error) {
  121. data, err := mc.readPacket()
  122. if err != nil {
  123. return
  124. }
  125. if data[0] == iERR {
  126. return nil, 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. return
  135. }
  136. // server version [null terminated string]
  137. // connection id [4 bytes]
  138. pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
  139. // first part of the password cipher [8 bytes]
  140. cipher = data[pos : pos+8]
  141. // (filler) always 0x00 [1 byte]
  142. pos += 8 + 1
  143. // capability flags (lower 2 bytes) [2 bytes]
  144. mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  145. if mc.flags&clientProtocol41 == 0 {
  146. return nil, errOldProtocol
  147. }
  148. if mc.flags&clientSSL == 0 && mc.cfg.tls != nil {
  149. return nil, errNoTLS
  150. }
  151. pos += 2
  152. if len(data) > pos {
  153. // character set [1 byte]
  154. // status flags [2 bytes]
  155. // capability flags (upper 2 bytes) [2 bytes]
  156. // length of auth-plugin-data [1 byte]
  157. // reserved (all [00]) [10 bytes]
  158. pos += 1 + 2 + 2 + 1 + 10
  159. // second part of the password cipher [12? bytes]
  160. // The documentation is ambiguous about the length.
  161. // The official Python library uses the fixed length 12
  162. // which is not documented but seems to work.
  163. cipher = append(cipher, data[pos:pos+12]...)
  164. // TODO: Verify string termination
  165. // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2)
  166. // \NUL otherwise
  167. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
  168. //
  169. //if data[len(data)-1] == 0 {
  170. // return
  171. //}
  172. //return errMalformPkt
  173. }
  174. return
  175. }
  176. // Client Authentication Packet
  177. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::HandshakeResponse
  178. func (mc *mysqlConn) writeAuthPacket(cipher []byte) error {
  179. // Adjust client flags based on server support
  180. clientFlags := clientProtocol41 |
  181. clientSecureConn |
  182. clientLongPassword |
  183. clientTransactions |
  184. clientLocalFiles |
  185. mc.flags&clientLongFlag
  186. if mc.cfg.clientFoundRows {
  187. clientFlags |= clientFoundRows
  188. }
  189. // To enable TLS / SSL
  190. if mc.cfg.tls != nil {
  191. clientFlags |= clientSSL
  192. }
  193. // User Password
  194. scrambleBuff := scramblePassword(cipher, []byte(mc.cfg.passwd))
  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. // Client old authentication packet
  260. // http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::AuthSwitchResponse
  261. func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error {
  262. // User password
  263. scrambleBuff := scrambleOldPassword(cipher, []byte(mc.cfg.passwd))
  264. // Calculate the packet lenght and add a tailing 0
  265. pktLen := len(scrambleBuff) + 1
  266. data := make([]byte, pktLen+4)
  267. // Add the packet header [24bit length + 1 byte sequence]
  268. data[0] = byte(pktLen)
  269. data[1] = byte(pktLen >> 8)
  270. data[2] = byte(pktLen >> 16)
  271. data[3] = mc.sequence
  272. // Add the scrambled password [null terminated string]
  273. copy(data[4:], scrambleBuff)
  274. return mc.writePacket(data)
  275. }
  276. /******************************************************************************
  277. * Command Packets *
  278. ******************************************************************************/
  279. func (mc *mysqlConn) writeCommandPacket(command byte) error {
  280. // Reset Packet Sequence
  281. mc.sequence = 0
  282. // Send CMD packet
  283. return mc.writePacket([]byte{
  284. // Add the packet header [24bit length + 1 byte sequence]
  285. 0x01, // 1 byte long
  286. 0x00,
  287. 0x00,
  288. 0x00, // mc.sequence
  289. // Add command byte
  290. command,
  291. })
  292. }
  293. func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {
  294. // Reset Packet Sequence
  295. mc.sequence = 0
  296. pktLen := 1 + len(arg)
  297. data := make([]byte, pktLen+4)
  298. // Add the packet header [24bit length + 1 byte sequence]
  299. data[0] = byte(pktLen)
  300. data[1] = byte(pktLen >> 8)
  301. data[2] = byte(pktLen >> 16)
  302. //data[3] = mc.sequence
  303. // Add command byte
  304. data[4] = command
  305. // Add arg
  306. copy(data[5:], arg)
  307. // Send CMD packet
  308. return mc.writePacket(data)
  309. }
  310. func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {
  311. // Reset Packet Sequence
  312. mc.sequence = 0
  313. // Send CMD packet
  314. return mc.writePacket([]byte{
  315. // Add the packet header [24bit length + 1 byte sequence]
  316. 0x05, // 5 bytes long
  317. 0x00,
  318. 0x00,
  319. 0x00, // mc.sequence
  320. // Add command byte
  321. command,
  322. // Add arg [32 bit]
  323. byte(arg),
  324. byte(arg >> 8),
  325. byte(arg >> 16),
  326. byte(arg >> 24),
  327. })
  328. }
  329. /******************************************************************************
  330. * Result Packets *
  331. ******************************************************************************/
  332. // Returns error if Packet is not an 'Result OK'-Packet
  333. func (mc *mysqlConn) readResultOK() error {
  334. data, err := mc.readPacket()
  335. if err == nil {
  336. // packet indicator
  337. switch data[0] {
  338. case iOK:
  339. return mc.handleOkPacket(data)
  340. case iEOF:
  341. // someone is using old_passwords
  342. return errOldPassword
  343. default: // Error otherwise
  344. return mc.handleErrorPacket(data)
  345. }
  346. }
  347. return err
  348. }
  349. // Result Set Header Packet
  350. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
  351. func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) {
  352. data, err := mc.readPacket()
  353. if err == nil {
  354. switch data[0] {
  355. case iOK:
  356. return 0, mc.handleOkPacket(data)
  357. case iERR:
  358. return 0, mc.handleErrorPacket(data)
  359. case iLocalInFile:
  360. return 0, mc.handleInFileRequest(string(data[1:]))
  361. }
  362. // column count
  363. num, _, n := readLengthEncodedInteger(data)
  364. if n-len(data) == 0 {
  365. return int(num), nil
  366. }
  367. return 0, errMalformPkt
  368. }
  369. return 0, err
  370. }
  371. // Error Packet
  372. // http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
  373. func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  374. if data[0] != iERR {
  375. return errMalformPkt
  376. }
  377. // 0xff [1 byte]
  378. // Error Number [16 bit uint]
  379. errno := binary.LittleEndian.Uint16(data[1:3])
  380. pos := 3
  381. // SQL State [optional: # + 5bytes string]
  382. //sqlstate := string(data[pos : pos+6])
  383. if data[pos] == 0x23 {
  384. pos = 9
  385. }
  386. // Error Message [string]
  387. return &MySQLError{
  388. Number: errno,
  389. Message: string(data[pos:]),
  390. }
  391. }
  392. // Ok Packet
  393. // http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
  394. func (mc *mysqlConn) handleOkPacket(data []byte) (err error) {
  395. var n, m int
  396. // 0x00 [1 byte]
  397. // Affected rows [Length Coded Binary]
  398. mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
  399. // Insert id [Length Coded Binary]
  400. mc.insertId, _, m = readLengthEncodedInteger(data[1+n:])
  401. // server_status [2 bytes]
  402. // warning count [2 bytes]
  403. if !mc.strict {
  404. return
  405. } else {
  406. pos := 1 + n + m + 2
  407. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  408. err = mc.getWarnings()
  409. }
  410. }
  411. // message [until end of packet]
  412. return
  413. }
  414. // Read Packets as Field Packets until EOF-Packet or an Error appears
  415. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
  416. func (mc *mysqlConn) readColumns(count int) (columns []mysqlField, err error) {
  417. var data []byte
  418. var i, pos, n int
  419. var name []byte
  420. columns = make([]mysqlField, count)
  421. for {
  422. data, err = mc.readPacket()
  423. if err != nil {
  424. return
  425. }
  426. // EOF Packet
  427. if data[0] == iEOF && (len(data) == 5 || len(data) == 1) {
  428. if i != count {
  429. err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
  430. }
  431. return
  432. }
  433. // Catalog
  434. pos, err = skipLengthEnodedString(data)
  435. if err != nil {
  436. return
  437. }
  438. // Database [len coded string]
  439. n, err = skipLengthEnodedString(data[pos:])
  440. if err != nil {
  441. return
  442. }
  443. pos += n
  444. // Table [len coded string]
  445. n, err = skipLengthEnodedString(data[pos:])
  446. if err != nil {
  447. return
  448. }
  449. pos += n
  450. // Original table [len coded string]
  451. n, err = skipLengthEnodedString(data[pos:])
  452. if err != nil {
  453. return
  454. }
  455. pos += n
  456. // Name [len coded string]
  457. name, _, n, err = readLengthEnodedString(data[pos:])
  458. if err != nil {
  459. return
  460. }
  461. columns[i].name = string(name)
  462. pos += n
  463. // Original name [len coded string]
  464. n, err = skipLengthEnodedString(data[pos:])
  465. if err != nil {
  466. return
  467. }
  468. // Filler [1 byte]
  469. // Charset [16 bit uint]
  470. // Length [32 bit uint]
  471. pos += n + 1 + 2 + 4
  472. // Field type [byte]
  473. columns[i].fieldType = data[pos]
  474. pos++
  475. // Flags [16 bit uint]
  476. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  477. //pos += 2
  478. // Decimals [8 bit uint]
  479. //pos++
  480. // Default value [len coded binary]
  481. //if pos < len(data) {
  482. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  483. //}
  484. i++
  485. }
  486. }
  487. // Read Packets as Field Packets until EOF-Packet or an Error appears
  488. // http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
  489. func (rows *mysqlRows) readRow(dest []driver.Value) (err error) {
  490. data, err := rows.mc.readPacket()
  491. if err != nil {
  492. return
  493. }
  494. // EOF Packet
  495. if data[0] == iEOF && len(data) == 5 {
  496. return io.EOF
  497. }
  498. // RowSet Packet
  499. var n int
  500. var isNull bool
  501. pos := 0
  502. for i := range dest {
  503. // Read bytes and convert to string
  504. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  505. pos += n
  506. if err == nil {
  507. if !isNull {
  508. if !rows.mc.parseTime {
  509. continue
  510. } else {
  511. switch rows.columns[i].fieldType {
  512. case fieldTypeTimestamp, fieldTypeDateTime,
  513. fieldTypeDate, fieldTypeNewDate:
  514. dest[i], err = parseDateTime(string(dest[i].([]byte)), rows.mc.cfg.loc)
  515. if err == nil {
  516. continue
  517. }
  518. default:
  519. continue
  520. }
  521. }
  522. } else {
  523. dest[i] = nil
  524. continue
  525. }
  526. }
  527. return // err
  528. }
  529. return
  530. }
  531. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  532. func (mc *mysqlConn) readUntilEOF() (err error) {
  533. var data []byte
  534. for {
  535. data, err = mc.readPacket()
  536. // No Err and no EOF Packet
  537. if err == nil && data[0] != iEOF {
  538. continue
  539. }
  540. return // Err or EOF
  541. }
  542. }
  543. /******************************************************************************
  544. * Prepared Statements *
  545. ******************************************************************************/
  546. // Prepare Result Packets
  547. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-prepare-response
  548. func (stmt *mysqlStmt) readPrepareResultPacket() (columnCount uint16, err error) {
  549. data, err := stmt.mc.readPacket()
  550. if err == nil {
  551. // Position
  552. pos := 0
  553. // packet indicator [1 byte]
  554. if data[pos] != iOK {
  555. err = stmt.mc.handleErrorPacket(data)
  556. return
  557. }
  558. pos++
  559. // statement id [4 bytes]
  560. stmt.id = binary.LittleEndian.Uint32(data[pos : pos+4])
  561. pos += 4
  562. // Column count [16 bit uint]
  563. columnCount = binary.LittleEndian.Uint16(data[pos : pos+2])
  564. pos += 2
  565. // Param count [16 bit uint]
  566. stmt.paramCount = int(binary.LittleEndian.Uint16(data[pos : pos+2]))
  567. pos += 2
  568. // Reserved [8 bit]
  569. pos++
  570. // Warning count [16 bit uint]
  571. if !stmt.mc.strict {
  572. return
  573. } else {
  574. // Check for warnings count > 0, only available in MySQL > 4.1
  575. if len(data) >= 12 && binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  576. err = stmt.mc.getWarnings()
  577. }
  578. }
  579. }
  580. return
  581. }
  582. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-send-long-data
  583. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) (err error) {
  584. maxLen := stmt.mc.maxPacketAllowed - 1
  585. pktLen := maxLen
  586. argLen := len(arg)
  587. data := make([]byte, 4+1+4+2+argLen)
  588. copy(data[4+1+4+2:], arg)
  589. for argLen > 0 {
  590. if 1+4+2+argLen < maxLen {
  591. pktLen = 1 + 4 + 2 + argLen
  592. }
  593. // Add the packet header [24bit length + 1 byte sequence]
  594. data[0] = byte(pktLen)
  595. data[1] = byte(pktLen >> 8)
  596. data[2] = byte(pktLen >> 16)
  597. data[3] = 0x00 // mc.sequence
  598. // Add command byte [1 byte]
  599. data[4] = comStmtSendLongData
  600. // Add stmtID [32 bit]
  601. data[5] = byte(stmt.id)
  602. data[6] = byte(stmt.id >> 8)
  603. data[7] = byte(stmt.id >> 16)
  604. data[8] = byte(stmt.id >> 24)
  605. // Add paramID [16 bit]
  606. data[9] = byte(paramID)
  607. data[10] = byte(paramID >> 8)
  608. // Send CMD packet
  609. err = stmt.mc.writePacket(data[:4+pktLen])
  610. if err == nil {
  611. argLen -= pktLen - (1 + 4 + 2)
  612. data = data[pktLen-(1+4+2):]
  613. continue
  614. }
  615. return err
  616. }
  617. // Reset Packet Sequence
  618. stmt.mc.sequence = 0
  619. return nil
  620. }
  621. // Execute Prepared Statement
  622. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#com-stmt-execute
  623. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  624. if len(args) != stmt.paramCount {
  625. return fmt.Errorf(
  626. "Arguments count mismatch (Got: %d Has: %d)",
  627. len(args),
  628. stmt.paramCount)
  629. }
  630. // Reset packet-sequence
  631. stmt.mc.sequence = 0
  632. pktLen := 1 + 4 + 1 + 4 + ((stmt.paramCount + 7) >> 3) + 1 + (stmt.paramCount << 1)
  633. paramValues := make([][]byte, stmt.paramCount)
  634. paramTypes := make([]byte, (stmt.paramCount << 1))
  635. bitMask := uint64(0)
  636. var i int
  637. for i = range args {
  638. // build NULL-bitmap
  639. if args[i] == nil {
  640. bitMask += 1 << uint(i)
  641. paramTypes[i<<1] = fieldTypeNULL
  642. continue
  643. }
  644. // cache types and values
  645. switch v := args[i].(type) {
  646. case int64:
  647. paramTypes[i<<1] = fieldTypeLongLong
  648. paramValues[i] = uint64ToBytes(uint64(v))
  649. pktLen += 8
  650. continue
  651. case float64:
  652. paramTypes[i<<1] = fieldTypeDouble
  653. paramValues[i] = uint64ToBytes(math.Float64bits(v))
  654. pktLen += 8
  655. continue
  656. case bool:
  657. paramTypes[i<<1] = fieldTypeTiny
  658. pktLen++
  659. if v {
  660. paramValues[i] = []byte{0x01}
  661. } else {
  662. paramValues[i] = []byte{0x00}
  663. }
  664. continue
  665. case []byte:
  666. paramTypes[i<<1] = fieldTypeString
  667. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  668. paramValues[i] = append(
  669. lengthEncodedIntegerToBytes(uint64(len(v))),
  670. v...,
  671. )
  672. pktLen += len(paramValues[i])
  673. continue
  674. } else {
  675. err := stmt.writeCommandLongData(i, v)
  676. if err == nil {
  677. continue
  678. }
  679. return err
  680. }
  681. case string:
  682. paramTypes[i<<1] = fieldTypeString
  683. if len(v) < stmt.mc.maxPacketAllowed-pktLen-(stmt.paramCount-(i+1))*64 {
  684. paramValues[i] = append(
  685. lengthEncodedIntegerToBytes(uint64(len(v))),
  686. []byte(v)...,
  687. )
  688. pktLen += len(paramValues[i])
  689. continue
  690. } else {
  691. err := stmt.writeCommandLongData(i, []byte(v))
  692. if err == nil {
  693. continue
  694. }
  695. return err
  696. }
  697. case time.Time:
  698. paramTypes[i<<1] = fieldTypeString
  699. var val []byte
  700. if v.IsZero() {
  701. val = []byte("0000-00-00")
  702. } else {
  703. val = []byte(v.In(stmt.mc.cfg.loc).Format(timeFormat))
  704. }
  705. paramValues[i] = append(
  706. lengthEncodedIntegerToBytes(uint64(len(val))),
  707. val...,
  708. )
  709. pktLen += len(paramValues[i])
  710. continue
  711. default:
  712. return fmt.Errorf("Can't convert type: %T", args[i])
  713. }
  714. }
  715. data := make([]byte, pktLen+4)
  716. // packet header [4 bytes]
  717. data[0] = byte(pktLen)
  718. data[1] = byte(pktLen >> 8)
  719. data[2] = byte(pktLen >> 16)
  720. data[3] = stmt.mc.sequence
  721. // command [1 byte]
  722. data[4] = comStmtExecute
  723. // statement_id [4 bytes]
  724. data[5] = byte(stmt.id)
  725. data[6] = byte(stmt.id >> 8)
  726. data[7] = byte(stmt.id >> 16)
  727. data[8] = byte(stmt.id >> 24)
  728. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  729. //data[9] = 0x00
  730. // iteration_count (uint32(1)) [4 bytes]
  731. data[10] = 0x01
  732. //data[11] = 0x00
  733. //data[12] = 0x00
  734. //data[13] = 0x00
  735. if stmt.paramCount > 0 {
  736. // NULL-bitmap [(param_count+7)/8 bytes]
  737. pos := 14 + ((stmt.paramCount + 7) >> 3)
  738. // Convert bitMask to bytes
  739. for i = 14; i < pos; i++ {
  740. data[i] = byte(bitMask >> uint((i-14)<<3))
  741. }
  742. // newParameterBoundFlag 1 [1 byte]
  743. data[pos] = 0x01
  744. pos++
  745. // type of parameters [param_count*2 bytes]
  746. pos += copy(data[pos:], paramTypes)
  747. // values for the parameters [n bytes]
  748. for i = range paramValues {
  749. pos += copy(data[pos:], paramValues[i])
  750. }
  751. }
  752. return stmt.mc.writePacket(data)
  753. }
  754. // http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::ResultsetRow
  755. func (rows *mysqlRows) readBinaryRow(dest []driver.Value) (err error) {
  756. data, err := rows.mc.readPacket()
  757. if err != nil {
  758. return
  759. }
  760. // packet indicator [1 byte]
  761. if data[0] != iOK {
  762. // EOF Packet
  763. if data[0] == iEOF && len(data) == 5 {
  764. return io.EOF
  765. } else {
  766. // Error otherwise
  767. return rows.mc.handleErrorPacket(data)
  768. }
  769. }
  770. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  771. pos := 1 + (len(dest)+7+2)>>3
  772. nullBitMap := data[1:pos]
  773. // values [rest]
  774. var n int
  775. var unsigned bool
  776. for i := range dest {
  777. // Field is NULL
  778. // (byte >> bit-pos) % 2 == 1
  779. if ((nullBitMap[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  780. dest[i] = nil
  781. continue
  782. }
  783. unsigned = rows.columns[i].flags&flagUnsigned != 0
  784. // Convert to byte-coded string
  785. switch rows.columns[i].fieldType {
  786. case fieldTypeNULL:
  787. dest[i] = nil
  788. continue
  789. // Numeric Types
  790. case fieldTypeTiny:
  791. if unsigned {
  792. dest[i] = int64(data[pos])
  793. } else {
  794. dest[i] = int64(int8(data[pos]))
  795. }
  796. pos++
  797. continue
  798. case fieldTypeShort, fieldTypeYear:
  799. if unsigned {
  800. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  801. } else {
  802. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  803. }
  804. pos += 2
  805. continue
  806. case fieldTypeInt24, fieldTypeLong:
  807. if unsigned {
  808. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  809. } else {
  810. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  811. }
  812. pos += 4
  813. continue
  814. case fieldTypeLongLong:
  815. if unsigned {
  816. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  817. if val > math.MaxInt64 {
  818. dest[i] = uint64ToString(val)
  819. } else {
  820. dest[i] = int64(val)
  821. }
  822. } else {
  823. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  824. }
  825. pos += 8
  826. continue
  827. case fieldTypeFloat:
  828. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  829. pos += 4
  830. continue
  831. case fieldTypeDouble:
  832. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  833. pos += 8
  834. continue
  835. // Length coded Binary Strings
  836. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  837. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  838. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  839. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  840. var isNull bool
  841. dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
  842. pos += n
  843. if err == nil {
  844. if !isNull {
  845. continue
  846. } else {
  847. dest[i] = nil
  848. continue
  849. }
  850. }
  851. return // err
  852. // Date YYYY-MM-DD
  853. case fieldTypeDate, fieldTypeNewDate:
  854. var num uint64
  855. var isNull bool
  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. var num uint64
  876. var isNull bool
  877. num, isNull, n = readLengthEncodedInteger(data[pos:])
  878. pos += n
  879. if num == 0 {
  880. if isNull {
  881. dest[i] = nil
  882. continue
  883. } else {
  884. dest[i] = []byte("00:00:00")
  885. continue
  886. }
  887. }
  888. var sign byte
  889. if data[pos] == 1 {
  890. sign = byte('-')
  891. }
  892. switch num {
  893. case 8:
  894. dest[i] = []byte(fmt.Sprintf(
  895. "%c%02d:%02d:%02d",
  896. sign,
  897. uint16(data[pos+1])*24+uint16(data[pos+5]),
  898. data[pos+6],
  899. data[pos+7],
  900. ))
  901. pos += 8
  902. continue
  903. case 12:
  904. dest[i] = []byte(fmt.Sprintf(
  905. "%c%02d:%02d:%02d.%06d",
  906. sign,
  907. uint16(data[pos+1])*24+uint16(data[pos+5]),
  908. data[pos+6],
  909. data[pos+7],
  910. binary.LittleEndian.Uint32(data[pos+8:pos+12]),
  911. ))
  912. pos += 12
  913. continue
  914. default:
  915. return fmt.Errorf("Invalid TIME-packet length %d", num)
  916. }
  917. // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  918. case fieldTypeTimestamp, fieldTypeDateTime:
  919. var num uint64
  920. var isNull bool
  921. num, isNull, n = readLengthEncodedInteger(data[pos:])
  922. pos += n
  923. if isNull {
  924. dest[i] = nil
  925. continue
  926. }
  927. if rows.mc.parseTime {
  928. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  929. } else {
  930. dest[i], err = formatBinaryDateTime(num, data[pos:])
  931. }
  932. if err == nil {
  933. pos += int(num)
  934. continue
  935. } else {
  936. return err
  937. }
  938. // Please report if this happens!
  939. default:
  940. return fmt.Errorf("Unknown FieldType %d", rows.columns[i].fieldType)
  941. }
  942. }
  943. return
  944. }