packets.go 31 KB

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