packets.go 29 KB

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