tcp2.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package tcp2
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net"
  10. "strings"
  11. "time"
  12. "git.me9.top/git/tinymq/config"
  13. "git.me9.top/git/tinymq/conn"
  14. "git.me9.top/git/tinymq/conn/util"
  15. )
  16. const PROTO string = "tcp"
  17. const VERSION uint8 = 2
  18. // 数据包的最大长度
  19. const MAX_LENGTH = 0xFFFF
  20. const MAX2_LENGTH = 0x1FFFFFFF // 500 M,避免申请过大内存
  21. type Tcp2 struct {
  22. cf *config.Config
  23. conn net.Conn
  24. cipher *util.Cipher // 记录当前的加解密类
  25. }
  26. // 服务端
  27. // hash 格式 encryptMethod:encryptKey
  28. func Server(cf *config.Config, bind string, hash string, fn conn.ServerConnectFunc) (err error) {
  29. var ci *util.CipherInfo
  30. var encryptKey string
  31. if hash != "" {
  32. i := strings.Index(hash, ":")
  33. if i <= 0 {
  34. err = errors.New("hash is invalid")
  35. return
  36. }
  37. encryptMethod := hash[0:i]
  38. encryptKey = hash[i+1:]
  39. if c, ok := util.CipherMethod[encryptMethod]; ok {
  40. ci = c
  41. } else {
  42. return errors.New("Unsupported encryption method: " + encryptMethod)
  43. }
  44. }
  45. log.Printf("Listening and serving tcp on %s\n", bind)
  46. l, err := net.Listen("tcp", bind)
  47. if err != nil {
  48. log.Println("[tcp2 Server ERROR]", err)
  49. return
  50. }
  51. go func(l net.Listener) {
  52. defer l.Close()
  53. for {
  54. conn, err := l.Accept()
  55. if err != nil {
  56. log.Println("[accept ERROR]", err)
  57. return
  58. }
  59. go func(conn net.Conn) {
  60. if ci == nil {
  61. c := &Tcp2{
  62. cf: cf,
  63. conn: conn,
  64. }
  65. fn(c)
  66. return
  67. }
  68. var eiv []byte
  69. var div []byte
  70. if ci.IvLen > 0 {
  71. // 服务端 IV
  72. eiv = make([]byte, ci.IvLen)
  73. _, err = rand.Read(eiv)
  74. if err != nil {
  75. log.Println("[tcp2 Server rand.Read ERROR]", err)
  76. return
  77. }
  78. // 发送 IV
  79. conn.SetWriteDeadline(time.Now().Add(time.Duration(cf.WriteWait) * time.Millisecond))
  80. if _, err := conn.Write(eiv); err != nil {
  81. log.Println("[tcp2 Server conn.Write ERROR]", err)
  82. return
  83. }
  84. // 读取 IV
  85. err = conn.SetReadDeadline(time.Now().Add(time.Millisecond * time.Duration(cf.ReadWait)))
  86. if err != nil {
  87. log.Println("[tcp2 Server SetReadDeadline ERROR]", err)
  88. return
  89. }
  90. div = make([]byte, ci.IvLen)
  91. _, err := io.ReadFull(conn, div)
  92. if err != nil {
  93. log.Println("[tcp2 Server ReadFull ERROR]", err)
  94. return
  95. }
  96. }
  97. cipher, err := util.NewCipher(ci, encryptKey, eiv, div)
  98. if err != nil {
  99. log.Println("[tcp2 NewCipher ERROR]", err)
  100. return
  101. }
  102. // 初始化
  103. c := &Tcp2{
  104. cf: cf,
  105. conn: conn,
  106. cipher: cipher,
  107. }
  108. fn(c)
  109. }(conn)
  110. }
  111. }(l)
  112. return
  113. }
  114. // 客户端,新建一个连接
  115. func Client(cf *config.Config, addr string, hash string) (conn.Connect, error) {
  116. // 没有加密的情况
  117. if hash == "" {
  118. conn, err := net.DialTimeout("tcp", addr, time.Duration(cf.ConnectTimeout)*time.Millisecond)
  119. if err != nil {
  120. return nil, err
  121. }
  122. c := &Tcp2{
  123. cf: cf,
  124. conn: conn,
  125. }
  126. return c, nil
  127. }
  128. i := strings.Index(hash, ":")
  129. if i <= 0 {
  130. return nil, errors.New("hash is invalid")
  131. }
  132. encryptMethod := hash[0:i]
  133. encryptKey := hash[i+1:]
  134. ci, ok := util.CipherMethod[encryptMethod]
  135. if !ok {
  136. return nil, errors.New("Unsupported encryption method: " + encryptMethod)
  137. }
  138. conn, err := net.DialTimeout("tcp", addr, time.Duration(cf.ConnectTimeout)*time.Millisecond)
  139. if err != nil {
  140. return nil, err
  141. }
  142. var eiv []byte
  143. var div []byte
  144. if ci.IvLen > 0 {
  145. // 客户端 IV
  146. eiv = make([]byte, ci.IvLen)
  147. _, err = rand.Read(eiv)
  148. if err != nil {
  149. log.Println("[tcp2 Client rand.Read ERROR]", err)
  150. return nil, err
  151. }
  152. // 发送 IV
  153. conn.SetWriteDeadline(time.Now().Add(time.Duration(cf.WriteWait) * time.Millisecond))
  154. if _, err := conn.Write(eiv); err != nil {
  155. log.Println("[tcp2 Client conn.Write ERROR]", err)
  156. return nil, err
  157. }
  158. // 读取 IV
  159. err = conn.SetReadDeadline(time.Now().Add(time.Millisecond * time.Duration(cf.ReadWait)))
  160. if err != nil {
  161. log.Println("[tcp2 Client SetReadDeadline ERROR]", err)
  162. return nil, err
  163. }
  164. div = make([]byte, ci.IvLen)
  165. _, err := io.ReadFull(conn, div)
  166. if err != nil {
  167. log.Println("[tcp2 Client ReadFull ERROR]", err)
  168. return nil, err
  169. }
  170. }
  171. cipher, err := util.NewCipher(ci, encryptKey, eiv, div)
  172. if err != nil {
  173. log.Println("[tcp2 NewCipher ERROR]", err)
  174. return nil, err
  175. }
  176. // 初始化
  177. c := &Tcp2{
  178. cf: cf,
  179. conn: conn,
  180. cipher: cipher,
  181. }
  182. return c, nil
  183. }
  184. // 发送数据到网络
  185. // 如果有加密函数的话会直接修改源数据
  186. func (c *Tcp2) writeMessage(buf []byte) (err error) {
  187. if len(buf) > MAX2_LENGTH {
  188. return fmt.Errorf("data length more than %d", MAX2_LENGTH)
  189. }
  190. if c.cipher != nil {
  191. c.cipher.Encrypt(buf, buf)
  192. }
  193. c.conn.SetWriteDeadline(time.Now().Add(time.Duration(c.cf.WriteWait) * time.Millisecond))
  194. for {
  195. n, err := c.conn.Write(buf)
  196. if err != nil {
  197. return err
  198. }
  199. if n < len(buf) {
  200. buf = buf[n:]
  201. } else {
  202. return nil
  203. }
  204. }
  205. }
  206. // 申请内存并写入数据长度信息
  207. // 还多申请一个字节用于保存crc
  208. func (c *Tcp2) writeDataLen(dlen int) (buf []byte, start int) {
  209. if dlen >= MAX_LENGTH {
  210. buf = make([]byte, dlen+2+4+1)
  211. start = 2 + 4
  212. binary.BigEndian.PutUint16(buf[:2], MAX_LENGTH)
  213. binary.BigEndian.PutUint32(buf[2:6], uint32(dlen))
  214. } else {
  215. buf = make([]byte, dlen+2+1)
  216. start = 2
  217. binary.BigEndian.PutUint16(buf[:2], uint16(dlen))
  218. }
  219. return
  220. }
  221. // 发送Auth信息
  222. // 建立连接后第一个发送的消息
  223. func (c *Tcp2) WriteAuthInfo(channel string, auth []byte) (err error) {
  224. protoLen := len(PROTO)
  225. channelLen := len(channel)
  226. if channelLen > 0xFFFF {
  227. return errors.New("length of channel over")
  228. }
  229. dlen := 2 + 1 + 1 + protoLen + 2 + channelLen + len(auth)
  230. buf, start := c.writeDataLen(dlen)
  231. index := start
  232. binary.BigEndian.PutUint16(buf[index:index+2], config.ID_AUTH)
  233. index += 2
  234. buf[index] = VERSION
  235. index++
  236. buf[index] = byte(protoLen)
  237. index++
  238. copy(buf[index:index+protoLen], []byte(PROTO))
  239. index += protoLen
  240. binary.BigEndian.PutUint16(buf[index:index+2], uint16(channelLen))
  241. index += 2
  242. copy(buf[index:index+channelLen], []byte(channel))
  243. index += channelLen
  244. copy(buf[index:], auth)
  245. buf[start+dlen] = util.CRC8(buf[start : start+dlen])
  246. return c.writeMessage(buf)
  247. }
  248. // 从连接中读取信息
  249. func (c *Tcp2) readMessage(deadline int) ([]byte, error) {
  250. buf := make([]byte, 2)
  251. err := c.conn.SetReadDeadline(time.Now().Add(time.Millisecond * time.Duration(deadline)))
  252. if err != nil {
  253. return nil, err
  254. }
  255. // 读取数据流长度
  256. _, err = io.ReadFull(c.conn, buf)
  257. if err != nil {
  258. return nil, err
  259. }
  260. // 将读出来的数据进行解密
  261. if c.cipher != nil {
  262. c.cipher.Decrypt(buf, buf)
  263. }
  264. dlen := uint32(binary.BigEndian.Uint16(buf))
  265. if dlen < 2 {
  266. return nil, errors.New("length is less to 2")
  267. }
  268. if dlen >= MAX_LENGTH {
  269. // 数据包比较大,通过后面的4位长度来表示实际长度
  270. buf = make([]byte, 4)
  271. _, err := io.ReadFull(c.conn, buf)
  272. if err != nil {
  273. return nil, err
  274. }
  275. if c.cipher != nil {
  276. c.cipher.Decrypt(buf, buf)
  277. }
  278. dlen = binary.BigEndian.Uint32(buf)
  279. if dlen < MAX_LENGTH || dlen > MAX2_LENGTH {
  280. return nil, errors.New("wrong length in read message")
  281. }
  282. }
  283. // 读取指定长度的数据
  284. buf = make([]byte, dlen+1) // 最后一个是crc的值
  285. _, err = io.ReadFull(c.conn, buf)
  286. if err != nil {
  287. return nil, err
  288. }
  289. if c.cipher != nil {
  290. c.cipher.Decrypt(buf, buf)
  291. }
  292. // 检查CRC8
  293. if util.CRC8(buf[:dlen]) != buf[dlen] {
  294. return nil, errors.New("CRC error")
  295. }
  296. return buf[:dlen], nil
  297. }
  298. // 获取Auth信息
  299. // id(uint16)+version(uint8)+proto(string)+channel(string)+auth([]byte)
  300. func (c *Tcp2) ReadAuthInfo() (proto string, version uint8, channel string, auth []byte, err error) {
  301. defer func() {
  302. if r := recover(); r != nil {
  303. err = fmt.Errorf("recovered from panic: %v", r)
  304. return
  305. }
  306. }()
  307. msg, err := c.readMessage(c.cf.ReadWait)
  308. if err != nil {
  309. return
  310. }
  311. msgLen := len(msg)
  312. if msgLen < 4 {
  313. err = errors.New("message length less than 4")
  314. return
  315. }
  316. start := 0
  317. id := binary.BigEndian.Uint16(msg[start : start+2])
  318. if id != config.ID_AUTH {
  319. err = fmt.Errorf("wrong message id: %d", id)
  320. return
  321. }
  322. start += 2
  323. version = msg[start]
  324. if version != VERSION {
  325. err = fmt.Errorf("require version %d, get version: %d", VERSION, version)
  326. return
  327. }
  328. start++
  329. protoLen := int(msg[start])
  330. if protoLen < 2 {
  331. err = errors.New("wrong proto length")
  332. return
  333. }
  334. start++
  335. proto = string(msg[start : start+protoLen])
  336. if proto != PROTO {
  337. err = fmt.Errorf("wrong proto: %s", proto)
  338. return
  339. }
  340. start += protoLen
  341. channelLen := int(binary.BigEndian.Uint16(msg[start : start+2]))
  342. if channelLen < 2 {
  343. err = errors.New("wrong channel length")
  344. return
  345. }
  346. start += 2
  347. channel = string(msg[start : start+channelLen])
  348. start += channelLen
  349. auth = msg[start:]
  350. return
  351. }
  352. // 发送请求数据包到网络
  353. func (c *Tcp2) WriteRequest(id uint16, cmd string, data []byte) error {
  354. // 为了区分请求还是响应包,命令字符串不能超过127个字节,如果超过则截断
  355. cmdLen := len(cmd)
  356. if cmdLen > 0x7F {
  357. return errors.New("command length is more than 0x7F")
  358. }
  359. dlen := 2 + 1 + cmdLen + len(data)
  360. buf, start := c.writeDataLen(dlen)
  361. index := start
  362. binary.BigEndian.PutUint16(buf[index:index+2], id)
  363. index += 2
  364. buf[index] = byte(cmdLen)
  365. index++
  366. copy(buf[index:index+cmdLen], cmd)
  367. index += cmdLen
  368. copy(buf[index:], data)
  369. buf[start+dlen] = util.CRC8(buf[start : start+dlen])
  370. return c.writeMessage(buf)
  371. }
  372. // 发送响应数据包到网络
  373. // 网络格式:[id, stateCode, data]
  374. func (c *Tcp2) WriteResponse(id uint16, state uint8, data []byte) error {
  375. dlen := 2 + 1 + len(data)
  376. buf, start := c.writeDataLen(dlen)
  377. index := start
  378. binary.BigEndian.PutUint16(buf[index:index+2], id)
  379. index += 2
  380. buf[index] = state | 0x80
  381. index++
  382. copy(buf[index:], data)
  383. buf[start+dlen] = util.CRC8(buf[start : start+dlen])
  384. return c.writeMessage(buf)
  385. }
  386. // 发送ping包
  387. func (c *Tcp2) WritePing(id uint16) error {
  388. dlen := 2
  389. buf, start := c.writeDataLen(dlen)
  390. index := start
  391. binary.BigEndian.PutUint16(buf[index:index+2], id)
  392. // index += 2
  393. buf[start+dlen] = util.CRC8(buf[start : start+dlen])
  394. return c.writeMessage(buf)
  395. }
  396. // 获取信息
  397. func (c *Tcp2) ReadMessage(deadline int) (msgType conn.MsgType, id uint16, cmd string, state uint8, data []byte, err error) {
  398. msg, err := c.readMessage(deadline)
  399. if err != nil {
  400. return
  401. }
  402. msgLen := len(msg)
  403. id = binary.BigEndian.Uint16(msg[0:2])
  404. // ping信息
  405. if msgLen == 2 {
  406. msgType = conn.PingMsg
  407. return
  408. }
  409. if id > config.ID_MAX {
  410. err = fmt.Errorf("wrong message id: %d", id)
  411. return
  412. }
  413. cmdx := msg[2]
  414. if (cmdx & 0x80) == 0 {
  415. // 请求包
  416. msgType = conn.RequestMsg
  417. cmdLen := int(cmdx)
  418. cmd = string(msg[3 : cmdLen+3])
  419. data = msg[cmdLen+3:]
  420. return
  421. } else {
  422. // 响应数据包
  423. msgType = conn.ResponseMsg
  424. state = cmdx & 0x7F
  425. data = msg[3:]
  426. return
  427. }
  428. }
  429. // 获取远程的地址
  430. func (c *Tcp2) RemoteAddr() net.Addr {
  431. return c.conn.RemoteAddr()
  432. }
  433. // 获取本地的地址
  434. func (c *Tcp2) LocalAddr() net.Addr {
  435. return c.conn.LocalAddr()
  436. }
  437. func (c *Tcp2) Close() error {
  438. return c.conn.Close()
  439. }