You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

packets.go 32KB

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