api.go 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package api

import (
	"fmt"
	"io"
22
	"net/http"
23 24 25 26
	"regexp"
	"strings"
	"sync"

27 28 29 30
	"bytes"
	"mime"
	"path/filepath"
	"time"
31 32 33 34

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/swarm/storage"
35 36
)

37
var hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}")
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

type Resolver interface {
	Resolve(string) (common.Hash, error)
}

/*
Api implements webserver/file system related content storage and retrieval
on top of the dpa
it is the public interface of the dpa which is included in the ethereum stack
*/
type Api struct {
	dpa *storage.DPA
	dns Resolver
}

//the api constructor initialises
func NewApi(dpa *storage.DPA, dns Resolver) (self *Api) {
	self = &Api{
		dpa: dpa,
		dns: dns,
	}
	return
}

62 63 64 65 66 67 68
// to be used only in TEST
func (self *Api) Upload(uploadDir, index string) (hash string, err error) {
	fs := NewFileSystem(self)
	hash, err = fs.Upload(uploadDir, index)
	return hash, err
}

69 70 71 72 73 74 75 76 77 78 79 80
// DPA reader API
func (self *Api) Retrieve(key storage.Key) storage.LazySectionReader {
	return self.dpa.Retrieve(key)
}

func (self *Api) Store(data io.Reader, size int64, wg *sync.WaitGroup) (key storage.Key, err error) {
	return self.dpa.Store(data, size, wg, nil)
}

type ErrResolve error

// DNS Resolver
81 82
func (self *Api) Resolve(uri *URI) (storage.Key, error) {
	log.Trace(fmt.Sprintf("Resolving : %v", uri.Addr))
83

84 85
	// if the URI is immutable, check if the address is a hash
	isHash := hashMatcher.MatchString(uri.Addr)
86
	if uri.Immutable() || uri.DeprecatedImmutable() {
87 88
		if !isHash {
			return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
89
		}
90
		return common.Hex2Bytes(uri.Addr), nil
91
	}
92 93 94 95 96 97 98

	// if DNS is not configured, check if the address is a hash
	if self.dns == nil {
		if !isHash {
			return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
		}
		return common.Hex2Bytes(uri.Addr), nil
99
	}
100 101 102 103 104 105 106

	// try and resolve the address
	resolved, err := self.dns.Resolve(uri.Addr)
	if err == nil {
		return resolved[:], nil
	} else if !isHash {
		return nil, err
107
	}
108
	return common.Hex2Bytes(uri.Addr), nil
109 110 111
}

// Put provides singleton manifest creation on top of dpa store
112
func (self *Api) Put(content, contentType string) (storage.Key, error) {
113 114 115 116
	r := strings.NewReader(content)
	wg := &sync.WaitGroup{}
	key, err := self.dpa.Store(r, int64(len(content)), wg, nil)
	if err != nil {
117
		return nil, err
118 119 120 121 122
	}
	manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
	r = strings.NewReader(manifest)
	key, err = self.dpa.Store(r, int64(len(manifest)), wg, nil)
	if err != nil {
123
		return nil, err
124 125
	}
	wg.Wait()
126
	return key, nil
127 128 129
}

// Get uses iterative manifest retrieval and prefix matching
130
// to resolve basePath to content using dpa retrieve
131
// it returns a section reader, mimeType, status and an error
132 133
func (self *Api) Get(key storage.Key, path string) (reader storage.LazySectionReader, mimeType string, status int, err error) {
	trie, err := loadManifest(self.dpa, key, nil)
134
	if err != nil {
135
		status = http.StatusNotFound
136
		log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
137 138 139
		return
	}

140
	log.Trace(fmt.Sprintf("getEntry(%s)", path))
141

142
	entry, _ := trie.getEntry(path)
143

144 145 146
	if entry != nil {
		key = common.Hex2Bytes(entry.Hash)
		status = entry.Status
147 148 149 150 151 152 153
		if status == http.StatusMultipleChoices {
			return
		} else {
			mimeType = entry.ContentType
			log.Trace(fmt.Sprintf("content lookup key: '%v' (%v)", key, mimeType))
			reader = self.dpa.Retrieve(key)
		}
154
	} else {
155
		status = http.StatusNotFound
156
		err = fmt.Errorf("manifest entry for '%s' not found", path)
157
		log.Warn(fmt.Sprintf("%v", err))
158 159 160 161
	}
	return
}

