log_client.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //go:build ios
  2. package libbox
  3. import (
  4. "net"
  5. "path/filepath"
  6. "github.com/sagernet/sing/common"
  7. )
  8. type LogClient struct {
  9. sockPath string
  10. handler LogClientHandler
  11. conn net.Conn
  12. }
  13. type LogClientHandler interface {
  14. Connected()
  15. Disconnected()
  16. WriteLog(message string)
  17. }
  18. func NewLogClient(sharedDirectory string, handler LogClientHandler) *LogClient {
  19. return &LogClient{
  20. sockPath: filepath.Join(sharedDirectory, "log.sock"),
  21. handler: handler,
  22. }
  23. }
  24. func (c *LogClient) Connect() error {
  25. conn, err := net.DialUnix("unix", nil, &net.UnixAddr{
  26. Name: c.sockPath,
  27. Net: "unix",
  28. })
  29. if err != nil {
  30. return err
  31. }
  32. c.conn = conn
  33. go c.loopConnection(&messageConn{conn})
  34. return nil
  35. }
  36. func (c *LogClient) Disconnect() error {
  37. return common.Close(c.conn)
  38. }
  39. func (c *LogClient) loopConnection(conn *messageConn) {
  40. c.handler.Connected()
  41. defer c.handler.Disconnected()
  42. for {
  43. message, err := conn.Read()
  44. if err != nil {
  45. c.handler.WriteLog("(log client error) " + err.Error())
  46. return
  47. }
  48. c.handler.WriteLog(string(message))
  49. }
  50. }