upload.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. "bytes"
  20. "encoding/json"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "mime"
  25. "net/http"
  26. "os"
  27. "os/user"
  28. "path"
  29. "path/filepath"
  30. "strings"
  31. "github.com/ethereum/go-ethereum/cmd/utils"
  32. "github.com/ethereum/go-ethereum/log"
  33. "gopkg.in/urfave/cli.v1"
  34. )
  35. func upload(ctx *cli.Context) {
  36. args := ctx.Args()
  37. var (
  38. bzzapi = strings.TrimRight(ctx.GlobalString(SwarmApiFlag.Name), "/")
  39. recursive = ctx.GlobalBool(SwarmRecursiveUploadFlag.Name)
  40. wantManifest = ctx.GlobalBoolT(SwarmWantManifestFlag.Name)
  41. defaultPath = ctx.GlobalString(SwarmUploadDefaultPath.Name)
  42. )
  43. if len(args) != 1 {
  44. utils.Fatalf("Need filename as the first and only argument")
  45. }
  46. var (
  47. file = args[0]
  48. client = &client{api: bzzapi}
  49. )
  50. fi, err := os.Stat(expandPath(file))
  51. if err != nil {
  52. utils.Fatalf("Failed to stat file: %v", err)
  53. }
  54. if fi.IsDir() {
  55. if !recursive {
  56. utils.Fatalf("Argument is a directory and recursive upload is disabled")
  57. }
  58. if !wantManifest {
  59. utils.Fatalf("Manifest is required for directory uploads")
  60. }
  61. mhash, err := client.uploadDirectory(file, defaultPath)
  62. if err != nil {
  63. utils.Fatalf("Failed to upload directory: %v", err)
  64. }
  65. fmt.Println(mhash)
  66. return
  67. }
  68. entry, err := client.uploadFile(file, fi)
  69. if err != nil {
  70. utils.Fatalf("Upload failed: %v", err)
  71. }
  72. mroot := manifest{[]manifestEntry{entry}}
  73. if !wantManifest {
  74. // Print the manifest. This is the only output to stdout.
  75. mrootJSON, _ := json.MarshalIndent(mroot, "", " ")
  76. fmt.Println(string(mrootJSON))
  77. return
  78. }
  79. hash, err := client.uploadManifest(mroot)
  80. if err != nil {
  81. utils.Fatalf("Manifest upload failed: %v", err)
  82. }
  83. fmt.Println(hash)
  84. }
  85. // Expands a file path
  86. // 1. replace tilde with users home dir
  87. // 2. expands embedded environment variables
  88. // 3. cleans the path, e.g. /a/b/../c -> /a/c
  89. // Note, it has limitations, e.g. ~someuser/tmp will not be expanded
  90. func expandPath(p string) string {
  91. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  92. if home := homeDir(); home != "" {
  93. p = home + p[1:]
  94. }
  95. }
  96. return path.Clean(os.ExpandEnv(p))
  97. }
  98. func homeDir() string {
  99. if home := os.Getenv("HOME"); home != "" {
  100. return home
  101. }
  102. if usr, err := user.Current(); err == nil {
  103. return usr.HomeDir
  104. }
  105. return ""
  106. }
  107. // client wraps interaction with the swarm HTTP gateway.
  108. type client struct {
  109. api string
  110. }
  111. // manifest is the JSON representation of a swarm manifest.
  112. type manifestEntry struct {
  113. Hash string `json:"hash,omitempty"`
  114. ContentType string `json:"contentType,omitempty"`
  115. Path string `json:"path,omitempty"`
  116. }
  117. // manifest is the JSON representation of a swarm manifest.
  118. type manifest struct {
  119. Entries []manifestEntry `json:"entries,omitempty"`
  120. }
  121. func (c *client) uploadDirectory(dir string, defaultPath string) (string, error) {
  122. mhash, err := c.postRaw("application/json", 2, ioutil.NopCloser(bytes.NewReader([]byte("{}"))))
  123. if err != nil {
  124. return "", fmt.Errorf("failed to upload empty manifest")
  125. }
  126. if len(defaultPath) > 0 {
  127. fi, err := os.Stat(defaultPath)
  128. if err != nil {
  129. return "", err
  130. }
  131. mhash, err = c.uploadToManifest(mhash, "", defaultPath, fi)
  132. if err != nil {
  133. return "", err
  134. }
  135. }
  136. prefix := filepath.ToSlash(filepath.Clean(dir)) + "/"
  137. err = filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  138. if err != nil || fi.IsDir() {
  139. return err
  140. }
  141. if !strings.HasPrefix(path, dir) {
  142. return fmt.Errorf("path %s outside directory %s", path, dir)
  143. }
  144. uripath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean(path)), prefix)
  145. mhash, err = c.uploadToManifest(mhash, uripath, path, fi)
  146. return err
  147. })
  148. return mhash, err
  149. }
  150. func (c *client) uploadFile(file string, fi os.FileInfo) (manifestEntry, error) {
  151. hash, err := c.uploadFileContent(file, fi)
  152. m := manifestEntry{
  153. Hash: hash,
  154. ContentType: mime.TypeByExtension(filepath.Ext(fi.Name())),
  155. }
  156. return m, err
  157. }
  158. func (c *client) uploadFileContent(file string, fi os.FileInfo) (string, error) {
  159. fd, err := os.Open(file)
  160. if err != nil {
  161. return "", err
  162. }
  163. defer fd.Close()
  164. log.Info("Uploading swarm content", "file", file, "bytes", fi.Size())
  165. return c.postRaw("application/octet-stream", fi.Size(), fd)
  166. }
  167. func (c *client) uploadManifest(m manifest) (string, error) {
  168. jsm, err := json.Marshal(m)
  169. if err != nil {
  170. panic(err)
  171. }
  172. log.Info("Uploading swarm manifest")
  173. return c.postRaw("application/json", int64(len(jsm)), ioutil.NopCloser(bytes.NewReader(jsm)))
  174. }
  175. func (c *client) uploadToManifest(mhash string, path string, fpath string, fi os.FileInfo) (string, error) {
  176. fd, err := os.Open(fpath)
  177. if err != nil {
  178. return "", err
  179. }
  180. defer fd.Close()
  181. log.Info("Uploading swarm content and path", "file", fpath, "bytes", fi.Size(), "path", path)
  182. req, err := http.NewRequest("PUT", c.api+"/bzz:/"+mhash+"/"+path, fd)
  183. if err != nil {
  184. return "", err
  185. }
  186. req.Header.Set("content-type", mime.TypeByExtension(filepath.Ext(fi.Name())))
  187. req.ContentLength = fi.Size()
  188. resp, err := http.DefaultClient.Do(req)
  189. if err != nil {
  190. return "", err
  191. }
  192. defer resp.Body.Close()
  193. if resp.StatusCode >= 400 {
  194. return "", fmt.Errorf("bad status: %s", resp.Status)
  195. }
  196. content, err := ioutil.ReadAll(resp.Body)
  197. return string(content), err
  198. }
  199. func (c *client) postRaw(mimetype string, size int64, body io.ReadCloser) (string, error) {
  200. req, err := http.NewRequest("POST", c.api+"/bzzr:/", body)
  201. if err != nil {
  202. return "", err
  203. }
  204. req.Header.Set("content-type", mimetype)
  205. req.ContentLength = size
  206. resp, err := http.DefaultClient.Do(req)
  207. if err != nil {
  208. return "", err
  209. }
  210. defer resp.Body.Close()
  211. if resp.StatusCode >= 400 {
  212. return "", fmt.Errorf("bad status: %s", resp.Status)
  213. }
  214. content, err := ioutil.ReadAll(resp.Body)
  215. return string(content), err
  216. }
  217. func (c *client) downloadManifest(mhash string) (manifest, error) {
  218. mroot := manifest{}
  219. req, err := http.NewRequest("GET", c.api+"/bzzr:/"+mhash, nil)
  220. if err != nil {
  221. return mroot, err
  222. }
  223. resp, err := http.DefaultClient.Do(req)
  224. if err != nil {
  225. return mroot, err
  226. }
  227. defer resp.Body.Close()
  228. if resp.StatusCode >= 400 {
  229. return mroot, fmt.Errorf("bad status: %s", resp.Status)
  230. }
  231. content, err := ioutil.ReadAll(resp.Body)
  232. err = json.Unmarshal(content, &mroot)
  233. if err != nil {
  234. return mroot, fmt.Errorf("Manifest %v is malformed: %v", mhash, err)
  235. }
  236. return mroot, err
  237. }