162
func (self *Api) Modify(key storage.Key, path, contentHash, contentType string) (storage.Key, error) {
163
	quitC := make(chan bool)
164
	trie, err := loadManifest(self.dpa, key, quitC)
165
	if err != nil {
166
		return nil, err
167 168
	}
	if contentHash != "" {
169
		entry := newManifestTrieEntry(&ManifestEntry{
170 171
			Path:        path,
			ContentType: contentType,
172 173
		}, nil)
		entry.Hash = contentHash
174 175 176 177 178
		trie.addEntry(entry, quitC)
	} else {
		trie.deleteEntry(path, quitC)
	}

179 180
	if err := trie.recalcAndStore(); err != nil {
		return nil, err
181
	}
182
	return trie.hash, nil
183
}
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

func (self *Api) AddFile(mhash, path, fname string, content []byte, nameresolver bool) (storage.Key, string, error) {

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return nil, "", err
	}
	mkey, err := self.Resolve(uri)
	if err != nil {
		return nil, "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

	entry := &ManifestEntry{
		Path:        filepath.Join(path, fname),
		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
		Mode:        0700,
		Size:        int64(len(content)),
		ModTime:     time.Now(),
	}

	mw, err := self.NewManifestWriter(mkey, nil)
	if err != nil {
		return nil, "", err
	}

	fkey, err := mw.AddEntry(bytes.NewReader(content), entry)
	if err != nil {
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
		return nil, "", err

	}

	return fkey, newMkey.String(), nil

}

func (self *Api) RemoveFile(mhash, path, fname string, nameresolver bool) (string, error) {

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return "", err
	}
	mkey, err := self.Resolve(uri)
	if err != nil {
		return "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

	mw, err := self.NewManifestWriter(mkey, nil)
	if err != nil {
		return "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
		return "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
		return "", err

	}

	return newMkey.String(), nil
}

func (self *Api) AppendFile(mhash, path, fname string, existingSize int64, content []byte, oldKey storage.Key, offset int64, addSize int64, nameresolver bool) (storage.Key, string, error) {

	buffSize := offset + addSize
	if buffSize < existingSize {
		buffSize = existingSize
	}

	buf := make([]byte, buffSize)

	oldReader := self.Retrieve(oldKey)
	io.ReadAtLeast(oldReader, buf, int(offset))

	newReader := bytes.NewReader(content)
	io.ReadAtLeast(newReader, buf[offset:], int(addSize))

	if buffSize < existingSize {
		io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
	}

	combinedReader := bytes.NewReader(buf)
	totalSize := int64(len(buf))

	// TODO(jmozah): to append using pyramid chunker when it is ready
	//oldReader := self.Retrieve(oldKey)
	//newReader := bytes.NewReader(content)
	//combinedReader := io.MultiReader(oldReader, newReader)

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return nil, "", err
	}
	mkey, err := self.Resolve(uri)
	if err != nil {
		return nil, "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

	mw, err := self.NewManifestWriter(mkey, nil)
	if err != nil {
		return nil, "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
		return nil, "", err
	}

	entry := &ManifestEntry{
		Path:        filepath.Join(path, fname),
		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
		Mode:        0700,
		Size:        totalSize,
		ModTime:     time.Now(),
	}

	fkey, err := mw.AddEntry(io.Reader(combinedReader), entry)
	if err != nil {
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
		return nil, "", err

	}

	return fkey, newMkey.String(), nil

}

func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storage.Key, manifestEntryMap map[string]*manifestTrieEntry, err error) {
	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return nil, nil, err
	}
	key, err = self.Resolve(uri)
	if err != nil {
		return nil, nil, err
	}

	quitC := make(chan bool)
	rootTrie, err := loadManifest(self.dpa, key, quitC)
	if err != nil {
		return nil, nil, fmt.Errorf("can't load manifest %v: %v", key.String(), err)
	}

	manifestEntryMap = map[string]*manifestTrieEntry{}
	err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
		manifestEntryMap[suffix] = entry
	})

359 360 361
	if err != nil {
		return nil, nil, fmt.Errorf("list with prefix failed %v: %v", key.String(), err)
	}
362 363
	return key, manifestEntryMap, nil
}