setup.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/log"
  11. )
  12. var (
  13. sBasePath string
  14. sWorkingPath string
  15. sTempPath string
  16. sUserID int
  17. sGroupID int
  18. sTVOS bool
  19. )
  20. func init() {
  21. debug.SetPanicOnFault(true)
  22. debug.SetTraceback("all")
  23. }
  24. func Setup(basePath string, workingPath string, tempPath string, isTVOS bool) {
  25. sBasePath = basePath
  26. sWorkingPath = workingPath
  27. sTempPath = tempPath
  28. sUserID = os.Getuid()
  29. sGroupID = os.Getgid()
  30. sTVOS = isTVOS
  31. os.MkdirAll(sWorkingPath, 0o777)
  32. os.MkdirAll(sTempPath, 0o777)
  33. }
  34. func SetupWithUsername(basePath string, workingPath string, tempPath string, username string) error {
  35. sBasePath = basePath
  36. sWorkingPath = workingPath
  37. sTempPath = tempPath
  38. sUser, err := user.Lookup(username)
  39. if err != nil {
  40. return err
  41. }
  42. sUserID, _ = strconv.Atoi(sUser.Uid)
  43. sGroupID, _ = strconv.Atoi(sUser.Gid)
  44. os.MkdirAll(sWorkingPath, 0o777)
  45. os.MkdirAll(sTempPath, 0o777)
  46. os.Chown(sWorkingPath, sUserID, sGroupID)
  47. os.Chown(sTempPath, sUserID, sGroupID)
  48. return nil
  49. }
  50. func Version() string {
  51. return C.Version
  52. }
  53. func FormatBytes(length int64) string {
  54. return humanize.Bytes(uint64(length))
  55. }
  56. func FormatMemoryBytes(length int64) string {
  57. return humanize.MemoryBytes(uint64(length))
  58. }
  59. func FormatDuration(duration int64) string {
  60. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  61. }
  62. func ProxyDisplayType(proxyType string) string {
  63. return C.ProxyDisplayName(proxyType)
  64. }