dail.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package tinymq
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "git.me9.top/git/tinymq/config"
  9. "git.me9.top/git/tinymq/conn"
  10. "git.me9.top/git/tinymq/conn/tcp2"
  11. "git.me9.top/git/tinymq/conn/ws2"
  12. )
  13. // 根据协议名建立连接,输出实际代码实现的协议
  14. // 会一直阻塞直到连接结束
  15. func Dail(host *conn.HostInfo, cf *config.Config) (conn conn.Connect, err error) {
  16. addr := net.JoinHostPort(host.Host, strconv.Itoa(int(host.Port)))
  17. if host.Version == ws2.VERSION && (host.Proto == ws2.PROTO || host.Proto == ws2.PROTO_STL) {
  18. if cf.PrintMsg {
  19. log.Println("[Dail]:", host.Proto, addr, host.Path, host.Hash)
  20. }
  21. conn, err = ws2.Dial(cf, host.Proto, addr, host.Path, host.Hash)
  22. } else if host.Version == tcp2.VERSION && host.Proto == tcp2.PROTO {
  23. if cf.PrintMsg {
  24. log.Println("[Dail]:", host.Proto, addr, host.Hash)
  25. }
  26. conn, err = tcp2.Dial(cf, addr, host.Hash)
  27. } else {
  28. err = fmt.Errorf("not correct protocol and version found in: %+v", host)
  29. }
  30. return
  31. }
  32. // 客户端检验 AuthInfo
  33. func ClientCheckAuthInfo(
  34. conn conn.Connect,
  35. host *conn.HostInfo,
  36. localChannel string,
  37. remoteChannel string,
  38. authFunc AuthFunc,
  39. checkAuthFunc CheckAuthFunc,
  40. ) (err error) {
  41. // 发送验证信息
  42. if err := conn.WriteAuthInfo(localChannel, authFunc(true, host.Proto, host.Version, remoteChannel, nil)); err != nil {
  43. log.Println("[ClientCheckAuthInfo] WriteAuthInfo failed:", err)
  44. return err
  45. }
  46. // 接收频道信息
  47. proto, version, channel, auth, err := conn.ReadAuthInfo()
  48. if err != nil {
  49. log.Println("[ClientCheckAuthInfo] ReadAuthInfo failed:", err)
  50. return err
  51. }
  52. // 检查版本和协议是否一致
  53. if version != host.Version || !strings.HasPrefix(host.Proto, proto) {
  54. err = fmt.Errorf("[ClientCheckAuthInfo] version or protocol wrong: %d, %s", version, proto)
  55. log.Println(err)
  56. return err
  57. }
  58. // 检查频道名称是否匹配
  59. if !strings.Contains(channel, remoteChannel) {
  60. err = fmt.Errorf("[ClientCheckAuthInfo] channel want %s, get %s", remoteChannel, channel)
  61. log.Println(err)
  62. return err
  63. }
  64. // 检查验证是否合法
  65. if !checkAuthFunc(true, proto, version, channel, auth) {
  66. err = fmt.Errorf("[ClientCheckAuthInfo] failed in proto: %s, version: %d, channel: %s, auth: %s", proto, version, channel, string(auth))
  67. log.Println(err)
  68. return err
  69. }
  70. return
  71. }