api.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package api
  17. import (
  18. "fmt"
  19. "io"
  20. "net/http"
  21. "regexp"
  22. "strings"
  23. "sync"
  24. "bytes"
  25. "mime"
  26. "path/filepath"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/swarm/storage"
  31. )
  32. var hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}")
  33. type Resolver interface {
  34. Resolve(string) (common.Hash, error)
  35. }
  36. /*
  37. Api implements webserver/file system related content storage and retrieval
  38. on top of the dpa
  39. it is the public interface of the dpa which is included in the ethereum stack
  40. */
  41. type Api struct {
  42. dpa *storage.DPA
  43. dns Resolver
  44. }
  45. //the api constructor initialises
  46. func NewApi(dpa *storage.DPA, dns Resolver) (self *Api) {
  47. self = &Api{
  48. dpa: dpa,
  49. dns: dns,
  50. }
  51. return
  52. }
  53. // to be used only in TEST
  54. func (self *Api) Upload(uploadDir, index string) (hash string, err error) {
  55. fs := NewFileSystem(self)
  56. hash, err = fs.Upload(uploadDir, index)
  57. return hash, err
  58. }
  59. // DPA reader API
  60. func (self *Api) Retrieve(key storage.Key) storage.LazySectionReader {
  61. return self.dpa.Retrieve(key)
  62. }
  63. func (self *Api) Store(data io.Reader, size int64, wg *sync.WaitGroup) (key storage.Key, err error) {
  64. return self.dpa.Store(data, size, wg, nil)
  65. }
  66. type ErrResolve error
  67. // DNS Resolver
  68. func (self *Api) Resolve(uri *URI) (storage.Key, error) {
  69. log.Trace(fmt.Sprintf("Resolving : %v", uri.Addr))
  70. // if the URI is immutable, check if the address is a hash
  71. isHash := hashMatcher.MatchString(uri.Addr)
  72. if uri.Immutable() {
  73. if !isHash {
  74. return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
  75. }
  76. return common.Hex2Bytes(uri.Addr), nil
  77. }
  78. // if DNS is not configured, check if the address is a hash
  79. if self.dns == nil {
  80. if !isHash {
  81. return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
  82. }
  83. return common.Hex2Bytes(uri.Addr), nil
  84. }
  85. // try and resolve the address
  86. resolved, err := self.dns.Resolve(uri.Addr)
  87. if err == nil {
  88. return resolved[:], nil
  89. } else if !isHash {
  90. return nil, err
  91. }
  92. return common.Hex2Bytes(uri.Addr), nil
  93. }
  94. // Put provides singleton manifest creation on top of dpa store
  95. func (self *Api) Put(content, contentType string) (storage.Key, error) {
  96. r := strings.NewReader(content)
  97. wg := &sync.WaitGroup{}
  98. key, err := self.dpa.Store(r, int64(len(content)), wg, nil)
  99. if err != nil {
  100. return nil, err
  101. }
  102. manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
  103. r = strings.NewReader(manifest)
  104. key, err = self.dpa.Store(r, int64(len(manifest)), wg, nil)
  105. if err != nil {
  106. return nil, err
  107. }
  108. wg.Wait()
  109. return key, nil
  110. }
  111. // Get uses iterative manifest retrieval and prefix matching
  112. // to resolve basePath to content using dpa retrieve
  113. // it returns a section reader, mimeType, status and an error
  114. func (self *Api) Get(key storage.Key, path string) (reader storage.LazySectionReader, mimeType string, status int, err error) {
  115. trie, err := loadManifest(self.dpa, key, nil)
  116. if err != nil {
  117. log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
  118. return
  119. }
  120. log.Trace(fmt.Sprintf("getEntry(%s)", path))
  121. entry, _ := trie.getEntry(path)
  122. if entry != nil {
  123. key = common.Hex2Bytes(entry.Hash)
  124. status = entry.Status
  125. mimeType = entry.ContentType
  126. log.Trace(fmt.Sprintf("content lookup key: '%v' (%v)", key, mimeType))
  127. reader = self.dpa.Retrieve(key)
  128. } else {
  129. status = http.StatusNotFound
  130. err = fmt.Errorf("manifest entry for '%s' not found", path)
  131. log.Warn(fmt.Sprintf("%v", err))
  132. }
  133. return
  134. }
  135. func (self *Api) Modify(key storage.Key, path, contentHash, contentType string) (storage.Key, error) {
  136. quitC := make(chan bool)
  137. trie, err := loadManifest(self.dpa, key, quitC)
  138. if err != nil {
  139. return nil, err
  140. }
  141. if contentHash != "" {
  142. entry := newManifestTrieEntry(&ManifestEntry{
  143. Path: path,
  144. ContentType: contentType,
  145. }, nil)
  146. entry.Hash = contentHash
  147. trie.addEntry(entry, quitC)
  148. } else {
  149. trie.deleteEntry(path, quitC)
  150. }
  151. if err := trie.recalcAndStore(); err != nil {
  152. return nil, err
  153. }
  154. return trie.hash, nil
  155. }
  156. func (self *Api) AddFile(mhash, path, fname string, content []byte, nameresolver bool) (storage.Key, string, error) {
  157. uri, err := Parse("bzz:/" + mhash)
  158. if err != nil {
  159. return nil, "", err
  160. }
  161. mkey, err := self.Resolve(uri)
  162. if err != nil {
  163. return nil, "", err
  164. }
  165. // trim the root dir we added
  166. if path[:1] == "/" {
  167. path = path[1:]
  168. }
  169. entry := &ManifestEntry{
  170. Path: filepath.Join(path, fname),
  171. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  172. Mode: 0700,
  173. Size: int64(len(content)),
  174. ModTime: time.Now(),
  175. }
  176. mw, err := self.NewManifestWriter(mkey, nil)
  177. if err != nil {
  178. return nil, "", err
  179. }
  180. fkey, err := mw.AddEntry(bytes.NewReader(content), entry)
  181. if err != nil {
  182. return nil, "", err
  183. }
  184. newMkey, err := mw.Store()
  185. if err != nil {
  186. return nil, "", err
  187. }
  188. return fkey, newMkey.String(), nil
  189. }
  190. func (self *Api) RemoveFile(mhash, path, fname string, nameresolver bool) (string, error) {
  191. uri, err := Parse("bzz:/" + mhash)
  192. if err != nil {
  193. return "", err
  194. }
  195. mkey, err := self.Resolve(uri)
  196. if err != nil {
  197. return "", err
  198. }
  199. // trim the root dir we added
  200. if path[:1] == "/" {
  201. path = path[1:]
  202. }
  203. mw, err := self.NewManifestWriter(mkey, nil)
  204. if err != nil {
  205. return "", err
  206. }
  207. err = mw.RemoveEntry(filepath.Join(path, fname))
  208. if err != nil {
  209. return "", err
  210. }
  211. newMkey, err := mw.Store()
  212. if err != nil {
  213. return "", err
  214. }
  215. return newMkey.String(), nil
  216. }
  217. 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) {
  218. buffSize := offset + addSize
  219. if buffSize < existingSize {
  220. buffSize = existingSize
  221. }
  222. buf := make([]byte, buffSize)
  223. oldReader := self.Retrieve(oldKey)
  224. io.ReadAtLeast(oldReader, buf, int(offset))
  225. newReader := bytes.NewReader(content)
  226. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  227. if buffSize < existingSize {
  228. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  229. }
  230. combinedReader := bytes.NewReader(buf)
  231. totalSize := int64(len(buf))
  232. // TODO(jmozah): to append using pyramid chunker when it is ready
  233. //oldReader := self.Retrieve(oldKey)
  234. //newReader := bytes.NewReader(content)
  235. //combinedReader := io.MultiReader(oldReader, newReader)
  236. uri, err := Parse("bzz:/" + mhash)
  237. if err != nil {
  238. return nil, "", err
  239. }
  240. mkey, err := self.Resolve(uri)
  241. if err != nil {
  242. return nil, "", err
  243. }
  244. // trim the root dir we added
  245. if path[:1] == "/" {
  246. path = path[1:]
  247. }
  248. mw, err := self.NewManifestWriter(mkey, nil)
  249. if err != nil {
  250. return nil, "", err
  251. }
  252. err = mw.RemoveEntry(filepath.Join(path, fname))
  253. if err != nil {
  254. return nil, "", err
  255. }
  256. entry := &ManifestEntry{
  257. Path: filepath.Join(path, fname),
  258. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  259. Mode: 0700,
  260. Size: totalSize,
  261. ModTime: time.Now(),
  262. }
  263. fkey, err := mw.AddEntry(io.Reader(combinedReader), entry)
  264. if err != nil {
  265. return nil, "", err
  266. }
  267. newMkey, err := mw.Store()
  268. if err != nil {
  269. return nil, "", err
  270. }
  271. return fkey, newMkey.String(), nil
  272. }
  273. func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storage.Key, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  274. uri, err := Parse("bzz:/" + mhash)
  275. if err != nil {
  276. return nil, nil, err
  277. }
  278. key, err = self.Resolve(uri)
  279. if err != nil {
  280. return nil, nil, err
  281. }
  282. quitC := make(chan bool)
  283. rootTrie, err := loadManifest(self.dpa, key, quitC)
  284. if err != nil {
  285. return nil, nil, fmt.Errorf("can't load manifest %v: %v", key.String(), err)
  286. }
  287. manifestEntryMap = map[string]*manifestTrieEntry{}
  288. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  289. manifestEntryMap[suffix] = entry
  290. })
  291. if err != nil {
  292. return nil, nil, fmt.Errorf("list with prefix failed %v: %v", key.String(), err)
  293. }
  294. return key, manifestEntryMap, nil
  295. }