setup.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package libbox
  2. import (
  3. "os"
  4. "os/user"
  5. "runtime/debug"
  6. "strconv"
  7. "time"
  8. C "github.com/sagernet/sing-box/constant"
  9. "github.com/sagernet/sing-box/experimental/locale"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing/common/byteformats"
  12. )
  13. var (
  14. sBasePath string
  15. sWorkingPath string
  16. sTempPath string
  17. sUserID int
  18. sGroupID int
  19. sTVOS bool
  20. sFixAndroidStack bool
  21. )
  22. func init() {
  23. debug.SetPanicOnFault(true)
  24. }
  25. type SetupOptions struct {
  26. BasePath string
  27. WorkingPath string
  28. TempPath string
  29. Username string
  30. IsTVOS bool
  31. FixAndroidStack bool
  32. }
  33. func Setup(options *SetupOptions) error {
  34. sBasePath = options.BasePath
  35. sWorkingPath = options.WorkingPath
  36. sTempPath = options.TempPath
  37. if options.Username != "" {
  38. sUser, err := user.Lookup(options.Username)
  39. if err != nil {
  40. return err
  41. }
  42. sUserID, _ = strconv.Atoi(sUser.Uid)
  43. sGroupID, _ = strconv.Atoi(sUser.Gid)
  44. } else {
  45. sUserID = os.Getuid()
  46. sGroupID = os.Getgid()
  47. }
  48. sTVOS = options.IsTVOS
  49. // TODO: remove after fixed
  50. // https://github.com/golang/go/issues/68760
  51. sFixAndroidStack = options.FixAndroidStack
  52. os.MkdirAll(sWorkingPath, 0o777)
  53. os.MkdirAll(sTempPath, 0o777)
  54. if options.Username != "" {
  55. os.Chown(sWorkingPath, sUserID, sGroupID)
  56. os.Chown(sTempPath, sUserID, sGroupID)
  57. }
  58. return nil
  59. }
  60. func SetLocale(localeId string) {
  61. locale.Set(localeId)
  62. }
  63. func Version() string {
  64. return C.Version
  65. }
  66. func FormatBytes(length int64) string {
  67. return byteformats.FormatBytes(uint64(length))
  68. }
  69. func FormatMemoryBytes(length int64) string {
  70. return byteformats.FormatMemoryBytes(uint64(length))
  71. }
  72. func FormatDuration(duration int64) string {
  73. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  74. }
  75. func ProxyDisplayType(proxyType string) string {
  76. return C.ProxyDisplayName(proxyType)
  77. }