packets.go 32 KB

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