packets.go 27 KB

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