packets.go 29 KB

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