packets.go 32 KB

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