tftp.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package tftp
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "regexp"
  7. "strings"
  8. "github.com/rancher/os/config/cloudinit/datasource"
  9. "github.com/pin/tftp"
  10. )
  11. type Client interface {
  12. Receive(filename string, mode string) (io.WriterTo, error)
  13. }
  14. type RemoteFile struct {
  15. host string
  16. path string
  17. client Client
  18. stream io.WriterTo
  19. lastError error
  20. }
  21. func NewDatasource(hostAndPath string) *RemoteFile {
  22. parts := strings.SplitN(hostAndPath, "/", 2)
  23. if len(parts) < 2 {
  24. return &RemoteFile{hostAndPath, "", nil, nil, nil}
  25. }
  26. host := parts[0]
  27. if match, _ := regexp.MatchString(":[0-9]{2,5}$", host); !match {
  28. // No port, using default port 69
  29. host += ":69"
  30. }
  31. path := parts[1]
  32. if client, lastError := tftp.NewClient(host); lastError == nil {
  33. return &RemoteFile{host, path, client, nil, nil}
  34. }
  35. return &RemoteFile{host, path, nil, nil, nil}
  36. }
  37. func (f *RemoteFile) IsAvailable() bool {
  38. f.stream, f.lastError = f.client.Receive(f.path, "octet")
  39. return f.lastError == nil
  40. }
  41. func (f *RemoteFile) Finish() error {
  42. return nil
  43. }
  44. func (f *RemoteFile) String() string {
  45. return fmt.Sprintf("%s: %s%s (lastError: %v)", f.Type(), f.host, f.path, f.lastError)
  46. }
  47. func (f *RemoteFile) AvailabilityChanges() bool {
  48. return false
  49. }
  50. func (f *RemoteFile) ConfigRoot() string {
  51. return ""
  52. }
  53. func (f *RemoteFile) FetchMetadata() (datasource.Metadata, error) {
  54. return datasource.Metadata{}, nil
  55. }
  56. func (f *RemoteFile) FetchUserdata() ([]byte, error) {
  57. var b bytes.Buffer
  58. _, err := f.stream.WriteTo(&b)
  59. return b.Bytes(), err
  60. }
  61. func (f *RemoteFile) Type() string {
  62. return "tftp"
  63. }