upload.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. mroot manifest
  49. entry manifestEntry
  50. )
  51. fi, err := os.Stat(expandPath(file))
  52. if err != nil {
  53. log.Fatal(err)
  54. }
  55. if fi.IsDir() {
  56. if !recursive {
  57. log.Fatal("argument is a directory and recursive upload is disabled")
  58. }
  59. mroot, err = client.uploadDirectory(file, defaultPath)
  60. } else {
  61. entry, err = client.uploadFile(file, fi)
  62. mroot = manifest{[]manifestEntry{entry}}
  63. }
  64. if err != nil {
  65. log.Fatalln("upload failed:", err)
  66. }
  67. if !wantManifest {
  68. // Print the manifest. This is the only output to stdout.
  69. mrootJSON, _ := json.MarshalIndent(mroot, "", " ")
  70. fmt.Println(string(mrootJSON))
  71. return
  72. }
  73. hash, err := client.uploadManifest(mroot)
  74. if err != nil {
  75. log.Fatalln("manifest upload failed:", err)
  76. }
  77. fmt.Println(hash)
  78. }
  79. // Expands a file path
  80. // 1. replace tilde with users home dir
  81. // 2. expands embedded environment variables
  82. // 3. cleans the path, e.g. /a/b/../c -> /a/c
  83. // Note, it has limitations, e.g. ~someuser/tmp will not be expanded
  84. func expandPath(p string) string {
  85. if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
  86. if home := homeDir(); home != "" {
  87. p = home + p[1:]
  88. }
  89. }
  90. return path.Clean(os.ExpandEnv(p))
  91. }
  92. func homeDir() string {
  93. if home := os.Getenv("HOME"); home != "" {
  94. return home
  95. }
  96. if usr, err := user.Current(); err == nil {
  97. return usr.HomeDir
  98. }
  99. return ""
  100. }
  101. // client wraps interaction with the swarm HTTP gateway.
  102. type client struct {
  103. api string
  104. }
  105. // manifest is the JSON representation of a swarm manifest.
  106. type manifestEntry struct {
  107. Hash string `json:"hash,omitempty"`
  108. ContentType string `json:"contentType,omitempty"`
  109. Path string `json:"path,omitempty"`
  110. }
  111. // manifest is the JSON representation of a swarm manifest.
  112. type manifest struct {
  113. Entries []manifestEntry `json:"entries,omitempty"`
  114. }
  115. func (c *client) uploadFile(file string, fi os.FileInfo) (manifestEntry, error) {
  116. hash, err := c.uploadFileContent(file, fi)
  117. m := manifestEntry{
  118. Hash: hash,
  119. ContentType: mime.TypeByExtension(filepath.Ext(fi.Name())),
  120. }
  121. return m, err
  122. }
  123. func (c *client) uploadDirectory(dir string, defaultPath string) (manifest, error) {
  124. dirm := manifest{}
  125. if len(defaultPath) > 0 {
  126. fi, err := os.Stat(defaultPath)
  127. if err != nil {
  128. log.Fatal(err)
  129. }
  130. entry, err := c.uploadFile(defaultPath, fi)
  131. if err != nil {
  132. log.Fatal(err)
  133. }
  134. entry.Path = ""
  135. dirm.Entries = append(dirm.Entries, entry)
  136. }
  137. prefix := filepath.ToSlash(filepath.Clean(dir)) + "/"
  138. err := filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  139. if err != nil || fi.IsDir() {
  140. return err
  141. }
  142. if !strings.HasPrefix(path, dir) {
  143. return fmt.Errorf("path %s outside directory %s", path, dir)
  144. }
  145. entry, err := c.uploadFile(path, fi)
  146. entry.Path = strings.TrimPrefix(filepath.ToSlash(filepath.Clean(path)), prefix)
  147. dirm.Entries = append(dirm.Entries, entry)
  148. return err
  149. })
  150. return dirm, err
  151. }
  152. func (c *client) uploadFileContent(file string, fi os.FileInfo) (string, error) {
  153. fd, err := os.Open(file)
  154. if err != nil {
  155. return "", err
  156. }
  157. defer fd.Close()
  158. log.Printf("uploading file %s (%d bytes)", file, fi.Size())
  159. return c.postRaw("application/octet-stream", fi.Size(), fd)
  160. }
  161. func (c *client) uploadManifest(m manifest) (string, error) {
  162. jsm, err := json.Marshal(m)
  163. if err != nil {
  164. panic(err)
  165. }
  166. log.Println("uploading manifest")
  167. return c.postRaw("application/json", int64(len(jsm)), ioutil.NopCloser(bytes.NewReader(jsm)))
  168. }
  169. func (c *client) postRaw(mimetype string, size int64, body io.ReadCloser) (string, error) {
  170. req, err := http.NewRequest("POST", c.api+"/bzzr:/", body)
  171. if err != nil {
  172. return "", err
  173. }
  174. req.Header.Set("content-type", mimetype)
  175. req.ContentLength = size
  176. resp, err := http.DefaultClient.Do(req)
  177. if err != nil {
  178. return "", err
  179. }
  180. defer resp.Body.Close()
  181. if resp.StatusCode >= 400 {
  182. return "", fmt.Errorf("bad status: %s", resp.Status)
  183. }
  184. content, err := ioutil.ReadAll(resp.Body)
  185. return string(content), err
  186. }