api.go 8.4 KB

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