packets.go 27 KB

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