embed.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package frankenphp
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "crypto/md5"
  6. _ "embed"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/fs"
  12. "log"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strings"
  18. "time"
  19. )
  20. // The path of the embedded PHP application (empty if none)
  21. var EmbeddedAppPath string
  22. //go:embed app.tar
  23. var embeddedApp []byte
  24. func init() {
  25. if len(embeddedApp) == 0 {
  26. // No embedded app
  27. return
  28. }
  29. h := md5.Sum(embeddedApp)
  30. appPath := filepath.Join(os.TempDir(), "frankenphp_"+hex.EncodeToString(h[:]))
  31. if err := os.RemoveAll(appPath); err != nil {
  32. panic(err)
  33. }
  34. if err := untar(appPath); err != nil {
  35. os.RemoveAll(appPath)
  36. panic(err)
  37. }
  38. EmbeddedAppPath = appPath
  39. }
  40. // untar reads the tar file from r and writes it into dir.
  41. //
  42. // Adapted from https://github.com/golang/build/blob/master/cmd/buildlet/buildlet.go
  43. func untar(dir string) (err error) {
  44. t0 := time.Now()
  45. nFiles := 0
  46. madeDir := map[string]bool{}
  47. tr := tar.NewReader(bytes.NewReader(embeddedApp))
  48. loggedChtimesError := false
  49. for {
  50. f, err := tr.Next()
  51. if err == io.EOF {
  52. break
  53. }
  54. if err != nil {
  55. return fmt.Errorf("tar error: %w", err)
  56. }
  57. if f.Typeflag == tar.TypeXGlobalHeader {
  58. // golang.org/issue/22748: git archive exports
  59. // a global header ('g') which after Go 1.9
  60. // (for a bit?) contained an empty filename.
  61. // Ignore it.
  62. continue
  63. }
  64. rel, err := nativeRelPath(f.Name)
  65. if err != nil {
  66. return fmt.Errorf("tar file contained invalid name %q: %v", f.Name, err)
  67. }
  68. abs := filepath.Join(dir, rel)
  69. fi := f.FileInfo()
  70. mode := fi.Mode()
  71. switch {
  72. case mode.IsRegular():
  73. // Make the directory. This is redundant because it should
  74. // already be made by a directory entry in the tar
  75. // beforehand. Thus, don't check for errors; the next
  76. // write will fail with the same error.
  77. dir := filepath.Dir(abs)
  78. if !madeDir[dir] {
  79. if err := os.MkdirAll(filepath.Dir(abs), mode.Perm()); err != nil {
  80. return err
  81. }
  82. madeDir[dir] = true
  83. }
  84. if runtime.GOOS == "darwin" && mode&0111 != 0 {
  85. // See comment in writeFile.
  86. err := os.Remove(abs)
  87. if err != nil && !errors.Is(err, fs.ErrNotExist) {
  88. return err
  89. }
  90. }
  91. wf, err := os.OpenFile(abs, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode.Perm())
  92. if err != nil {
  93. return err
  94. }
  95. n, err := io.Copy(wf, tr)
  96. if closeErr := wf.Close(); closeErr != nil && err == nil {
  97. err = closeErr
  98. }
  99. if err != nil {
  100. return fmt.Errorf("error writing to %s: %v", abs, err)
  101. }
  102. if n != f.Size {
  103. return fmt.Errorf("only wrote %d bytes to %s; expected %d", n, abs, f.Size)
  104. }
  105. modTime := f.ModTime
  106. if modTime.After(t0) {
  107. // Clamp modtimes at system time. See
  108. // golang.org/issue/19062 when clock on
  109. // buildlet was behind the gitmirror server
  110. // doing the git-archive.
  111. modTime = t0
  112. }
  113. if !modTime.IsZero() {
  114. if err := os.Chtimes(abs, modTime, modTime); err != nil && !loggedChtimesError {
  115. // benign error. Gerrit doesn't even set the
  116. // modtime in these, and we don't end up relying
  117. // on it anywhere (the gomote push command relies
  118. // on digests only), so this is a little pointless
  119. // for now.
  120. log.Printf("error changing modtime: %v (further Chtimes errors suppressed)", err)
  121. loggedChtimesError = true // once is enough
  122. }
  123. }
  124. nFiles++
  125. case mode.IsDir():
  126. if err := os.MkdirAll(abs, mode.Perm()); err != nil {
  127. return err
  128. }
  129. madeDir[abs] = true
  130. case mode&os.ModeSymlink != 0:
  131. // TODO: ignore these for now. They were breaking x/build tests.
  132. // Implement these if/when we ever have a test that needs them.
  133. // But maybe we'd have to skip creating them on Windows for some builders
  134. // without permissions.
  135. default:
  136. return fmt.Errorf("tar file entry %s contained unsupported file type %v", f.Name, mode)
  137. }
  138. }
  139. return nil
  140. }
  141. // nativeRelPath verifies that p is a non-empty relative path
  142. // using either slashes or the buildlet's native path separator,
  143. // and returns it canonicalized to the native path separator.
  144. func nativeRelPath(p string) (string, error) {
  145. if p == "" {
  146. return "", errors.New("path not provided")
  147. }
  148. if filepath.Separator != '/' && strings.Contains(p, string(filepath.Separator)) {
  149. clean := filepath.Clean(p)
  150. if filepath.IsAbs(clean) {
  151. return "", fmt.Errorf("path %q is not relative", p)
  152. }
  153. if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
  154. return "", fmt.Errorf("path %q refers to a parent directory", p)
  155. }
  156. if strings.HasPrefix(p, string(filepath.Separator)) || filepath.VolumeName(clean) != "" {
  157. // On Windows, this catches semi-relative paths like "C:" (meaning “the
  158. // current working directory on volume C:”) and "\windows" (meaning “the
  159. // windows subdirectory of the current drive letter”).
  160. return "", fmt.Errorf("path %q is relative to volume", p)
  161. }
  162. return p, nil
  163. }
  164. clean := path.Clean(p)
  165. if path.IsAbs(clean) {
  166. return "", fmt.Errorf("path %q is not relative", p)
  167. }
  168. if clean == ".." || strings.HasPrefix(clean, "../") {
  169. return "", fmt.Errorf("path %q refers to a parent directory", p)
  170. }
  171. canon := filepath.FromSlash(p)
  172. if filepath.VolumeName(canon) != "" {
  173. return "", fmt.Errorf("path %q begins with a native volume name", p)
  174. }
  175. return canon, nil
  176. }