packets.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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. if mc.cfg.columnsWithAlias {
  440. tableName, _, n, err := readLengthEncodedString(data[pos:])
  441. if err != nil {
  442. return nil, err
  443. }
  444. pos += n
  445. columns[i].tableName = string(tableName)
  446. } else {
  447. n, err = skipLengthEncodedString(data[pos:])
  448. if err != nil {
  449. return nil, err
  450. }
  451. pos += n
  452. }
  453. // Original table [len coded string]
  454. n, err = skipLengthEncodedString(data[pos:])
  455. if err != nil {
  456. return nil, err
  457. }
  458. pos += n
  459. // Name [len coded string]
  460. name, _, n, err := readLengthEncodedString(data[pos:])
  461. if err != nil {
  462. return nil, err
  463. }
  464. columns[i].name = string(name)
  465. pos += n
  466. // Original name [len coded string]
  467. n, err = skipLengthEncodedString(data[pos:])
  468. if err != nil {
  469. return nil, err
  470. }
  471. // Filler [uint8]
  472. // Charset [charset, collation uint8]
  473. // Length [uint32]
  474. pos += n + 1 + 2 + 4
  475. // Field type [uint8]
  476. columns[i].fieldType = data[pos]
  477. pos++
  478. // Flags [uint16]
  479. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  480. pos += 2
  481. // Decimals [uint8]
  482. columns[i].decimals = data[pos]
  483. //pos++
  484. // Default value [len coded binary]
  485. //if pos < len(data) {
  486. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  487. //}
  488. }
  489. }
  490. // Read Packets as Field Packets until EOF-Packet or an Error appears
  491. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow
  492. func (rows *textRows) readRow(dest []driver.Value) error {
  493. mc := rows.mc
  494. data, err := mc.readPacket()
  495. if err != nil {
  496. return err
  497. }
  498. // EOF Packet
  499. if data[0] == iEOF && len(data) == 5 {
  500. return io.EOF
  501. }
  502. // RowSet Packet
  503. var n int
  504. var isNull bool
  505. pos := 0
  506. for i := range dest {
  507. // Read bytes and convert to string
  508. dest[i], isNull, n, err = readLengthEncodedString(data[pos:])
  509. pos += n
  510. if err == nil {
  511. if !isNull {
  512. if !mc.parseTime {
  513. continue
  514. } else {
  515. switch rows.columns[i].fieldType {
  516. case fieldTypeTimestamp, fieldTypeDateTime,
  517. fieldTypeDate, fieldTypeNewDate:
  518. dest[i], err = parseDateTime(
  519. string(dest[i].([]byte)),
  520. mc.cfg.loc,
  521. )
  522. if err == nil {
  523. continue
  524. }
  525. default:
  526. continue
  527. }
  528. }
  529. } else {
  530. dest[i] = nil
  531. continue
  532. }
  533. }
  534. return err // err != nil
  535. }
  536. return nil
  537. }
  538. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  539. func (mc *mysqlConn) readUntilEOF() error {
  540. for {
  541. data, err := mc.readPacket()
  542. // No Err and no EOF Packet
  543. if err == nil && data[0] != iEOF {
  544. continue
  545. }
  546. return err // Err or EOF
  547. }
  548. }
  549. /******************************************************************************
  550. * Prepared Statements *
  551. ******************************************************************************/
  552. // Prepare Result Packets
  553. // http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html
  554. func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) {
  555. data, err := stmt.mc.readPacket()
  556. if err == nil {
  557. // packet indicator [1 byte]
  558. if data[0] != iOK {
  559. return 0, stmt.mc.handleErrorPacket(data)
  560. }
  561. // statement id [4 bytes]
  562. stmt.id = binary.LittleEndian.Uint32(data[1:5])
  563. // Column count [16 bit uint]
  564. columnCount := binary.LittleEndian.Uint16(data[5:7])
  565. // Param count [16 bit uint]
  566. stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9]))
  567. // Reserved [8 bit]
  568. // Warning count [16 bit uint]
  569. if !stmt.mc.strict {
  570. return columnCount, nil
  571. } else {
  572. // Check for warnings count > 0, only available in MySQL > 4.1
  573. if len(data) >= 12 && binary.LittleEndian.Uint16(data[10:12]) > 0 {
  574. return columnCount, stmt.mc.getWarnings()
  575. }
  576. return columnCount, nil
  577. }
  578. }
  579. return 0, err
  580. }
  581. // http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html
  582. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
  583. maxLen := stmt.mc.maxPacketAllowed - 1
  584. pktLen := maxLen
  585. // After the header (bytes 0-3) follows before the data:
  586. // 1 byte command
  587. // 4 bytes stmtID
  588. // 2 bytes paramID
  589. const dataOffset = 1 + 4 + 2
  590. // Can not use the write buffer since
  591. // a) the buffer is too small
  592. // b) it is in use
  593. data := make([]byte, 4+1+4+2+len(arg))
  594. copy(data[4+dataOffset:], arg)
  595. for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset {
  596. if dataOffset+argLen < maxLen {
  597. pktLen = dataOffset + argLen
  598. }
  599. stmt.mc.sequence = 0
  600. // Add command byte [1 byte]
  601. data[4] = comStmtSendLongData
  602. // Add stmtID [32 bit]
  603. data[5] = byte(stmt.id)
  604. data[6] = byte(stmt.id >> 8)
  605. data[7] = byte(stmt.id >> 16)
  606. data[8] = byte(stmt.id >> 24)
  607. // Add paramID [16 bit]
  608. data[9] = byte(paramID)
  609. data[10] = byte(paramID >> 8)
  610. // Send CMD packet
  611. err := stmt.mc.writePacket(data[:4+pktLen])
  612. if err == nil {
  613. data = data[pktLen-dataOffset:]
  614. continue
  615. }
  616. return err
  617. }
  618. // Reset Packet Sequence
  619. stmt.mc.sequence = 0
  620. return nil
  621. }
  622. // Execute Prepared Statement
  623. // http://dev.mysql.com/doc/internals/en/com-stmt-execute.html
  624. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  625. if len(args) != stmt.paramCount {
  626. return fmt.Errorf(
  627. "Arguments count mismatch (Got: %d Has: %d)",
  628. len(args),
  629. stmt.paramCount,
  630. )
  631. }
  632. const minPktLen = 4 + 1 + 4 + 1 + 4
  633. mc := stmt.mc
  634. // Reset packet-sequence
  635. mc.sequence = 0
  636. var data []byte
  637. if len(args) == 0 {
  638. data = mc.buf.takeBuffer(minPktLen)
  639. } else {
  640. data = mc.buf.takeCompleteBuffer()
  641. }
  642. if data == nil {
  643. // can not take the buffer. Something must be wrong with the connection
  644. errLog.Print(ErrBusyBuffer)
  645. return driver.ErrBadConn
  646. }
  647. // command [1 byte]
  648. data[4] = comStmtExecute
  649. // statement_id [4 bytes]
  650. data[5] = byte(stmt.id)
  651. data[6] = byte(stmt.id >> 8)
  652. data[7] = byte(stmt.id >> 16)
  653. data[8] = byte(stmt.id >> 24)
  654. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  655. data[9] = 0x00
  656. // iteration_count (uint32(1)) [4 bytes]
  657. data[10] = 0x01
  658. data[11] = 0x00
  659. data[12] = 0x00
  660. data[13] = 0x00
  661. if len(args) > 0 {
  662. pos := minPktLen
  663. var nullMask []byte
  664. if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= len(data) {
  665. // buffer has to be extended but we don't know by how much so
  666. // we depend on append after all data with known sizes fit.
  667. // We stop at that because we deal with a lot of columns here
  668. // which makes the required allocation size hard to guess.
  669. tmp := make([]byte, pos+maskLen+typesLen)
  670. copy(tmp[:pos], data[:pos])
  671. data = tmp
  672. nullMask = data[pos : pos+maskLen]
  673. pos += maskLen
  674. } else {
  675. nullMask = data[pos : pos+maskLen]
  676. for i := 0; i < maskLen; i++ {
  677. nullMask[i] = 0
  678. }
  679. pos += maskLen
  680. }
  681. // newParameterBoundFlag 1 [1 byte]
  682. data[pos] = 0x01
  683. pos++
  684. // type of each parameter [len(args)*2 bytes]
  685. paramTypes := data[pos:]
  686. pos += len(args) * 2
  687. // value of each parameter [n bytes]
  688. paramValues := data[pos:pos]
  689. valuesCap := cap(paramValues)
  690. for i, arg := range args {
  691. // build NULL-bitmap
  692. if arg == nil {
  693. nullMask[i/8] |= 1 << (uint(i) & 7)
  694. paramTypes[i+i] = fieldTypeNULL
  695. paramTypes[i+i+1] = 0x00
  696. continue
  697. }
  698. // cache types and values
  699. switch v := arg.(type) {
  700. case int64:
  701. paramTypes[i+i] = fieldTypeLongLong
  702. paramTypes[i+i+1] = 0x00
  703. if cap(paramValues)-len(paramValues)-8 >= 0 {
  704. paramValues = paramValues[:len(paramValues)+8]
  705. binary.LittleEndian.PutUint64(
  706. paramValues[len(paramValues)-8:],
  707. uint64(v),
  708. )
  709. } else {
  710. paramValues = append(paramValues,
  711. uint64ToBytes(uint64(v))...,
  712. )
  713. }
  714. case float64:
  715. paramTypes[i+i] = fieldTypeDouble
  716. paramTypes[i+i+1] = 0x00
  717. if cap(paramValues)-len(paramValues)-8 >= 0 {
  718. paramValues = paramValues[:len(paramValues)+8]
  719. binary.LittleEndian.PutUint64(
  720. paramValues[len(paramValues)-8:],
  721. math.Float64bits(v),
  722. )
  723. } else {
  724. paramValues = append(paramValues,
  725. uint64ToBytes(math.Float64bits(v))...,
  726. )
  727. }
  728. case bool:
  729. paramTypes[i+i] = fieldTypeTiny
  730. paramTypes[i+i+1] = 0x00
  731. if v {
  732. paramValues = append(paramValues, 0x01)
  733. } else {
  734. paramValues = append(paramValues, 0x00)
  735. }
  736. case []byte:
  737. // Common case (non-nil value) first
  738. if v != nil {
  739. paramTypes[i+i] = fieldTypeString
  740. paramTypes[i+i+1] = 0x00
  741. if len(v) < mc.maxPacketAllowed-pos-len(paramValues)-(len(args)-(i+1))*64 {
  742. paramValues = appendLengthEncodedInteger(paramValues,
  743. uint64(len(v)),
  744. )
  745. paramValues = append(paramValues, v...)
  746. } else {
  747. if err := stmt.writeCommandLongData(i, v); err != nil {
  748. return err
  749. }
  750. }
  751. continue
  752. }
  753. // Handle []byte(nil) as a NULL value
  754. nullMask[i/8] |= 1 << (uint(i) & 7)
  755. paramTypes[i+i] = fieldTypeNULL
  756. paramTypes[i+i+1] = 0x00
  757. case string:
  758. paramTypes[i+i] = fieldTypeString
  759. paramTypes[i+i+1] = 0x00
  760. if len(v) < mc.maxPacketAllowed-pos-len(paramValues)-(len(args)-(i+1))*64 {
  761. paramValues = appendLengthEncodedInteger(paramValues,
  762. uint64(len(v)),
  763. )
  764. paramValues = append(paramValues, v...)
  765. } else {
  766. if err := stmt.writeCommandLongData(i, []byte(v)); err != nil {
  767. return err
  768. }
  769. }
  770. case time.Time:
  771. paramTypes[i+i] = fieldTypeString
  772. paramTypes[i+i+1] = 0x00
  773. var val []byte
  774. if v.IsZero() {
  775. val = []byte("0000-00-00")
  776. } else {
  777. val = []byte(v.In(mc.cfg.loc).Format(timeFormat))
  778. }
  779. paramValues = appendLengthEncodedInteger(paramValues,
  780. uint64(len(val)),
  781. )
  782. paramValues = append(paramValues, val...)
  783. default:
  784. return fmt.Errorf("Can't convert type: %T", arg)
  785. }
  786. }
  787. // Check if param values exceeded the available buffer
  788. // In that case we must build the data packet with the new values buffer
  789. if valuesCap != cap(paramValues) {
  790. data = append(data[:pos], paramValues...)
  791. mc.buf.buf = data
  792. }
  793. pos += len(paramValues)
  794. data = data[:pos]
  795. }
  796. return mc.writePacket(data)
  797. }
  798. // http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html
  799. func (rows *binaryRows) readRow(dest []driver.Value) error {
  800. data, err := rows.mc.readPacket()
  801. if err != nil {
  802. return err
  803. }
  804. // packet indicator [1 byte]
  805. if data[0] != iOK {
  806. // EOF Packet
  807. if data[0] == iEOF && len(data) == 5 {
  808. return io.EOF
  809. }
  810. // Error otherwise
  811. return rows.mc.handleErrorPacket(data)
  812. }
  813. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  814. pos := 1 + (len(dest)+7+2)>>3
  815. nullMask := data[1:pos]
  816. for i := range dest {
  817. // Field is NULL
  818. // (byte >> bit-pos) % 2 == 1
  819. if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  820. dest[i] = nil
  821. continue
  822. }
  823. // Convert to byte-coded string
  824. switch rows.columns[i].fieldType {
  825. case fieldTypeNULL:
  826. dest[i] = nil
  827. continue
  828. // Numeric Types
  829. case fieldTypeTiny:
  830. if rows.columns[i].flags&flagUnsigned != 0 {
  831. dest[i] = int64(data[pos])
  832. } else {
  833. dest[i] = int64(int8(data[pos]))
  834. }
  835. pos++
  836. continue
  837. case fieldTypeShort, fieldTypeYear:
  838. if rows.columns[i].flags&flagUnsigned != 0 {
  839. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  840. } else {
  841. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  842. }
  843. pos += 2
  844. continue
  845. case fieldTypeInt24, fieldTypeLong:
  846. if rows.columns[i].flags&flagUnsigned != 0 {
  847. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  848. } else {
  849. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  850. }
  851. pos += 4
  852. continue
  853. case fieldTypeLongLong:
  854. if rows.columns[i].flags&flagUnsigned != 0 {
  855. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  856. if val > math.MaxInt64 {
  857. dest[i] = uint64ToString(val)
  858. } else {
  859. dest[i] = int64(val)
  860. }
  861. } else {
  862. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  863. }
  864. pos += 8
  865. continue
  866. case fieldTypeFloat:
  867. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  868. pos += 4
  869. continue
  870. case fieldTypeDouble:
  871. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  872. pos += 8
  873. continue
  874. // Length coded Binary Strings
  875. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  876. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  877. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  878. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  879. var isNull bool
  880. var n int
  881. dest[i], isNull, n, err = readLengthEncodedString(data[pos:])
  882. pos += n
  883. if err == nil {
  884. if !isNull {
  885. continue
  886. } else {
  887. dest[i] = nil
  888. continue
  889. }
  890. }
  891. return err
  892. case
  893. fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD
  894. fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal]
  895. fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  896. num, isNull, n := readLengthEncodedInteger(data[pos:])
  897. pos += n
  898. switch {
  899. case isNull:
  900. dest[i] = nil
  901. continue
  902. case rows.columns[i].fieldType == fieldTypeTime:
  903. // database/sql does not support an equivalent to TIME, return a string
  904. var dstlen uint8
  905. switch decimals := rows.columns[i].decimals; decimals {
  906. case 0x00, 0x1f:
  907. dstlen = 8
  908. case 1, 2, 3, 4, 5, 6:
  909. dstlen = 8 + 1 + decimals
  910. default:
  911. return fmt.Errorf(
  912. "MySQL protocol error, illegal decimals value %d",
  913. rows.columns[i].decimals,
  914. )
  915. }
  916. dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen, true)
  917. case rows.mc.parseTime:
  918. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.loc)
  919. default:
  920. var dstlen uint8
  921. if rows.columns[i].fieldType == fieldTypeDate {
  922. dstlen = 10
  923. } else {
  924. switch decimals := rows.columns[i].decimals; decimals {
  925. case 0x00, 0x1f:
  926. dstlen = 19
  927. case 1, 2, 3, 4, 5, 6:
  928. dstlen = 19 + 1 + decimals
  929. default:
  930. return fmt.Errorf(
  931. "MySQL protocol error, illegal decimals value %d",
  932. rows.columns[i].decimals,
  933. )
  934. }
  935. }
  936. dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen, false)
  937. }
  938. if err == nil {
  939. pos += int(num)
  940. continue
  941. } else {
  942. return err
  943. }
  944. // Please report if this happens!
  945. default:
  946. return fmt.Errorf("Unknown FieldType %d", rows.columns[i].fieldType)
  947. }
  948. }
  949. return nil
  950. }