Switch to zipfs lib for loading files from a zip

This commit is contained in:
Daniel
2022-08-30 16:11:52 +02:00
parent 092b1cd8a0
commit 0e3dde4cf1
2 changed files with 32 additions and 36 deletions

View File

@@ -1,8 +1,6 @@
package ui package ui
import ( import (
resources "github.com/cookieo9/resources-go"
"github.com/safing/portbase/api" "github.com/safing/portbase/api"
"github.com/safing/portbase/log" "github.com/safing/portbase/log"
) )
@@ -22,16 +20,18 @@ func reloadUI(_ *api.Request) (msg string, err error) {
appsLock.Lock() appsLock.Lock()
defer appsLock.Unlock() defer appsLock.Unlock()
// close all bundles. // Close all archives.
for id, bundle := range apps { for id, archiveFS := range apps {
err := bundle.Close() err := archiveFS.Close()
if err != nil { if err != nil {
log.Warningf("ui: failed to close bundle %s: %s", id, err) log.Warningf("ui: failed to close archive %s: %s", id, err)
} }
} }
// Reset index. // Reset index.
apps = make(map[string]*resources.BundleSequence) for key := range apps {
delete(apps, key)
}
return "all ui bundles successfully reloaded", nil return "all ui archives successfully reloaded", nil
} }

View File

@@ -6,11 +6,12 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
resources "github.com/cookieo9/resources-go" "github.com/spkg/zipfs"
"github.com/safing/portbase/api" "github.com/safing/portbase/api"
"github.com/safing/portbase/log" "github.com/safing/portbase/log"
@@ -20,7 +21,7 @@ import (
) )
var ( var (
apps = make(map[string]*resources.BundleSequence) apps = make(map[string]*zipfs.FileSystem)
appsLock sync.RWMutex appsLock sync.RWMutex
) )
@@ -28,7 +29,7 @@ func registerRoutes() error {
// Server assets. // Server assets.
api.RegisterHandler( api.RegisterHandler(
"/assets/{resPath:[a-zA-Z0-9/\\._-]+}", "/assets/{resPath:[a-zA-Z0-9/\\._-]+}",
&bundleServer{defaultModuleName: "assets"}, &archiveServer{defaultModuleName: "assets"},
) )
// Add slash to plain module namespaces. // Add slash to plain module namespaces.
@@ -38,7 +39,7 @@ func registerRoutes() error {
) )
// Serve modules. // Serve modules.
srv := &bundleServer{} srv := &archiveServer{}
api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/", srv) api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/", srv)
api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/{resPath:[a-zA-Z0-9/\\._-]+}", srv) api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/{resPath:[a-zA-Z0-9/\\._-]+}", srv)
@@ -51,17 +52,17 @@ func registerRoutes() error {
return nil return nil
} }
type bundleServer struct { type archiveServer struct {
defaultModuleName string defaultModuleName string
} }
func (bs *bundleServer) BelongsTo() *modules.Module { return module } func (bs *archiveServer) BelongsTo() *modules.Module { return module }
func (bs *bundleServer) ReadPermission(*http.Request) api.Permission { return api.PermitAnyone } func (bs *archiveServer) ReadPermission(*http.Request) api.Permission { return api.PermitAnyone }
func (bs *bundleServer) WritePermission(*http.Request) api.Permission { return api.NotSupported } func (bs *archiveServer) WritePermission(*http.Request) api.Permission { return api.NotSupported }
func (bs *bundleServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (bs *archiveServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get request context. // Get request context.
ar := api.GetAPIRequest(r) ar := api.GetAPIRequest(r)
if ar == nil { if ar == nil {
@@ -85,10 +86,10 @@ func (bs *bundleServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
appsLock.RLock() appsLock.RLock()
bundle, ok := apps[moduleName] archiveFS, ok := apps[moduleName]
appsLock.RUnlock() appsLock.RUnlock()
if ok { if ok {
ServeFileFromBundle(w, r, moduleName, bundle, resPath) ServeFileFromArchive(w, r, moduleName, archiveFS, resPath)
return return
} }
@@ -105,39 +106,38 @@ func (bs *bundleServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
// open bundle // Open archive from disk.
newBundle, err := resources.OpenZip(zipFile.Path()) archiveFS, err = zipfs.New(zipFile.Path())
if err != nil { if err != nil {
log.Tracef("ui: error prepping module %s: %s", moduleName, err) log.Tracef("ui: error prepping module %s: %s", moduleName, err)
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
bundle = &resources.BundleSequence{newBundle}
appsLock.Lock() appsLock.Lock()
apps[moduleName] = bundle apps[moduleName] = archiveFS
appsLock.Unlock() appsLock.Unlock()
ServeFileFromBundle(w, r, moduleName, bundle, resPath) ServeFileFromArchive(w, r, moduleName, archiveFS, resPath)
} }
// ServeFileFromBundle serves a file from the given bundle. // ServeFileFromArchive serves a file from the given archive.
func ServeFileFromBundle(w http.ResponseWriter, r *http.Request, bundleName string, bundle *resources.BundleSequence, path string) { func ServeFileFromArchive(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string) {
readCloser, err := bundle.Open(path) readCloser, err := archiveFS.Open(path)
if err != nil { if err != nil {
if errors.Is(err, resources.ErrNotFound) { if os.IsNotExist(err) {
// Check if there is a base index.html file we can serve instead. // Check if there is a base index.html file we can serve instead.
var indexErr error var indexErr error
path = "index.html" path = "index.html"
readCloser, indexErr = bundle.Open(path) readCloser, indexErr = archiveFS.Open(path)
if indexErr != nil { if indexErr != nil {
// If we cannot get an index, continue with handling the original error. // If we cannot get an index, continue with handling the original error.
log.Tracef("ui: requested resource \"%s\" not found in bundle %s: %s", path, bundleName, err) log.Tracef("ui: requested resource \"%s\" not found in archive %s: %s", path, archiveName, err)
http.Error(w, err.Error(), http.StatusNotFound) http.Error(w, err.Error(), http.StatusNotFound)
return return
} }
} else { } else {
log.Tracef("ui: error opening module %s: %s", bundleName, err) log.Tracef("ui: error opening module %s: %s", archiveName, err)
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
@@ -152,12 +152,8 @@ func ServeFileFromBundle(w http.ResponseWriter, r *http.Request, bundleName stri
} }
} }
// TODO: Set content security policy
// For some reason, this breaks the ui client
// w.Header().Set("Content-Security-Policy", "default-src 'self'")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
if r.Method != "HEAD" { if r.Method != http.MethodHead {
_, err = io.Copy(w, readCloser) _, err = io.Copy(w, readCloser)
if err != nil { if err != nil {
log.Errorf("ui: failed to serve file: %s", err) log.Errorf("ui: failed to serve file: %s", err)