packets.go 32 KB

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