mirror of
https://github.com/safing/portmaster
synced 2025-09-01 10:09:11 +00:00
Update API endpoints and handlers
This commit is contained in:
parent
3d2cbdd4e6
commit
72c7592cdd
7 changed files with 182 additions and 72 deletions
43
core/api.go
Normal file
43
core/api.go
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/safing/portbase/api"
|
||||||
|
"github.com/safing/portbase/log"
|
||||||
|
"github.com/safing/portbase/modules"
|
||||||
|
"github.com/safing/portmaster/updates"
|
||||||
|
)
|
||||||
|
|
||||||
|
func registerActions() error {
|
||||||
|
if err := api.RegisterEndpoint(api.Endpoint{
|
||||||
|
Path: "core/shutdown",
|
||||||
|
Read: api.PermitSelf,
|
||||||
|
ActionFn: shutdown,
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := api.RegisterEndpoint(api.Endpoint{
|
||||||
|
Path: "core/restart",
|
||||||
|
Read: api.PermitSelf,
|
||||||
|
ActionFn: restart,
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// shutdown shuts the Portmaster down.
|
||||||
|
func shutdown(_ *api.Request) (msg string, err error) {
|
||||||
|
log.Warning("core: user requested shutdown via action")
|
||||||
|
// Do not use a worker, as this would block itself here.
|
||||||
|
go modules.Shutdown() //nolint:errcheck
|
||||||
|
return "shutdown initiated", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// restart restarts the Portmaster.
|
||||||
|
func restart(_ *api.Request) (msg string, err error) {
|
||||||
|
log.Info("core: user requested restart via action")
|
||||||
|
updates.RestartNow()
|
||||||
|
return "restart initiated", nil
|
||||||
|
}
|
|
@ -55,6 +55,10 @@ func start() error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := registerActions(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
registerLogCleaner()
|
registerLogCleaner()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
// DEPRECATED: remove in v0.7
|
||||||
|
|
||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
@ -19,12 +21,12 @@ func registerEvents() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func registerEventHooks() error {
|
func registerEventHooks() error {
|
||||||
err := module.RegisterEventHook("core", eventShutdown, "execute shutdown", shutdown)
|
err := module.RegisterEventHook("core", eventShutdown, "execute shutdown", shutdownHook)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = module.RegisterEventHook("core", eventRestart, "execute shutdown", restart)
|
err = module.RegisterEventHook("core", eventRestart, "execute shutdown", restartHook)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -32,16 +34,16 @@ func registerEventHooks() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// shutdown shuts the Portmaster down.
|
// shutdownHook shuts the Portmaster down.
|
||||||
func shutdown(ctx context.Context, _ interface{}) error {
|
func shutdownHook(ctx context.Context, _ interface{}) error {
|
||||||
log.Warning("core: user requested shutdown")
|
log.Warning("core: user requested shutdown")
|
||||||
// Do not use a worker, as this would block itself here.
|
// Do not use a worker, as this would block itself here.
|
||||||
go modules.Shutdown() //nolint:errcheck
|
go modules.Shutdown() //nolint:errcheck
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// restart restarts the Portmaster.
|
// restartHook restarts the Portmaster.
|
||||||
func restart(ctx context.Context, data interface{}) error {
|
func restartHook(ctx context.Context, data interface{}) error {
|
||||||
log.Info("core: user requested restart")
|
log.Info("core: user requested restart")
|
||||||
updates.RestartNow()
|
updates.RestartNow()
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -59,21 +59,24 @@ func startAPIAuth() {
|
||||||
log.Tracef("filter: api port set to %d", apiPort)
|
log.Tracef("filter: api port set to %d", apiPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func apiAuthenticator(ctx context.Context, s *http.Server, r *http.Request) (err error) {
|
func apiAuthenticator(ctx context.Context, s *http.Server, r *http.Request) (token *api.AuthToken, err error) {
|
||||||
if devMode() {
|
if devMode() {
|
||||||
return nil
|
return &api.AuthToken{
|
||||||
|
Read: api.PermitSelf,
|
||||||
|
Write: api.PermitSelf,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// get local IP/Port
|
// get local IP/Port
|
||||||
localIP, localPort, err := parseHostPort(s.Addr)
|
localIP, localPort, err := parseHostPort(s.Addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to get local IP/Port: %s", err)
|
return nil, fmt.Errorf("failed to get local IP/Port: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// get remote IP/Port
|
// get remote IP/Port
|
||||||
remoteIP, remotePort, err := parseHostPort(r.RemoteAddr)
|
remoteIP, remotePort, err := parseHostPort(r.RemoteAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to get remote IP/Port: %s", err)
|
return nil, fmt.Errorf("failed to get remote IP/Port: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Tracer(r.Context()).Tracef("filter: authenticating API request from %s", r.RemoteAddr)
|
log.Tracer(r.Context()).Tracef("filter: authenticating API request from %s", r.RemoteAddr)
|
||||||
|
@ -94,14 +97,20 @@ func apiAuthenticator(ctx context.Context, s *http.Server, r *http.Request) (err
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if !retry {
|
if !retry {
|
||||||
return err
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// wait a little
|
// wait a little
|
||||||
time.Sleep(250 * time.Millisecond)
|
time.Sleep(250 * time.Millisecond)
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return err
|
return &api.AuthToken{
|
||||||
|
Read: api.PermitSelf,
|
||||||
|
Write: api.PermitSelf,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bool, err error) {
|
func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bool, err error) {
|
||||||
|
|
|
@ -6,6 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/safing/portbase/api"
|
||||||
|
|
||||||
"github.com/safing/portbase/log"
|
"github.com/safing/portbase/log"
|
||||||
"github.com/safing/portbase/modules"
|
"github.com/safing/portbase/modules"
|
||||||
"github.com/safing/portmaster/intel"
|
"github.com/safing/portmaster/intel"
|
||||||
|
@ -76,12 +78,22 @@ func start() error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Register api endpoint to clear DNS cache.
|
||||||
|
if err := api.RegisterEndpoint(api.Endpoint{
|
||||||
|
Path: "dns/clear/namecache",
|
||||||
|
Read: api.PermitUser,
|
||||||
|
ActionFn: clearNameCache,
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DEPRECATED: remove in v0.7
|
||||||
// cache clearing
|
// cache clearing
|
||||||
err = module.RegisterEventHook(
|
err = module.RegisterEventHook(
|
||||||
"resolver",
|
"resolver",
|
||||||
ClearNameCacheEvent,
|
ClearNameCacheEvent,
|
||||||
ClearNameCacheEvent,
|
ClearNameCacheEvent,
|
||||||
clearNameCache,
|
clearNameCacheEventHandler,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/safing/portbase/api"
|
||||||
"github.com/safing/portbase/database"
|
"github.com/safing/portbase/database"
|
||||||
"github.com/safing/portbase/database/query"
|
"github.com/safing/portbase/database/query"
|
||||||
"github.com/safing/portbase/database/record"
|
"github.com/safing/portbase/database/record"
|
||||||
|
@ -104,7 +105,20 @@ func (rec *NameRecord) Save() error {
|
||||||
return recordDatabase.PutNew(rec)
|
return recordDatabase.PutNew(rec)
|
||||||
}
|
}
|
||||||
|
|
||||||
func clearNameCache(ctx context.Context, _ interface{}) error {
|
// clearNameCache clears all dns caches from the database.
|
||||||
|
func clearNameCache(ar *api.Request) (msg string, err error) {
|
||||||
|
log.Warning("resolver: user requested dns cache clearing via action")
|
||||||
|
|
||||||
|
n, err := recordDatabase.Purge(ar.Ctx(), query.New(nameRecordsKeyPrefix))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("cleared %d dns cache entries", n), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DEPRECATED: remove in v0.7
|
||||||
|
func clearNameCacheEventHandler(ctx context.Context, _ interface{}) error {
|
||||||
log.Debugf("resolver: dns cache clearing started...")
|
log.Debugf("resolver: dns cache clearing started...")
|
||||||
n, err := recordDatabase.Purge(ctx, query.New(nameRecordsKeyPrefix))
|
n, err := recordDatabase.Purge(ctx, query.New(nameRecordsKeyPrefix))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
142
ui/serve.go
142
ui/serve.go
|
@ -24,72 +24,98 @@ var (
|
||||||
)
|
)
|
||||||
|
|
||||||
func registerRoutes() error {
|
func registerRoutes() error {
|
||||||
api.RegisterHandleFunc("/assets/{resPath:[a-zA-Z0-9/\\._-]+}", ServeBundle("assets")).Methods("GET", "HEAD")
|
// Server assets.
|
||||||
api.RegisterHandleFunc("/ui/modules/{moduleName:[a-z]+}", redirAddSlash).Methods("GET", "HEAD")
|
api.RegisterHandler(
|
||||||
api.RegisterHandleFunc("/ui/modules/{moduleName:[a-z]+}/", ServeBundle("")).Methods("GET", "HEAD")
|
"/assets/{resPath:[a-zA-Z0-9/\\._-]+}",
|
||||||
api.RegisterHandleFunc("/ui/modules/{moduleName:[a-z]+}/{resPath:[a-zA-Z0-9/\\._-]+}", ServeBundle("")).Methods("GET", "HEAD")
|
&bundleServer{defaultModuleName: "assets"},
|
||||||
api.RegisterHandleFunc("/", redirectToDefault)
|
)
|
||||||
|
|
||||||
|
// Add slash to plain module namespaces.
|
||||||
|
api.RegisterHandler(
|
||||||
|
"/ui/modules/{moduleName:[a-z]+}",
|
||||||
|
api.WrapInAuthHandler(redirAddSlash, api.PermitAnyone, api.NotSupported),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Serve modules.
|
||||||
|
srv := &bundleServer{}
|
||||||
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeBundle serves bundles.
|
type bundleServer struct {
|
||||||
func ServeBundle(defaultModuleName string) func(w http.ResponseWriter, r *http.Request) {
|
defaultModuleName string
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
}
|
||||||
|
|
||||||
// log.Tracef("ui: request for %s", r.RequestURI)
|
func (bs *bundleServer) ReadPermission(*http.Request) api.Permission { return api.PermitAnyone }
|
||||||
|
|
||||||
vars := api.GetMuxVars(r)
|
func (bs *bundleServer) WritePermission(*http.Request) api.Permission { return api.NotSupported }
|
||||||
moduleName, ok := vars["moduleName"]
|
|
||||||
if !ok {
|
|
||||||
moduleName = defaultModuleName
|
|
||||||
if moduleName == "" {
|
|
||||||
http.Error(w, "missing module name", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
resPath, ok := vars["resPath"]
|
func (bs *bundleServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
if !ok || strings.HasSuffix(resPath, "/") {
|
// Get request context.
|
||||||
resPath = "index.html"
|
ar := api.GetAPIRequest(r)
|
||||||
}
|
if ar == nil {
|
||||||
|
log.Errorf("ui: missing api request context")
|
||||||
appsLock.RLock()
|
http.Error(w, "Internal server error.", http.StatusInternalServerError)
|
||||||
bundle, ok := apps[moduleName]
|
return
|
||||||
appsLock.RUnlock()
|
|
||||||
if ok {
|
|
||||||
ServeFileFromBundle(w, r, moduleName, bundle, resPath)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// get file from update system
|
|
||||||
zipFile, err := updates.GetFile(fmt.Sprintf("ui/modules/%s.zip", moduleName))
|
|
||||||
if err != nil {
|
|
||||||
if 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 bundle
|
|
||||||
newBundle, err := resources.OpenZip(zipFile.Path())
|
|
||||||
if err != nil {
|
|
||||||
log.Tracef("ui: error prepping module %s: %s", moduleName, err)
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
bundle = &resources.BundleSequence{newBundle}
|
|
||||||
appsLock.Lock()
|
|
||||||
apps[moduleName] = bundle
|
|
||||||
appsLock.Unlock()
|
|
||||||
|
|
||||||
ServeFileFromBundle(w, r, moduleName, bundle, resPath)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
bundle, ok := apps[moduleName]
|
||||||
|
appsLock.RUnlock()
|
||||||
|
if ok {
|
||||||
|
ServeFileFromBundle(w, r, moduleName, bundle, resPath)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// get file from update system
|
||||||
|
zipFile, err := updates.GetFile(fmt.Sprintf("ui/modules/%s.zip", moduleName))
|
||||||
|
if err != nil {
|
||||||
|
if 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 bundle
|
||||||
|
newBundle, err := resources.OpenZip(zipFile.Path())
|
||||||
|
if err != nil {
|
||||||
|
log.Tracef("ui: error prepping module %s: %s", moduleName, err)
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
bundle = &resources.BundleSequence{newBundle}
|
||||||
|
appsLock.Lock()
|
||||||
|
apps[moduleName] = bundle
|
||||||
|
appsLock.Unlock()
|
||||||
|
|
||||||
|
ServeFileFromBundle(w, r, moduleName, bundle, resPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeFileFromBundle serves a file from the given bundle.
|
// ServeFileFromBundle serves a file from the given bundle.
|
||||||
|
|
Loading…
Add table
Reference in a new issue