infile.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 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. "fmt"
  11. "io"
  12. "os"
  13. "strings"
  14. "sync"
  15. )
  16. var (
  17. fileRegister map[string]bool
  18. fileRegisterLock sync.RWMutex
  19. readerRegister map[string]func() io.Reader
  20. readerRegisterLock sync.RWMutex
  21. )
  22. // RegisterLocalFile adds the given file to the file allowlist,
  23. // so that it can be used by "LOAD DATA LOCAL INFILE <filepath>".
  24. // Alternatively you can allow the use of all local files with
  25. // the DSN parameter 'allowAllFiles=true'
  26. //
  27. // filePath := "/home/gopher/data.csv"
  28. // mysql.RegisterLocalFile(filePath)
  29. // err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo")
  30. // if err != nil {
  31. // ...
  32. func RegisterLocalFile(filePath string) {
  33. fileRegisterLock.Lock()
  34. // lazy map init
  35. if fileRegister == nil {
  36. fileRegister = make(map[string]bool)
  37. }
  38. fileRegister[strings.Trim(filePath, `"`)] = true
  39. fileRegisterLock.Unlock()
  40. }
  41. // DeregisterLocalFile removes the given filepath from the allowlist.
  42. func DeregisterLocalFile(filePath string) {
  43. fileRegisterLock.Lock()
  44. delete(fileRegister, strings.Trim(filePath, `"`))
  45. fileRegisterLock.Unlock()
  46. }
  47. // RegisterReaderHandler registers a handler function which is used
  48. // to receive a io.Reader.
  49. // The Reader can be used by "LOAD DATA LOCAL INFILE Reader::<name>".
  50. // If the handler returns a io.ReadCloser Close() is called when the
  51. // request is finished.
  52. //
  53. // mysql.RegisterReaderHandler("data", func() io.Reader {
  54. // var csvReader io.Reader // Some Reader that returns CSV data
  55. // ... // Open Reader here
  56. // return csvReader
  57. // })
  58. // err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo")
  59. // if err != nil {
  60. // ...
  61. func RegisterReaderHandler(name string, handler func() io.Reader) {
  62. readerRegisterLock.Lock()
  63. // lazy map init
  64. if readerRegister == nil {
  65. readerRegister = make(map[string]func() io.Reader)
  66. }
  67. readerRegister[name] = handler
  68. readerRegisterLock.Unlock()
  69. }
  70. // DeregisterReaderHandler removes the ReaderHandler function with
  71. // the given name from the registry.
  72. func DeregisterReaderHandler(name string) {
  73. readerRegisterLock.Lock()
  74. delete(readerRegister, name)
  75. readerRegisterLock.Unlock()
  76. }
  77. func deferredClose(err *error, closer io.Closer) {
  78. closeErr := closer.Close()
  79. if *err == nil {
  80. *err = closeErr
  81. }
  82. }
  83. const defaultPacketSize = 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP
  84. func (mc *okHandler) handleInFileRequest(name string) (err error) {
  85. var rdr io.Reader
  86. var data []byte
  87. packetSize := defaultPacketSize
  88. if mc.maxWriteSize < packetSize {
  89. packetSize = mc.maxWriteSize
  90. }
  91. if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader
  92. // The server might return an an absolute path. See issue #355.
  93. name = name[idx+8:]
  94. readerRegisterLock.RLock()
  95. handler, inMap := readerRegister[name]
  96. readerRegisterLock.RUnlock()
  97. if inMap {
  98. rdr = handler()
  99. if rdr != nil {
  100. if cl, ok := rdr.(io.Closer); ok {
  101. defer deferredClose(&err, cl)
  102. }
  103. } else {
  104. err = fmt.Errorf("reader '%s' is <nil>", name)
  105. }
  106. } else {
  107. err = fmt.Errorf("reader '%s' is not registered", name)
  108. }
  109. } else { // File
  110. name = strings.Trim(name, `"`)
  111. fileRegisterLock.RLock()
  112. fr := fileRegister[name]
  113. fileRegisterLock.RUnlock()
  114. if mc.cfg.AllowAllFiles || fr {
  115. var file *os.File
  116. var fi os.FileInfo
  117. if file, err = os.Open(name); err == nil {
  118. defer deferredClose(&err, file)
  119. // get file size
  120. if fi, err = file.Stat(); err == nil {
  121. rdr = file
  122. if fileSize := int(fi.Size()); fileSize < packetSize {
  123. packetSize = fileSize
  124. }
  125. }
  126. }
  127. } else {
  128. err = fmt.Errorf("local file '%s' is not registered", name)
  129. }
  130. }
  131. // send content packets
  132. // if packetSize == 0, the Reader contains no data
  133. if err == nil && packetSize > 0 {
  134. data := make([]byte, 4+packetSize)
  135. var n int
  136. for err == nil {
  137. n, err = rdr.Read(data[4:])
  138. if n > 0 {
  139. if ioErr := mc.conn().writePacket(data[:4+n]); ioErr != nil {
  140. return ioErr
  141. }
  142. }
  143. }
  144. if err == io.EOF {
  145. err = nil
  146. }
  147. }
  148. // send empty packet (termination)
  149. if data == nil {
  150. data = make([]byte, 4)
  151. }
  152. if ioErr := mc.conn().writePacket(data[:4]); ioErr != nil {
  153. return ioErr
  154. }
  155. // read OK packet
  156. if err == nil {
  157. return mc.readResultOK()
  158. }
  159. mc.conn().readPacket()
  160. return err
  161. }