Files
umbrix-libcore/custom/service.go

69 lines
1.7 KiB
Go
Raw Normal View History

2023-08-16 15:16:02 +03:30
package main
import (
"context"
"os"
"runtime"
2023-10-13 14:56:40 +03:30
runtimeDebug "runtime/debug"
2023-08-16 15:16:02 +03:30
B "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/common/urltest"
2023-08-27 13:57:23 +03:30
"github.com/sagernet/sing-box/experimental/libbox"
2023-08-16 15:16:02 +03:30
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/service"
"github.com/sagernet/sing/service/filemanager"
2023-08-27 13:57:23 +03:30
"github.com/sagernet/sing/service/pause"
2023-08-16 15:16:02 +03:30
)
var (
sWorkingPath string
sTempPath string
sUserID int
sGroupID int
)
func Setup(basePath string, workingPath string, tempPath string) {
tcpConn := runtime.GOOS == "windows" //TODO add TVOS
libbox.Setup(basePath, workingPath, tempPath, tcpConn)
2023-08-16 15:16:02 +03:30
sWorkingPath = workingPath
os.Chdir(sWorkingPath)
2023-08-16 15:16:02 +03:30
sTempPath = tempPath
sUserID = os.Getuid()
sGroupID = os.Getgid()
}
2023-08-27 13:57:23 +03:30
func NewService(options option.Options) (*libbox.BoxService, error) {
2023-10-13 14:56:40 +03:30
runtimeDebug.FreeOSMemory()
2023-08-16 15:16:02 +03:30
ctx, cancel := context.WithCancel(context.Background())
ctx = filemanager.WithDefault(ctx, sWorkingPath, sTempPath, sUserID, sGroupID)
2023-08-27 13:57:23 +03:30
urlTestHistoryStorage := urltest.NewHistoryStorage()
ctx = service.ContextWithPtr(ctx, urlTestHistoryStorage)
2023-08-16 15:16:02 +03:30
instance, err := B.New(B.Options{
Context: ctx,
Options: options,
})
if err != nil {
cancel()
return nil, E.Cause(err, "create service")
}
2023-10-13 14:56:40 +03:30
runtimeDebug.FreeOSMemory()
2023-08-27 13:57:23 +03:30
service := libbox.NewBoxService(
ctx,
cancel,
instance,
service.FromContext[pause.Manager](ctx),
2023-08-27 13:57:23 +03:30
urlTestHistoryStorage,
)
return &service, nil
2023-08-16 15:16:02 +03:30
}
func parseConfig(configContent string) (option.Options, error) {
var options option.Options
err := options.UnmarshalJSON([]byte(configContent))
if err != nil {
return option.Options{}, E.Cause(err, "decode config")
}
return options, nil
}