upload.go 5.28 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Copyright 2016 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

// Command bzzup uploads files to the swarm HTTP API.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime"
	"net/http"
	"os"
30 31
	"os/user"
	"path"
32 33
	"path/filepath"
	"strings"
34 35

	"gopkg.in/urfave/cli.v1"
36 37
)

38 39
func upload(ctx *cli.Context) {
	args := ctx.Args()
40
	var (
41
		bzzapi       = strings.TrimRight(ctx.GlobalString(SwarmApiFlag.Name), "/")
42 43
		recursive    = ctx.GlobalBool(SwarmRecursiveUploadFlag.Name)
		wantManifest = ctx.GlobalBoolT(SwarmWantManifestFlag.Name)
44
		defaultPath  = ctx.GlobalString(SwarmUploadDefaultPath.Name)
45
	)
46
	if len(args) != 1 {
47 48 49 50
		log.Fatal("need filename as the first and only argument")
	}

	var (
51 52
		file   = args[0]
		client = &client{api: bzzapi}
53
		mroot  manifest
54
		entry  manifestEntry
55
	)
56
	fi, err := os.Stat(expandPath(file))
57 58 59 60
	if err != nil {
		log.Fatal(err)
	}
	if fi.IsDir() {
61
		if !recursive {
62 63
			log.Fatal("argument is a directory and recursive upload is disabled")
		}
64
		mroot, err = client.uploadDirectory(file, defaultPath)
65
	} else {
66 67
		entry, err = client.uploadFile(file, fi)
		mroot = manifest{[]manifestEntry{entry}}
68 69 70 71
	}
	if err != nil {
		log.Fatalln("upload failed:", err)
	}
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	if !wantManifest {
		// Print the manifest. This is the only output to stdout.
		mrootJSON, _ := json.MarshalIndent(mroot, "", "  ")
		fmt.Println(string(mrootJSON))
		return
	}
	hash, err := client.uploadManifest(mroot)
	if err != nil {
		log.Fatalln("manifest upload failed:", err)
	}
	fmt.Println(hash)
}

// Expands a file path
// 1. replace tilde with users home dir
// 2. expands embedded environment variables
// 3. cleans the path, e.g. /a/b/../c -> /a/c
// Note, it has limitations, e.g. ~someuser/tmp will not be expanded
func expandPath(p string) string {
	if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
		if home := homeDir(); home != "" {
			p = home + p[1:]
94 95
		}
	}
96 97
	return path.Clean(os.ExpandEnv(p))
}
98

99 100 101 102 103 104 105 106
func homeDir() string {
	if home := os.Getenv("HOME"); home != "" {
		return home
	}
	if usr, err := user.Current(); err == nil {
		return usr.HomeDir
	}
	return ""
107 108 109 110 111 112 113
}

// client wraps interaction with the swarm HTTP gateway.
type client struct {
	api string
}

114 115 116 117 118 119 120
// manifest is the JSON representation of a swarm manifest.
type manifestEntry struct {
	Hash        string `json:"hash,omitempty"`
	ContentType string `json:"contentType,omitempty"`
	Path        string `json:"path,omitempty"`
}

121 122
// manifest is the JSON representation of a swarm manifest.
type manifest struct {
123
	Entries []manifestEntry `json:"entries,omitempty"`
124 125
}

126
func (c *client) uploadFile(file string, fi os.FileInfo) (manifestEntry, error) {
127
	hash, err := c.uploadFileContent(file, fi)
128
	m := manifestEntry{
129 130 131 132 133 134
		Hash:        hash,
		ContentType: mime.TypeByExtension(filepath.Ext(fi.Name())),
	}
	return m, err
}

135
func (c *client) uploadDirectory(dir string, defaultPath string) (manifest, error) {
136
	dirm := manifest{}
137 138 139 140 141 142 143 144 145 146 147 148
	if len(defaultPath) > 0 {
		fi, err := os.Stat(defaultPath)
		if err != nil {
			log.Fatal(err)
		}
		entry, err := c.uploadFile(defaultPath, fi)
		if err != nil {
			log.Fatal(err)
		}
		entry.Path = ""
		dirm.Entries = append(dirm.Entries, entry)
	}
149
	prefix := filepath.ToSlash(filepath.Clean(dir)) + "/"
150 151 152 153 154 155 156 157
	err := filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
		if err != nil || fi.IsDir() {
			return err
		}
		if !strings.HasPrefix(path, dir) {
			return fmt.Errorf("path %s outside directory %s", path, dir)
		}
		entry, err := c.uploadFile(path, fi)
158
		entry.Path = strings.TrimPrefix(filepath.ToSlash(filepath.Clean(path)), prefix)
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		dirm.Entries = append(dirm.Entries, entry)
		return err
	})
	return dirm, err
}

func (c *client) uploadFileContent(file string, fi os.FileInfo) (string, error) {
	fd, err := os.Open(file)
	if err != nil {
		return "", err
	}
	defer fd.Close()
	log.Printf("uploading file %s (%d bytes)", file, fi.Size())
	return c.postRaw("application/octet-stream", fi.Size(), fd)
}

func (c *client) uploadManifest(m manifest) (string, error) {
	jsm, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	log.Println("uploading manifest")
	return c.postRaw("application/json", int64(len(jsm)), ioutil.NopCloser(bytes.NewReader(jsm)))
}

func (c *client) postRaw(mimetype string, size int64, body io.ReadCloser) (string, error) {
	req, err := http.NewRequest("POST", c.api+"/bzzr:/", body)
	if err != nil {
		return "", err
	}
	req.Header.Set("content-type", mimetype)
	req.ContentLength = size
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		return "", fmt.Errorf("bad status: %s", resp.Status)
	}
	content, err := ioutil.ReadAll(resp.Body)
	return string(content), err
}