packets.go 32 KB

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