api.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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() || uri.DeprecatedImmutable() {
  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. status = http.StatusNotFound
  118. log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
  119. return
  120. }
  121. log.Trace(fmt.Sprintf("getEntry(%s)", path))
  122. entry, _ := trie.getEntry(path)
  123. if entry != nil {
  124. key = common.Hex2Bytes(entry.Hash)
  125. status = entry.Status
  126. if status == http.StatusMultipleChoices {
  127. return
  128. } else {
  129. mimeType = entry.ContentType
  130. log.Trace(fmt.Sprintf("content lookup key: '%v' (%v)", key, mimeType))
  131. reader = self.dpa.Retrieve(key)
  132. }
  133. } else {
  134. status = http.StatusNotFound
  135. err = fmt.Errorf("manifest entry for '%s' not found", path)
  136. log.Warn(fmt.Sprintf("%v", err))
  137. }
  138. return
  139. }
  140. func (self *Api) Modify(key storage.Key, path, contentHash, contentType string) (storage.Key, error) {
  141. quitC := make(chan bool)
  142. trie, err := loadManifest(self.dpa, key, quitC)
  143. if err != nil {
  144. return nil, err
  145. }
  146. if contentHash != "" {
  147. entry := newManifestTrieEntry(&ManifestEntry{
  148. Path: path,
  149. ContentType: contentType,
  150. }, nil)
  151. entry.Hash = contentHash
  152. trie.addEntry(entry, quitC)
  153. } else {
  154. trie.deleteEntry(path, quitC)
  155. }
  156. if err := trie.recalcAndStore(); err != nil {
  157. return nil, err
  158. }
  159. return trie.hash, nil
  160. }
  161. func (self *Api) AddFile(mhash, path, fname string, content []byte, nameresolver bool) (storage.Key, string, error) {
  162. uri, err := Parse("bzz:/" + mhash)
  163. if err != nil {
  164. return nil, "", err
  165. }
  166. mkey, err := self.Resolve(uri)
  167. if err != nil {
  168. return nil, "", err
  169. }
  170. // trim the root dir we added
  171. if path[:1] == "/" {
  172. path = path[1:]
  173. }
  174. entry := &ManifestEntry{
  175. Path: filepath.Join(path, fname),
  176. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  177. Mode: 0700,
  178. Size: int64(len(content)),
  179. ModTime: time.Now(),
  180. }
  181. mw, err := self.NewManifestWriter(mkey, nil)
  182. if err != nil {
  183. return nil, "", err
  184. }
  185. fkey, err := mw.AddEntry(bytes.NewReader(content), entry)
  186. if err != nil {
  187. return nil, "", err
  188. }
  189. newMkey, err := mw.Store()
  190. if err != nil {
  191. return nil, "", err
  192. }
  193. return fkey, newMkey.String(), nil
  194. }
  195. func (self *Api) RemoveFile(mhash, path, fname string, nameresolver bool) (string, error) {
  196. uri, err := Parse("bzz:/" + mhash)
  197. if err != nil {
  198. return "", err
  199. }
  200. mkey, err := self.Resolve(uri)
  201. if err != nil {
  202. return "", err
  203. }
  204. // trim the root dir we added
  205. if path[:1] == "/" {
  206. path = path[1:]
  207. }
  208. mw, err := self.NewManifestWriter(mkey, nil)
  209. if err != nil {
  210. return "", err
  211. }
  212. err = mw.RemoveEntry(filepath.Join(path, fname))
  213. if err != nil {
  214. return "", err
  215. }
  216. newMkey, err := mw.Store()
  217. if err != nil {
  218. return "", err
  219. }
  220. return newMkey.String(), nil
  221. }
  222. 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) {
  223. buffSize := offset + addSize
  224. if buffSize < existingSize {
  225. buffSize = existingSize
  226. }
  227. buf := make([]byte, buffSize)
  228. oldReader := self.Retrieve(oldKey)
  229. io.ReadAtLeast(oldReader, buf, int(offset))
  230. newReader := bytes.NewReader(content)
  231. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  232. if buffSize < existingSize {
  233. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  234. }
  235. combinedReader := bytes.NewReader(buf)
  236. totalSize := int64(len(buf))
  237. // TODO(jmozah): to append using pyramid chunker when it is ready
  238. //oldReader := self.Retrieve(oldKey)
  239. //newReader := bytes.NewReader(content)
  240. //combinedReader := io.MultiReader(oldReader, newReader)
  241. uri, err := Parse("bzz:/" + mhash)
  242. if err != nil {
  243. return nil, "", err
  244. }
  245. mkey, err := self.Resolve(uri)
  246. if err != nil {
  247. return nil, "", err
  248. }
  249. // trim the root dir we added
  250. if path[:1] == "/" {
  251. path = path[1:]
  252. }
  253. mw, err := self.NewManifestWriter(mkey, nil)
  254. if err != nil {
  255. return nil, "", err
  256. }
  257. err = mw.RemoveEntry(filepath.Join(path, fname))
  258. if err != nil {
  259. return nil, "", err
  260. }
  261. entry := &ManifestEntry{
  262. Path: filepath.Join(path, fname),
  263. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  264. Mode: 0700,
  265. Size: totalSize,
  266. ModTime: time.Now(),
  267. }
  268. fkey, err := mw.AddEntry(io.Reader(combinedReader), entry)
  269. if err != nil {
  270. return nil, "", err
  271. }
  272. newMkey, err := mw.Store()
  273. if err != nil {
  274. return nil, "", err
  275. }
  276. return fkey, newMkey.String(), nil
  277. }
  278. func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storage.Key, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  279. uri, err := Parse("bzz:/" + mhash)
  280. if err != nil {
  281. return nil, nil, err
  282. }
  283. key, err = self.Resolve(uri)
  284. if err != nil {
  285. return nil, nil, err
  286. }
  287. quitC := make(chan bool)
  288. rootTrie, err := loadManifest(self.dpa, key, quitC)
  289. if err != nil {
  290. return nil, nil, fmt.Errorf("can't load manifest %v: %v", key.String(), err)
  291. }
  292. manifestEntryMap = map[string]*manifestTrieEntry{}
  293. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  294. manifestEntryMap[suffix] = entry
  295. })
  296. if err != nil {
  297. return nil, nil, fmt.Errorf("list with prefix failed %v: %v", key.String(), err)
  298. }
  299. return key, manifestEntryMap, nil
  300. }