setup.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/include"
  11. "github.com/sagernet/sing-box/log"
  12. )
  13. var (
  14. sBasePath string
  15. sWorkingPath string
  16. sTempPath string
  17. sUserID int
  18. sGroupID int
  19. sTVOS bool
  20. )
  21. func init() {
  22. debug.SetPanicOnFault(true)
  23. debug.SetTraceback("all")
  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 Version() string {
  52. return C.Version
  53. }
  54. func FormatBytes(length int64) string {
  55. return humanize.Bytes(uint64(length))
  56. }
  57. func FormatMemoryBytes(length int64) string {
  58. return humanize.MemoryBytes(uint64(length))
  59. }
  60. func FormatDuration(duration int64) string {
  61. return log.FormatDuration(time.Duration(duration) * time.Millisecond)
  62. }
  63. func ProxyDisplayType(proxyType string) string {
  64. return C.ProxyDisplayName(proxyType)
  65. }