tftp.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package pxe
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net"
  21. "os"
  22. "path/filepath"
  23. "regexp"
  24. "yunion.io/x/log"
  25. "yunion.io/x/onecloud/pkg/baremetal/options"
  26. "yunion.io/x/onecloud/pkg/util/tftp"
  27. )
  28. var (
  29. PxeLinuxCfgPattern = `^pxelinux.cfg/01-(?P<mac>([0-9a-f]{2}-){5}[0-9a-f]{2})$`
  30. GrubCfgPattern = `grub/grub.cfg-01-(?P<mac>([0-9a-f]{2}-){5}[0-9a-f]{2})$`
  31. )
  32. type TFTPHandler struct {
  33. RootDir string
  34. BaremetalManager IBaremetalManager
  35. }
  36. func NewTFTPHandler(rootDir string, baremetalManager IBaremetalManager) (*TFTPHandler, error) {
  37. if _, err := os.Stat(rootDir); err != nil {
  38. return nil, fmt.Errorf("TFTP root dir %q stat error: %v", rootDir, err)
  39. }
  40. return &TFTPHandler{
  41. RootDir: rootDir,
  42. BaremetalManager: baremetalManager,
  43. }, nil
  44. }
  45. // Handle is called when client starts file download from server
  46. func (h *TFTPHandler) Handle(filename string, clientAddr net.Addr) (io.ReadCloser, int64, error) {
  47. regPxeEx := regexp.MustCompile(PxeLinuxCfgPattern)
  48. pxeMatches := regPxeEx.FindStringSubmatch(filename)
  49. regGrubEx := regexp.MustCompile(GrubCfgPattern)
  50. grubMatches := regGrubEx.FindStringSubmatch(filename)
  51. if len(pxeMatches) != 0 || len(grubMatches) != 0 {
  52. paramsMap := make(map[string]string)
  53. // pxelinux config matched
  54. for i, name := range regPxeEx.SubexpNames() {
  55. if i > 0 && i <= len(pxeMatches) {
  56. paramsMap[name] = pxeMatches[i]
  57. }
  58. }
  59. // grub config matched
  60. for i, name := range regGrubEx.SubexpNames() {
  61. if i > 0 && i <= len(grubMatches) {
  62. paramsMap[name] = grubMatches[i]
  63. }
  64. }
  65. mac, ok := paramsMap["mac"]
  66. if !ok {
  67. return nil, 0, fmt.Errorf("request filename %q not found mac pattern", filename)
  68. }
  69. macAddr, err := net.ParseMAC(mac)
  70. if err != nil {
  71. return nil, 0, fmt.Errorf("Parse mac string %q error: %v", mac, err)
  72. }
  73. return h.sendPxeLinuxCfgResponse(macAddr, clientAddr)
  74. }
  75. return h.sendFile(filename, clientAddr)
  76. }
  77. func (h *TFTPHandler) sendPxeLinuxCfgResponse(mac net.HardwareAddr, _ net.Addr) (io.ReadCloser, int64, error) {
  78. log.Debugf("[TFTP] client mac: %s", mac)
  79. bmInstance := h.BaremetalManager.GetBaremetalByMac(mac)
  80. if bmInstance == nil {
  81. err := fmt.Errorf("Not found baremetal instance by mac: %s", mac)
  82. log.Errorf("Get baremetal error: %v", err)
  83. return nil, 0, err
  84. }
  85. respStr := bmInstance.GetTFTPResponse()
  86. log.Debugf("[TFTP] get tftp response config: %s", respStr)
  87. bs := []byte(respStr)
  88. size := int64(len(bs))
  89. buffer := bytes.NewBufferString(respStr)
  90. return ioutil.NopCloser(buffer), size, nil
  91. }
  92. func (h *TFTPHandler) sendFile(filename string, _ net.Addr) (io.ReadCloser, int64, error) {
  93. filename = h.getFilePath(filename)
  94. st, err := os.Stat(filename)
  95. if err != nil {
  96. log.Errorf("TFTP stat file %q error: %v", filename, err)
  97. return nil, 0, err
  98. }
  99. if !st.Mode().IsRegular() {
  100. return nil, 0, fmt.Errorf("requested path %q is not a file", filename)
  101. }
  102. file, err := os.Open(filename)
  103. if err != nil {
  104. log.Errorf("TFTP open file %q error: %v", filename, err)
  105. return nil, 0, err
  106. }
  107. return file, st.Size(), err
  108. }
  109. func (h *TFTPHandler) getFilePath(fileName string) string {
  110. if path, ok := options.Options.TftpFileMap[fileName]; ok {
  111. return path
  112. }
  113. return filepath.Join(h.RootDir, fileName)
  114. }
  115. func (h *TFTPHandler) transferLog(clientAddr net.Addr, path string, err error) {
  116. log.Debugf("TFTP transfer log clientAddr: %s, path: %s, error: %v", clientAddr, path, err)
  117. }
  118. func (s *Server) serveTFTP(l net.PacketConn, handler *TFTPHandler) error {
  119. bindDial := func(network, addr string) (net.Conn, error) {
  120. localIp := l.LocalAddr().(*net.UDPAddr).IP
  121. remoteAddr, err := net.ResolveUDPAddr("udp", addr)
  122. if err != nil {
  123. return nil, err
  124. }
  125. log.Debugf("[TFTP] dial udp localAddr %s, remoteAddr: %s", localIp, remoteAddr.String())
  126. return net.DialUDP("udp", &net.UDPAddr{
  127. IP: localIp,
  128. Port: 0, // random free port
  129. }, remoteAddr)
  130. }
  131. ts := tftp.Server{
  132. Handler: handler.Handle,
  133. InfoLog: func(msg string) { log.Debugf("TFTP msg: %s", msg) },
  134. TransferLog: handler.transferLog,
  135. Dial: bindDial,
  136. MaxBlockSize: int64(options.Options.TftpBlockSizeInBytes),
  137. WriteAttempts: options.Options.TftpMaxTimeoutRetries,
  138. }
  139. err := ts.Serve(l)
  140. if err != nil {
  141. return fmt.Errorf("TFTP server shut down: %v", err)
  142. }
  143. return nil
  144. }