packets.go 32 KB

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