wip: migrate to mono-repo. SPN has already been moved to spn/

This commit is contained in:
Patrick Pacher
2024-03-15 11:55:13 +01:00
parent b30fd00ccf
commit 8579430db9
577 changed files with 35981 additions and 818 deletions

37
service/ui/api.go Normal file
View File

@@ -0,0 +1,37 @@
package ui
import (
"github.com/safing/portbase/api"
"github.com/safing/portbase/log"
)
func registerAPIEndpoints() error {
return api.RegisterEndpoint(api.Endpoint{
Path: "ui/reload",
Write: api.PermitUser,
BelongsTo: module,
ActionFunc: reloadUI,
Name: "Reload UI Assets",
Description: "Removes all assets from the cache and reloads the current (possibly updated) version from disk when requested.",
})
}
func reloadUI(_ *api.Request) (msg string, err error) {
appsLock.Lock()
defer appsLock.Unlock()
// Close all archives.
for id, archiveFS := range apps {
err := archiveFS.Close()
if err != nil {
log.Warningf("ui: failed to close archive %s: %s", id, err)
}
}
// Reset index.
for key := range apps {
delete(apps, key)
}
return "all ui archives successfully reloaded", nil
}

38
service/ui/module.go Normal file
View File

@@ -0,0 +1,38 @@
package ui
import (
"github.com/safing/portbase/dataroot"
"github.com/safing/portbase/log"
"github.com/safing/portbase/modules"
)
var module *modules.Module
func init() {
module = modules.Register("ui", prep, start, nil, "api", "updates")
}
func prep() error {
if err := registerAPIEndpoints(); err != nil {
return err
}
return registerRoutes()
}
func start() error {
// Create a dummy directory to which processes change their working directory
// to. Currently this includes the App and the Notifier. The aim is protect
// all other directories and increase compatibility should any process want
// to read or write something to the current working directory. This can also
// be useful in the future to dump data to for debugging. The permission used
// may seem dangerous, but proper permission on the parent directory provide
// (some) protection.
// Processes must _never_ read from this directory.
err := dataroot.Root().ChildDir("exec", 0o0777).Ensure()
if err != nil {
log.Warningf("ui: failed to create safe exec dir: %s", err)
}
return nil
}

179
service/ui/serve.go Normal file
View File

@@ -0,0 +1,179 @@
package ui
import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"github.com/spkg/zipfs"
"github.com/safing/portbase/api"
"github.com/safing/portbase/log"
"github.com/safing/portbase/modules"
"github.com/safing/portbase/updater"
"github.com/safing/portbase/utils"
"github.com/safing/portmaster/service/updates"
)
var (
apps = make(map[string]*zipfs.FileSystem)
appsLock sync.RWMutex
)
func registerRoutes() error {
// Server assets.
api.RegisterHandler(
"/assets/{resPath:[a-zA-Z0-9/\\._-]+}",
&archiveServer{defaultModuleName: "assets"},
)
// Add slash to plain module namespaces.
api.RegisterHandler(
"/ui/modules/{moduleName:[a-z]+}",
api.WrapInAuthHandler(redirAddSlash, api.PermitAnyone, api.NotSupported),
)
// Serve modules.
srv := &archiveServer{}
api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/", srv)
api.RegisterHandler("/ui/modules/{moduleName:[a-z]+}/{resPath:[a-zA-Z0-9/\\._-]+}", srv)
// Redirect "/" to default module.
api.RegisterHandler(
"/",
api.WrapInAuthHandler(redirectToDefault, api.PermitAnyone, api.NotSupported),
)
return nil
}
type archiveServer struct {
defaultModuleName string
}
func (bs *archiveServer) BelongsTo() *modules.Module { return module }
func (bs *archiveServer) ReadPermission(*http.Request) api.Permission { return api.PermitAnyone }
func (bs *archiveServer) WritePermission(*http.Request) api.Permission { return api.NotSupported }
func (bs *archiveServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get request context.
ar := api.GetAPIRequest(r)
if ar == nil {
log.Errorf("ui: missing api request context")
http.Error(w, "Internal server error.", http.StatusInternalServerError)
return
}
moduleName, ok := ar.URLVars["moduleName"]
if !ok {
moduleName = bs.defaultModuleName
if moduleName == "" {
http.Error(w, "missing module name", http.StatusBadRequest)
return
}
}
resPath, ok := ar.URLVars["resPath"]
if !ok || strings.HasSuffix(resPath, "/") {
resPath = "index.html"
}
appsLock.RLock()
archiveFS, ok := apps[moduleName]
appsLock.RUnlock()
if ok {
ServeFileFromArchive(w, r, moduleName, archiveFS, resPath)
return
}
// get file from update system
zipFile, err := updates.GetFile(fmt.Sprintf("ui/modules/%s.zip", moduleName))
if err != nil {
if errors.Is(err, updater.ErrNotFound) {
log.Tracef("ui: requested module %s does not exist", moduleName)
http.Error(w, err.Error(), http.StatusNotFound)
} else {
log.Tracef("ui: error loading module %s: %s", moduleName, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Open archive from disk.
archiveFS, err = zipfs.New(zipFile.Path())
if err != nil {
log.Tracef("ui: error prepping module %s: %s", moduleName, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
appsLock.Lock()
apps[moduleName] = archiveFS
appsLock.Unlock()
ServeFileFromArchive(w, r, moduleName, archiveFS, resPath)
}
// ServeFileFromArchive serves a file from the given archive.
func ServeFileFromArchive(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string) {
readCloser, err := archiveFS.Open(path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// Check if there is a base index.html file we can serve instead.
var indexErr error
path = "index.html"
readCloser, indexErr = archiveFS.Open(path)
if indexErr != nil {
// If we cannot get an index, continue with handling the original error.
log.Tracef("ui: requested resource \"%s\" not found in archive %s: %s", path, archiveName, err)
http.Error(w, err.Error(), http.StatusNotFound)
return
}
} else {
log.Tracef("ui: error opening module %s: %s", archiveName, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// set content type
_, ok := w.Header()["Content-Type"]
if !ok {
contentType, _ := utils.MimeTypeByExtension(filepath.Ext(path))
w.Header().Set("Content-Type", contentType)
}
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
_, err = io.Copy(w, readCloser)
if err != nil {
log.Errorf("ui: failed to serve file: %s", err)
return
}
}
_ = readCloser.Close()
}
// redirectToDefault redirects the request to the default UI module.
func redirectToDefault(w http.ResponseWriter, r *http.Request) {
u, err := url.Parse("/ui/modules/portmaster/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, r.URL.ResolveReference(u).String(), http.StatusTemporaryRedirect)
}
// redirAddSlash redirects the request to the same, but with a trailing slash.
func redirAddSlash(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.RequestURI+"/", http.StatusPermanentRedirect)
}