2022-10-25 12:55:00 +08:00
|
|
|
package libbox
|
|
|
|
|
|
|
|
import (
|
2023-04-05 04:38:56 +08:00
|
|
|
"bytes"
|
2023-04-02 10:35:03 +08:00
|
|
|
"context"
|
2023-04-05 04:38:56 +08:00
|
|
|
"encoding/json"
|
2023-04-02 10:35:03 +08:00
|
|
|
|
|
|
|
"github.com/sagernet/sing-box"
|
2022-10-25 12:55:00 +08:00
|
|
|
"github.com/sagernet/sing-box/option"
|
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2023-04-02 10:35:03 +08:00
|
|
|
|
|
|
|
func CheckConfig(configContent string) error {
|
|
|
|
options, err := parseConfig(configContent)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
2023-04-03 18:24:20 +08:00
|
|
|
instance, err := box.New(box.Options{
|
|
|
|
Context: ctx,
|
|
|
|
Options: options,
|
|
|
|
})
|
2023-04-02 10:35:03 +08:00
|
|
|
if err == nil {
|
|
|
|
instance.Close()
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2023-04-05 04:38:56 +08:00
|
|
|
|
|
|
|
func FormatConfig(configContent string) (string, error) {
|
|
|
|
options, err := parseConfig(configContent)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
var buffer bytes.Buffer
|
|
|
|
json.NewEncoder(&buffer)
|
|
|
|
encoder := json.NewEncoder(&buffer)
|
|
|
|
encoder.SetIndent("", " ")
|
|
|
|
err = encoder.Encode(options)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return buffer.String(), nil
|
|
|
|
}
|