packets.go 32 KB

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