setup.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package libbox
  2. import (
  3. "os"
  4. "os/user"
  5. "runtime/debug"
  6. "strconv"
  7. "time"
  8. "github.com/sagernet/sing-box/common/humanize"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/experimental/locale"
  11. _ "github.com/sagernet/sing-box/include"
  12. "github.com/sagernet/sing-box/log"
  13. )
  14. var (
  15. sBasePath string
  16. sWorkingPath string
  17. sTempPath string
  18. sUserID int
  19. sGroupID int
  20. sTVOS bool
  21. )
  22. func init() {
  23. debug.SetPanicOnFault(true)
  24. }
  25. func Setup(basePath string, workingPath string, tempPath string, isTVOS bool) {
  26. sBasePath = basePath
  27. sWorkingPath = workingPath
  28. sTempPath = tempPath
  29. sUserID = os.Getuid()
  30. sGroupID = os.Getgid()
  31. sTVOS = isTVOS
  32. os.MkdirAll(sWorkingPath, 0o777)
  33. os.MkdirAll(sTempPath, 0o777)
  34. }
  35. func SetupWithUsername(basePath string, workingPath string, tempPath string, username string) error {
  36. sBasePath = basePath
  37. sWorkingPath = workingPath
  38. sTempPath = tempPath
  39. sUser, err := user.Lookup(username)
  40. if err != nil {
  41. return err
  42. }
  43. sUserID, _ = strconv.Atoi(sUser.Uid)
  44. sGroupID, _ = strconv.Atoi(sUser.Gid)
  45. os.MkdirAll(sWorkingPath, 0o777)
  46. os.MkdirAll(sTempPath, 0o777)
  47. os.Chown(sWorkingPath, sUserID, sGroupID)
  48. os.Chown(sTempPath, sUserID, sGroupID)
  49. return nil
  50. }
  51. func SetLocale(localeId string) {
  52. locale.Set(localeId)
  53. }
  54. func Version() string {
  55. return C.Version
  56. }
  57. func FormatBytes(length int64) string {
  58. return humanize.Bytes(uint64(length))
  59. }
  60. func FormatMemoryBytes(length int64) string {
  61. return humanize.MemoryBytes(uint64(length))
  62. }
  63. func FormatDuration(duration int64) string {
  64. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  65. }
  66. func ProxyDisplayType(proxyType string) string {
  67. return C.ProxyDisplayName(proxyType)
  68. }