upload.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // Command bzzup uploads files to the swarm HTTP API.
  17. package main
  18. import (
  19. "errors"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "os"
  24. "os/user"
  25. "path"
  26. "path/filepath"
  27. "strconv"
  28. "strings"
  29. "github.com/ethereum/go-ethereum/log"
  30. swarm "github.com/ethereum/go-ethereum/swarm/api/client"
  31. "github.com/ethereum/go-ethereum/cmd/utils"
  32. "gopkg.in/urfave/cli.v1"
  33. )
  34. var upCommand = cli.Command{
  35. Action: upload,
  36. CustomHelpTemplate: helpTemplate,
  37. Name: "up",
  38. Usage: "uploads a file or directory to swarm using the HTTP API",
  39. ArgsUsage: "<file>",
  40. Flags: []cli.Flag{SwarmEncryptedFlag},
  41. Description: "uploads a file or directory to swarm using the HTTP API and prints the root hash",
  42. }
  43. func upload(ctx *cli.Context) {
  44. args := ctx.Args()
  45. var (
  46. bzzapi = strings.TrimRight(ctx.GlobalString(SwarmApiFlag.Name), "/")
  47. recursive = ctx.GlobalBool(SwarmRecursiveFlag.Name)
  48. wantManifest = ctx.GlobalBoolT(SwarmWantManifestFlag.Name)
  49. defaultPath = ctx.GlobalString(SwarmUploadDefaultPath.Name)
  50. fromStdin = ctx.GlobalBool(SwarmUpFromStdinFlag.Name)
  51. mimeType = ctx.GlobalString(SwarmUploadMimeType.Name)
  52. client = swarm.NewClient(bzzapi)
  53. toEncrypt = ctx.Bool(SwarmEncryptedFlag.Name)
  54. autoDefaultPath = false
  55. file string
  56. )
  57. if autoDefaultPathString := os.Getenv(SwarmAutoDefaultPath); autoDefaultPathString != "" {
  58. b, err := strconv.ParseBool(autoDefaultPathString)
  59. if err != nil {
  60. utils.Fatalf("invalid environment variable %s: %v", SwarmAutoDefaultPath, err)
  61. }
  62. autoDefaultPath = b
  63. }
  64. if len(args) != 1 {
  65. if fromStdin {
  66. tmp, err := ioutil.TempFile("", "swarm-stdin")
  67. if err != nil {
  68. utils.Fatalf("error create tempfile: %s", err)
  69. }
  70. defer os.Remove(tmp.Name())
  71. n, err := io.Copy(tmp, os.Stdin)
  72. if err != nil {
  73. utils.Fatalf("error copying stdin to tempfile: %s", err)
  74. } else if n == 0 {
  75. utils.Fatalf("error reading from stdin: zero length")
  76. }
  77. file = tmp.Name()
  78. } else {
  79. utils.Fatalf("Need filename as the first and only argument")
  80. }
  81. } else {
  82. file = expandPath(args[0])
  83. }
  84. if !wantManifest {
  85. f, err := swarm.Open(file)
  86. if err != nil {
  87. utils.Fatalf("Error opening file: %s", err)
  88. }
  89. defer f.Close()
  90. hash, err := client.UploadRaw(f, f.Size, toEncrypt)
  91. if err != nil {
  92. utils.Fatalf("Upload failed: %s", err)
  93. }
  94. fmt.Println(hash)
  95. return
  96. }
  97. stat, err := os.Stat(file)
  98. if err != nil {
  99. utils.Fatalf("Error opening file: %s", err)
  100. }
  101. // define a function which either uploads a directory or single file
  102. // based on the type of the file being uploaded
  103. var doUpload func() (hash string, err error)
  104. if stat.IsDir() {
  105. doUpload = func() (string, error) {
  106. if !recursive {
  107. return "", errors.New("Argument is a directory and recursive upload is disabled")
  108. }
  109. if autoDefaultPath && defaultPath == "" {
  110. defaultEntryCandidate := path.Join(file, "index.html")
  111. log.Debug("trying to find default path", "path", defaultEntryCandidate)
  112. defaultEntryStat, err := os.Stat(defaultEntryCandidate)
  113. if err == nil && !defaultEntryStat.IsDir() {
  114. log.Debug("setting auto detected default path", "path", defaultEntryCandidate)
  115. defaultPath = defaultEntryCandidate
  116. }
  117. }
  118. if defaultPath != "" {
  119. // construct absolute default path
  120. absDefaultPath, _ := filepath.Abs(defaultPath)
  121. absFile, _ := filepath.Abs(file)
  122. // make sure absolute directory ends with only one "/"
  123. // to trim it from absolute default path and get relative default path
  124. absFile = strings.TrimRight(absFile, "/") + "/"
  125. if absDefaultPath != "" && absFile != "" && strings.HasPrefix(absDefaultPath, absFile) {
  126. defaultPath = strings.TrimPrefix(absDefaultPath, absFile)
  127. }
  128. }
  129. return client.UploadDirectory(file, defaultPath, "", toEncrypt)
  130. }
  131. } else {
  132. doUpload = func() (string, error) {
  133. f, err := swarm.Open(file)
  134. if err != nil {
  135. return "", fmt.Errorf("error opening file: %s", err)
  136. }
  137. defer f.Close()
  138. if mimeType != "" {
  139. f.ContentType = mimeType
  140. }
  141. return client.Upload(f, "", toEncrypt)
  142. }
  143. }
  144. hash, err := doUpload()
  145. if err != nil {
  146. utils.Fatalf("Upload failed: %s", err)
  147. }
  148. fmt.Println(hash)
  149. }
  150. // Expands a file path
  151. // 1. replace tilde with users home dir
  152. // 2. expands embedded environment variables
  153. // 3. cleans the path, e.g. /a/b/../c -> /a/c
  154. // Note, it has limitations, e.g. ~someuser/tmp will not be expanded
  155. func expandPath(p string) string {
  156. if i := strings.Index(p, ":"); i > 0 {
  157. return p
  158. }
  159. if i := strings.Index(p, "@"); i > 0 {
  160. return p
  161. }
  162. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  163. if home := homeDir(); home != "" {
  164. p = home + p[1:]
  165. }
  166. }
  167. return path.Clean(os.ExpandEnv(p))
  168. }
  169. func homeDir() string {
  170. if home := os.Getenv("HOME"); home != "" {
  171. return home
  172. }
  173. if usr, err := user.Current(); err == nil {
  174. return usr.HomeDir
  175. }
  176. return ""
  177. }