packets.go 31 KB

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