packets.go 31 KB

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