setup.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package libbox
  2. import (
  3. "os"
  4. "os/user"
  5. "strconv"
  6. "time"
  7. "github.com/sagernet/sing-box/common/humanize"
  8. C "github.com/sagernet/sing-box/constant"
  9. _ "github.com/sagernet/sing-box/include"
  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 Setup(basePath string, workingPath string, tempPath string, isTVOS bool) {
  21. sBasePath = basePath
  22. sWorkingPath = workingPath
  23. sTempPath = tempPath
  24. sUserID = os.Getuid()
  25. sGroupID = os.Getgid()
  26. sTVOS = isTVOS
  27. os.MkdirAll(sWorkingPath, 0o777)
  28. os.MkdirAll(sTempPath, 0o777)
  29. }
  30. func SetupWithUsername(basePath string, workingPath string, tempPath string, username string) error {
  31. sBasePath = basePath
  32. sWorkingPath = workingPath
  33. sTempPath = tempPath
  34. sUser, err := user.Lookup(username)
  35. if err != nil {
  36. return err
  37. }
  38. sUserID, _ = strconv.Atoi(sUser.Uid)
  39. sGroupID, _ = strconv.Atoi(sUser.Gid)
  40. os.MkdirAll(sWorkingPath, 0o777)
  41. os.MkdirAll(sTempPath, 0o777)
  42. os.Chown(sWorkingPath, sUserID, sGroupID)
  43. os.Chown(sTempPath, sUserID, sGroupID)
  44. return nil
  45. }
  46. func Version() string {
  47. return C.Version
  48. }
  49. func FormatBytes(length int64) string {
  50. return humanize.Bytes(uint64(length))
  51. }
  52. func FormatMemoryBytes(length int64) string {
  53. return humanize.MemoryBytes(uint64(length))
  54. }
  55. func FormatDuration(duration int64) string {
  56. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  57. }
  58. func ProxyDisplayType(proxyType string) string {
  59. return C.ProxyDisplayName(proxyType)
  60. }