packets.go 34 KB

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