packets.go 26 KB

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