setup.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. sFixAndroidStack bool
  22. )
  23. func init() {
  24. debug.SetPanicOnFault(true)
  25. }
  26. type SetupOptions struct {
  27. BasePath string
  28. WorkingPath string
  29. TempPath string
  30. Username string
  31. IsTVOS bool
  32. FixAndroidStack bool
  33. }
  34. func Setup(options *SetupOptions) error {
  35. sBasePath = options.BasePath
  36. sWorkingPath = options.WorkingPath
  37. sTempPath = options.TempPath
  38. if options.Username != "" {
  39. sUser, err := user.Lookup(options.Username)
  40. if err != nil {
  41. return err
  42. }
  43. sUserID, _ = strconv.Atoi(sUser.Uid)
  44. sGroupID, _ = strconv.Atoi(sUser.Gid)
  45. } else {
  46. sUserID = os.Getuid()
  47. sGroupID = os.Getgid()
  48. }
  49. sTVOS = options.IsTVOS
  50. // TODO: remove after fixed
  51. // https://github.com/golang/go/issues/68760
  52. sFixAndroidStack = options.FixAndroidStack
  53. os.MkdirAll(sWorkingPath, 0o777)
  54. os.MkdirAll(sTempPath, 0o777)
  55. if options.Username != "" {
  56. os.Chown(sWorkingPath, sUserID, sGroupID)
  57. os.Chown(sTempPath, sUserID, sGroupID)
  58. }
  59. return nil
  60. }
  61. func SetLocale(localeId string) {
  62. locale.Set(localeId)
  63. }
  64. func Version() string {
  65. return C.Version
  66. }
  67. func FormatBytes(length int64) string {
  68. return humanize.Bytes(uint64(length))
  69. }
  70. func FormatMemoryBytes(length int64) string {
  71. return humanize.MemoryBytes(uint64(length))
  72. }
  73. func FormatDuration(duration int64) string {
  74. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  75. }
  76. func ProxyDisplayType(proxyType string) string {
  77. return C.ProxyDisplayName(proxyType)
  78. }