packets.go 34 KB

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