api.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 (
  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. // if the URI is immutable, check if the address is a hash
  75. isHash := hashMatcher.MatchString(uri.Addr)
  76. if uri.Immutable() {
  77. if !isHash {
  78. return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
  79. }
  80. return common.Hex2Bytes(uri.Addr), nil
  81. }
  82. // if DNS is not configured, check if the address is a hash
  83. if self.dns == nil {
  84. if !isHash {
  85. return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
  86. }
  87. return common.Hex2Bytes(uri.Addr), nil
  88. }
  89. // try and resolve the address
  90. resolved, err := self.dns.Resolve(uri.Addr)
  91. if err == nil {
  92. return resolved[:], nil
  93. } else if !isHash {
  94. return nil, err
  95. }
  96. return common.Hex2Bytes(uri.Addr), nil
  97. }
  98. // Put provides singleton manifest creation on top of dpa store
  99. func (self *Api) Put(content, contentType string) (storage.Key, error) {
  100. r := strings.NewReader(content)
  101. wg := &sync.WaitGroup{}
  102. key, err := self.dpa.Store(r, int64(len(content)), wg, nil)
  103. if err != nil {
  104. return nil, err
  105. }
  106. manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
  107. r = strings.NewReader(manifest)
  108. key, err = self.dpa.Store(r, int64(len(manifest)), wg, nil)
  109. if err != nil {
  110. return nil, err
  111. }
  112. wg.Wait()
  113. return key, nil
  114. }
  115. // Get uses iterative manifest retrieval and prefix matching
  116. // to resolve basePath to content using dpa retrieve
  117. // it returns a section reader, mimeType, status and an error
  118. func (self *Api) Get(key storage.Key, path string) (reader storage.LazySectionReader, mimeType string, status int, err error) {
  119. trie, err := loadManifest(self.dpa, key, nil)
  120. if err != nil {
  121. log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
  122. return
  123. }
  124. log.Trace(fmt.Sprintf("getEntry(%s)", path))
  125. entry, _ := trie.getEntry(path)
  126. if entry != nil {
  127. key = common.Hex2Bytes(entry.Hash)
  128. status = entry.Status
  129. mimeType = entry.ContentType
  130. log.Trace(fmt.Sprintf("content lookup key: '%v' (%v)", key, mimeType))
  131. reader = self.dpa.Retrieve(key)
  132. } else {
  133. status = http.StatusNotFound
  134. err = fmt.Errorf("manifest entry for '%s' not found", path)
  135. log.Warn(fmt.Sprintf("%v", err))
  136. }
  137. return
  138. }
  139. func (self *Api) Modify(key storage.Key, path, contentHash, contentType string) (storage.Key, error) {
  140. quitC := make(chan bool)
  141. trie, err := loadManifest(self.dpa, key, quitC)
  142. if err != nil {
  143. return nil, err
  144. }
  145. if contentHash != "" {
  146. entry := newManifestTrieEntry(&ManifestEntry{
  147. Path: path,
  148. ContentType: contentType,
  149. }, nil)
  150. entry.Hash = contentHash
  151. trie.addEntry(entry, quitC)
  152. } else {
  153. trie.deleteEntry(path, quitC)
  154. }
  155. if err := trie.recalcAndStore(); err != nil {
  156. return nil, err
  157. }
  158. return trie.hash, nil
  159. }
  160. func (self *Api) AddFile(mhash, path, fname string, content []byte, nameresolver bool) (storage.Key, string, error) {
  161. uri, err := Parse("bzz:/" + mhash)
  162. if err != nil {
  163. return nil, "", err
  164. }
  165. mkey, err := self.Resolve(uri)
  166. if err != nil {
  167. return nil, "", err
  168. }
  169. // trim the root dir we added
  170. if path[:1] == "/" {
  171. path = path[1:]
  172. }
  173. entry := &ManifestEntry{
  174. Path: filepath.Join(path, fname),
  175. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  176. Mode: 0700,
  177. Size: int64(len(content)),
  178. ModTime: time.Now(),
  179. }
  180. mw, err := self.NewManifestWriter(mkey, nil)
  181. if err != nil {
  182. return nil, "", err
  183. }
  184. fkey, err := mw.AddEntry(bytes.NewReader(content), entry)
  185. if err != nil {
  186. return nil, "", err
  187. }
  188. newMkey, err := mw.Store()
  189. if err != nil {
  190. return nil, "", err
  191. }
  192. return fkey, newMkey.String(), nil
  193. }
  194. func (self *Api) RemoveFile(mhash, path, fname string, nameresolver bool) (string, error) {
  195. uri, err := Parse("bzz:/" + mhash)
  196. if err != nil {
  197. return "", err
  198. }
  199. mkey, err := self.Resolve(uri)
  200. if err != nil {
  201. return "", err
  202. }
  203. // trim the root dir we added
  204. if path[:1] == "/" {
  205. path = path[1:]
  206. }
  207. mw, err := self.NewManifestWriter(mkey, nil)
  208. if err != nil {
  209. return "", err
  210. }
  211. err = mw.RemoveEntry(filepath.Join(path, fname))
  212. if err != nil {
  213. return "", err
  214. }
  215. newMkey, err := mw.Store()
  216. if err != nil {
  217. return "", err
  218. }
  219. return newMkey.String(), nil
  220. }
  221. 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) {
  222. buffSize := offset + addSize
  223. if buffSize < existingSize {
  224. buffSize = existingSize
  225. }
  226. buf := make([]byte, buffSize)
  227. oldReader := self.Retrieve(oldKey)
  228. io.ReadAtLeast(oldReader, buf, int(offset))
  229. newReader := bytes.NewReader(content)
  230. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  231. if buffSize < existingSize {
  232. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  233. }
  234. combinedReader := bytes.NewReader(buf)
  235. totalSize := int64(len(buf))
  236. // TODO(jmozah): to append using pyramid chunker when it is ready
  237. //oldReader := self.Retrieve(oldKey)
  238. //newReader := bytes.NewReader(content)
  239. //combinedReader := io.MultiReader(oldReader, newReader)
  240. uri, err := Parse("bzz:/" + mhash)
  241. if err != nil {
  242. return nil, "", err
  243. }
  244. mkey, err := self.Resolve(uri)
  245. if err != nil {
  246. return nil, "", err
  247. }
  248. // trim the root dir we added
  249. if path[:1] == "/" {
  250. path = path[1:]
  251. }
  252. mw, err := self.NewManifestWriter(mkey, nil)
  253. if err != nil {
  254. return nil, "", err
  255. }
  256. err = mw.RemoveEntry(filepath.Join(path, fname))
  257. if err != nil {
  258. return nil, "", err
  259. }
  260. entry := &ManifestEntry{
  261. Path: filepath.Join(path, fname),
  262. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  263. Mode: 0700,
  264. Size: totalSize,
  265. ModTime: time.Now(),
  266. }
  267. fkey, err := mw.AddEntry(io.Reader(combinedReader), entry)
  268. if err != nil {
  269. return nil, "", err
  270. }
  271. newMkey, err := mw.Store()
  272. if err != nil {
  273. return nil, "", err
  274. }
  275. return fkey, newMkey.String(), nil
  276. }
  277. func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storage.Key, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  278. uri, err := Parse("bzz:/" + mhash)
  279. if err != nil {
  280. return nil, nil, err
  281. }
  282. key, err = self.Resolve(uri)
  283. if err != nil {
  284. return nil, nil, err
  285. }
  286. quitC := make(chan bool)
  287. rootTrie, err := loadManifest(self.dpa, key, quitC)
  288. if err != nil {
  289. return nil, nil, fmt.Errorf("can't load manifest %v: %v", key.String(), err)
  290. }
  291. manifestEntryMap = map[string]*manifestTrieEntry{}
  292. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  293. manifestEntryMap[suffix] = entry
  294. })
  295. return key, manifestEntryMap, nil
  296. }