http urls monitor.

packets.go 31KB

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