packets.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. // warning count [2 bytes]
  452. if !mc.strict {
  453. return nil
  454. }
  455. pos := 1 + n + m + 2
  456. if binary.LittleEndian.Uint16(data[pos:pos+2]) > 0 {
  457. return mc.getWarnings()
  458. }
  459. return nil
  460. }
  461. // Read Packets as Field Packets until EOF-Packet or an Error appears
  462. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41
  463. func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) {
  464. columns := make([]mysqlField, count)
  465. for i := 0; ; i++ {
  466. data, err := mc.readPacket()
  467. if err != nil {
  468. return nil, err
  469. }
  470. // EOF Packet
  471. if data[0] == iEOF && (len(data) == 5 || len(data) == 1) {
  472. if i == count {
  473. return columns, nil
  474. }
  475. return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns))
  476. }
  477. // Catalog
  478. pos, err := skipLengthEncodedString(data)
  479. if err != nil {
  480. return nil, err
  481. }
  482. // Database [len coded string]
  483. n, err := skipLengthEncodedString(data[pos:])
  484. if err != nil {
  485. return nil, err
  486. }
  487. pos += n
  488. // Table [len coded string]
  489. if mc.cfg.ColumnsWithAlias {
  490. tableName, _, n, err := readLengthEncodedString(data[pos:])
  491. if err != nil {
  492. return nil, err
  493. }
  494. pos += n
  495. columns[i].tableName = string(tableName)
  496. } else {
  497. n, err = skipLengthEncodedString(data[pos:])
  498. if err != nil {
  499. return nil, err
  500. }
  501. pos += n
  502. }
  503. // Original table [len coded string]
  504. n, err = skipLengthEncodedString(data[pos:])
  505. if err != nil {
  506. return nil, err
  507. }
  508. pos += n
  509. // Name [len coded string]
  510. name, _, n, err := readLengthEncodedString(data[pos:])
  511. if err != nil {
  512. return nil, err
  513. }
  514. columns[i].name = string(name)
  515. pos += n
  516. // Original name [len coded string]
  517. n, err = skipLengthEncodedString(data[pos:])
  518. if err != nil {
  519. return nil, err
  520. }
  521. // Filler [uint8]
  522. // Charset [charset, collation uint8]
  523. // Length [uint32]
  524. pos += n + 1 + 2 + 4
  525. // Field type [uint8]
  526. columns[i].fieldType = data[pos]
  527. pos++
  528. // Flags [uint16]
  529. columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
  530. pos += 2
  531. // Decimals [uint8]
  532. columns[i].decimals = data[pos]
  533. //pos++
  534. // Default value [len coded binary]
  535. //if pos < len(data) {
  536. // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
  537. //}
  538. }
  539. }
  540. // Read Packets as Field Packets until EOF-Packet or an Error appears
  541. // http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow
  542. func (rows *textRows) readRow(dest []driver.Value) error {
  543. mc := rows.mc
  544. data, err := mc.readPacket()
  545. if err != nil {
  546. return err
  547. }
  548. // EOF Packet
  549. if data[0] == iEOF && len(data) == 5 {
  550. // server_status [2 bytes]
  551. rows.mc.status = readStatus(data[3:])
  552. if err := rows.mc.discardMoreResultsIfExists(); err != nil {
  553. return err
  554. }
  555. rows.mc = nil
  556. return io.EOF
  557. }
  558. if data[0] == iERR {
  559. rows.mc = nil
  560. return mc.handleErrorPacket(data)
  561. }
  562. // RowSet Packet
  563. var n int
  564. var isNull bool
  565. pos := 0
  566. for i := range dest {
  567. // Read bytes and convert to string
  568. dest[i], isNull, n, err = readLengthEncodedString(data[pos:])
  569. pos += n
  570. if err == nil {
  571. if !isNull {
  572. if !mc.parseTime {
  573. continue
  574. } else {
  575. switch rows.columns[i].fieldType {
  576. case fieldTypeTimestamp, fieldTypeDateTime,
  577. fieldTypeDate, fieldTypeNewDate:
  578. dest[i], err = parseDateTime(
  579. string(dest[i].([]byte)),
  580. mc.cfg.Loc,
  581. )
  582. if err == nil {
  583. continue
  584. }
  585. default:
  586. continue
  587. }
  588. }
  589. } else {
  590. dest[i] = nil
  591. continue
  592. }
  593. }
  594. return err // err != nil
  595. }
  596. return nil
  597. }
  598. // Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
  599. func (mc *mysqlConn) readUntilEOF() error {
  600. for {
  601. data, err := mc.readPacket()
  602. // No Err and no EOF Packet
  603. if err == nil && data[0] != iEOF {
  604. continue
  605. }
  606. if err == nil && data[0] == iEOF && len(data) == 5 {
  607. mc.status = readStatus(data[3:])
  608. }
  609. return err // Err or EOF
  610. }
  611. }
  612. /******************************************************************************
  613. * Prepared Statements *
  614. ******************************************************************************/
  615. // Prepare Result Packets
  616. // http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html
  617. func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) {
  618. data, err := stmt.mc.readPacket()
  619. if err == nil {
  620. // packet indicator [1 byte]
  621. if data[0] != iOK {
  622. return 0, stmt.mc.handleErrorPacket(data)
  623. }
  624. // statement id [4 bytes]
  625. stmt.id = binary.LittleEndian.Uint32(data[1:5])
  626. // Column count [16 bit uint]
  627. columnCount := binary.LittleEndian.Uint16(data[5:7])
  628. // Param count [16 bit uint]
  629. stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9]))
  630. // Reserved [8 bit]
  631. // Warning count [16 bit uint]
  632. if !stmt.mc.strict {
  633. return columnCount, nil
  634. }
  635. // Check for warnings count > 0, only available in MySQL > 4.1
  636. if len(data) >= 12 && binary.LittleEndian.Uint16(data[10:12]) > 0 {
  637. return columnCount, stmt.mc.getWarnings()
  638. }
  639. return columnCount, nil
  640. }
  641. return 0, err
  642. }
  643. // http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html
  644. func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
  645. maxLen := stmt.mc.maxPacketAllowed - 1
  646. pktLen := maxLen
  647. // After the header (bytes 0-3) follows before the data:
  648. // 1 byte command
  649. // 4 bytes stmtID
  650. // 2 bytes paramID
  651. const dataOffset = 1 + 4 + 2
  652. // Can not use the write buffer since
  653. // a) the buffer is too small
  654. // b) it is in use
  655. data := make([]byte, 4+1+4+2+len(arg))
  656. copy(data[4+dataOffset:], arg)
  657. for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset {
  658. if dataOffset+argLen < maxLen {
  659. pktLen = dataOffset + argLen
  660. }
  661. stmt.mc.sequence = 0
  662. // Add command byte [1 byte]
  663. data[4] = comStmtSendLongData
  664. // Add stmtID [32 bit]
  665. data[5] = byte(stmt.id)
  666. data[6] = byte(stmt.id >> 8)
  667. data[7] = byte(stmt.id >> 16)
  668. data[8] = byte(stmt.id >> 24)
  669. // Add paramID [16 bit]
  670. data[9] = byte(paramID)
  671. data[10] = byte(paramID >> 8)
  672. // Send CMD packet
  673. err := stmt.mc.writePacket(data[:4+pktLen])
  674. if err == nil {
  675. data = data[pktLen-dataOffset:]
  676. continue
  677. }
  678. return err
  679. }
  680. // Reset Packet Sequence
  681. stmt.mc.sequence = 0
  682. return nil
  683. }
  684. // Execute Prepared Statement
  685. // http://dev.mysql.com/doc/internals/en/com-stmt-execute.html
  686. func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  687. if len(args) != stmt.paramCount {
  688. return fmt.Errorf(
  689. "argument count mismatch (got: %d; has: %d)",
  690. len(args),
  691. stmt.paramCount,
  692. )
  693. }
  694. const minPktLen = 4 + 1 + 4 + 1 + 4
  695. mc := stmt.mc
  696. // Reset packet-sequence
  697. mc.sequence = 0
  698. var data []byte
  699. if len(args) == 0 {
  700. data = mc.buf.takeBuffer(minPktLen)
  701. } else {
  702. data = mc.buf.takeCompleteBuffer()
  703. }
  704. if data == nil {
  705. // can not take the buffer. Something must be wrong with the connection
  706. errLog.Print(ErrBusyBuffer)
  707. return driver.ErrBadConn
  708. }
  709. // command [1 byte]
  710. data[4] = comStmtExecute
  711. // statement_id [4 bytes]
  712. data[5] = byte(stmt.id)
  713. data[6] = byte(stmt.id >> 8)
  714. data[7] = byte(stmt.id >> 16)
  715. data[8] = byte(stmt.id >> 24)
  716. // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]
  717. data[9] = 0x00
  718. // iteration_count (uint32(1)) [4 bytes]
  719. data[10] = 0x01
  720. data[11] = 0x00
  721. data[12] = 0x00
  722. data[13] = 0x00
  723. if len(args) > 0 {
  724. pos := minPktLen
  725. var nullMask []byte
  726. if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= len(data) {
  727. // buffer has to be extended but we don't know by how much so
  728. // we depend on append after all data with known sizes fit.
  729. // We stop at that because we deal with a lot of columns here
  730. // which makes the required allocation size hard to guess.
  731. tmp := make([]byte, pos+maskLen+typesLen)
  732. copy(tmp[:pos], data[:pos])
  733. data = tmp
  734. nullMask = data[pos : pos+maskLen]
  735. pos += maskLen
  736. } else {
  737. nullMask = data[pos : pos+maskLen]
  738. for i := 0; i < maskLen; i++ {
  739. nullMask[i] = 0
  740. }
  741. pos += maskLen
  742. }
  743. // newParameterBoundFlag 1 [1 byte]
  744. data[pos] = 0x01
  745. pos++
  746. // type of each parameter [len(args)*2 bytes]
  747. paramTypes := data[pos:]
  748. pos += len(args) * 2
  749. // value of each parameter [n bytes]
  750. paramValues := data[pos:pos]
  751. valuesCap := cap(paramValues)
  752. for i, arg := range args {
  753. // build NULL-bitmap
  754. if arg == nil {
  755. nullMask[i/8] |= 1 << (uint(i) & 7)
  756. paramTypes[i+i] = fieldTypeNULL
  757. paramTypes[i+i+1] = 0x00
  758. continue
  759. }
  760. // cache types and values
  761. switch v := arg.(type) {
  762. case int64:
  763. paramTypes[i+i] = fieldTypeLongLong
  764. paramTypes[i+i+1] = 0x00
  765. if cap(paramValues)-len(paramValues)-8 >= 0 {
  766. paramValues = paramValues[:len(paramValues)+8]
  767. binary.LittleEndian.PutUint64(
  768. paramValues[len(paramValues)-8:],
  769. uint64(v),
  770. )
  771. } else {
  772. paramValues = append(paramValues,
  773. uint64ToBytes(uint64(v))...,
  774. )
  775. }
  776. case float64:
  777. paramTypes[i+i] = fieldTypeDouble
  778. paramTypes[i+i+1] = 0x00
  779. if cap(paramValues)-len(paramValues)-8 >= 0 {
  780. paramValues = paramValues[:len(paramValues)+8]
  781. binary.LittleEndian.PutUint64(
  782. paramValues[len(paramValues)-8:],
  783. math.Float64bits(v),
  784. )
  785. } else {
  786. paramValues = append(paramValues,
  787. uint64ToBytes(math.Float64bits(v))...,
  788. )
  789. }
  790. case bool:
  791. paramTypes[i+i] = fieldTypeTiny
  792. paramTypes[i+i+1] = 0x00
  793. if v {
  794. paramValues = append(paramValues, 0x01)
  795. } else {
  796. paramValues = append(paramValues, 0x00)
  797. }
  798. case []byte:
  799. // Common case (non-nil value) first
  800. if v != nil {
  801. paramTypes[i+i] = fieldTypeString
  802. paramTypes[i+i+1] = 0x00
  803. if len(v) < mc.maxPacketAllowed-pos-len(paramValues)-(len(args)-(i+1))*64 {
  804. paramValues = appendLengthEncodedInteger(paramValues,
  805. uint64(len(v)),
  806. )
  807. paramValues = append(paramValues, v...)
  808. } else {
  809. if err := stmt.writeCommandLongData(i, v); err != nil {
  810. return err
  811. }
  812. }
  813. continue
  814. }
  815. // Handle []byte(nil) as a NULL value
  816. nullMask[i/8] |= 1 << (uint(i) & 7)
  817. paramTypes[i+i] = fieldTypeNULL
  818. paramTypes[i+i+1] = 0x00
  819. case string:
  820. paramTypes[i+i] = fieldTypeString
  821. paramTypes[i+i+1] = 0x00
  822. if len(v) < mc.maxPacketAllowed-pos-len(paramValues)-(len(args)-(i+1))*64 {
  823. paramValues = appendLengthEncodedInteger(paramValues,
  824. uint64(len(v)),
  825. )
  826. paramValues = append(paramValues, v...)
  827. } else {
  828. if err := stmt.writeCommandLongData(i, []byte(v)); err != nil {
  829. return err
  830. }
  831. }
  832. case time.Time:
  833. paramTypes[i+i] = fieldTypeString
  834. paramTypes[i+i+1] = 0x00
  835. var val []byte
  836. if v.IsZero() {
  837. val = []byte("0000-00-00")
  838. } else {
  839. val = []byte(v.In(mc.cfg.Loc).Format(timeFormat))
  840. }
  841. paramValues = appendLengthEncodedInteger(paramValues,
  842. uint64(len(val)),
  843. )
  844. paramValues = append(paramValues, val...)
  845. default:
  846. return fmt.Errorf("can not convert type: %T", arg)
  847. }
  848. }
  849. // Check if param values exceeded the available buffer
  850. // In that case we must build the data packet with the new values buffer
  851. if valuesCap != cap(paramValues) {
  852. data = append(data[:pos], paramValues...)
  853. mc.buf.buf = data
  854. }
  855. pos += len(paramValues)
  856. data = data[:pos]
  857. }
  858. return mc.writePacket(data)
  859. }
  860. func (mc *mysqlConn) discardMoreResultsIfExists() error {
  861. for mc.status&statusMoreResultsExists != 0 {
  862. resLen, err := mc.readResultSetHeaderPacket()
  863. if err != nil {
  864. return err
  865. }
  866. if resLen > 0 {
  867. // columns
  868. if err := mc.readUntilEOF(); err != nil {
  869. return err
  870. }
  871. // rows
  872. if err := mc.readUntilEOF(); err != nil {
  873. return err
  874. }
  875. } else {
  876. mc.status &^= statusMoreResultsExists
  877. }
  878. }
  879. return nil
  880. }
  881. // http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html
  882. func (rows *binaryRows) readRow(dest []driver.Value) error {
  883. data, err := rows.mc.readPacket()
  884. if err != nil {
  885. return err
  886. }
  887. // packet indicator [1 byte]
  888. if data[0] != iOK {
  889. // EOF Packet
  890. if data[0] == iEOF && len(data) == 5 {
  891. rows.mc.status = readStatus(data[3:])
  892. if err := rows.mc.discardMoreResultsIfExists(); err != nil {
  893. return err
  894. }
  895. rows.mc = nil
  896. return io.EOF
  897. }
  898. rows.mc = nil
  899. // Error otherwise
  900. return rows.mc.handleErrorPacket(data)
  901. }
  902. // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]
  903. pos := 1 + (len(dest)+7+2)>>3
  904. nullMask := data[1:pos]
  905. for i := range dest {
  906. // Field is NULL
  907. // (byte >> bit-pos) % 2 == 1
  908. if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {
  909. dest[i] = nil
  910. continue
  911. }
  912. // Convert to byte-coded string
  913. switch rows.columns[i].fieldType {
  914. case fieldTypeNULL:
  915. dest[i] = nil
  916. continue
  917. // Numeric Types
  918. case fieldTypeTiny:
  919. if rows.columns[i].flags&flagUnsigned != 0 {
  920. dest[i] = int64(data[pos])
  921. } else {
  922. dest[i] = int64(int8(data[pos]))
  923. }
  924. pos++
  925. continue
  926. case fieldTypeShort, fieldTypeYear:
  927. if rows.columns[i].flags&flagUnsigned != 0 {
  928. dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
  929. } else {
  930. dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
  931. }
  932. pos += 2
  933. continue
  934. case fieldTypeInt24, fieldTypeLong:
  935. if rows.columns[i].flags&flagUnsigned != 0 {
  936. dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
  937. } else {
  938. dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
  939. }
  940. pos += 4
  941. continue
  942. case fieldTypeLongLong:
  943. if rows.columns[i].flags&flagUnsigned != 0 {
  944. val := binary.LittleEndian.Uint64(data[pos : pos+8])
  945. if val > math.MaxInt64 {
  946. dest[i] = uint64ToString(val)
  947. } else {
  948. dest[i] = int64(val)
  949. }
  950. } else {
  951. dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))
  952. }
  953. pos += 8
  954. continue
  955. case fieldTypeFloat:
  956. dest[i] = float64(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
  957. pos += 4
  958. continue
  959. case fieldTypeDouble:
  960. dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))
  961. pos += 8
  962. continue
  963. // Length coded Binary Strings
  964. case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,
  965. fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,
  966. fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,
  967. fieldTypeVarString, fieldTypeString, fieldTypeGeometry:
  968. var isNull bool
  969. var n int
  970. dest[i], isNull, n, err = readLengthEncodedString(data[pos:])
  971. pos += n
  972. if err == nil {
  973. if !isNull {
  974. continue
  975. } else {
  976. dest[i] = nil
  977. continue
  978. }
  979. }
  980. return err
  981. case
  982. fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD
  983. fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal]
  984. fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]
  985. num, isNull, n := readLengthEncodedInteger(data[pos:])
  986. pos += n
  987. switch {
  988. case isNull:
  989. dest[i] = nil
  990. continue
  991. case rows.columns[i].fieldType == fieldTypeTime:
  992. // database/sql does not support an equivalent to TIME, return a string
  993. var dstlen uint8
  994. switch decimals := rows.columns[i].decimals; decimals {
  995. case 0x00, 0x1f:
  996. dstlen = 8
  997. case 1, 2, 3, 4, 5, 6:
  998. dstlen = 8 + 1 + decimals
  999. default:
  1000. return fmt.Errorf(
  1001. "protocol error, illegal decimals value %d",
  1002. rows.columns[i].decimals,
  1003. )
  1004. }
  1005. dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen, true)
  1006. case rows.mc.parseTime:
  1007. dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc)
  1008. default:
  1009. var dstlen uint8
  1010. if rows.columns[i].fieldType == fieldTypeDate {
  1011. dstlen = 10
  1012. } else {
  1013. switch decimals := rows.columns[i].decimals; decimals {
  1014. case 0x00, 0x1f:
  1015. dstlen = 19
  1016. case 1, 2, 3, 4, 5, 6:
  1017. dstlen = 19 + 1 + decimals
  1018. default:
  1019. return fmt.Errorf(
  1020. "protocol error, illegal decimals value %d",
  1021. rows.columns[i].decimals,
  1022. )
  1023. }
  1024. }
  1025. dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen, false)
  1026. }
  1027. if err == nil {
  1028. pos += int(num)
  1029. continue
  1030. } else {
  1031. return err
  1032. }
  1033. // Please report if this happens!
  1034. default:
  1035. return fmt.Errorf("unknown field type %d", rows.columns[i].fieldType)
  1036. }
  1037. }
  1038. return nil
  1039. }