packets.go 31 KB

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