You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

packets.go 32KB

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