upload.go 6.2 KB

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