hello_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Copyright (C) 2016 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "io"
  8. "regexp"
  9. "testing"
  10. )
  11. var spaceRe = regexp.MustCompile(`\s`)
  12. func TestVersion14Hello(t *testing.T) {
  13. // Tests that we can send and receive a version 0.14 hello message.
  14. expected := Hello{
  15. DeviceName: "test device",
  16. ClientName: "syncthing",
  17. ClientVersion: "v0.14.5",
  18. }
  19. msgBuf, err := expected.Marshal()
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. hdrBuf := make([]byte, 6)
  24. binary.BigEndian.PutUint32(hdrBuf, HelloMessageMagic)
  25. binary.BigEndian.PutUint16(hdrBuf[4:], uint16(len(msgBuf)))
  26. outBuf := new(bytes.Buffer)
  27. outBuf.Write(hdrBuf)
  28. outBuf.Write(msgBuf)
  29. inBuf := new(bytes.Buffer)
  30. conn := &readWriter{outBuf, inBuf}
  31. send := &Hello{
  32. DeviceName: "this device",
  33. ClientName: "other client",
  34. ClientVersion: "v0.14.6",
  35. }
  36. res, err := ExchangeHello(conn, send)
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. if res.ClientName != expected.ClientName {
  41. t.Errorf("incorrect ClientName %q != expected %q", res.ClientName, expected.ClientName)
  42. }
  43. if res.ClientVersion != expected.ClientVersion {
  44. t.Errorf("incorrect ClientVersion %q != expected %q", res.ClientVersion, expected.ClientVersion)
  45. }
  46. if res.DeviceName != expected.DeviceName {
  47. t.Errorf("incorrect DeviceName %q != expected %q", res.DeviceName, expected.DeviceName)
  48. }
  49. }
  50. func TestOldHelloMsgs(t *testing.T) {
  51. // Tests that we can correctly identify old/missing/unknown hello
  52. // messages.
  53. cases := []struct {
  54. msg string
  55. err error
  56. }{
  57. {"00010001", ErrTooOldVersion}, // v12
  58. {"9F79BC40", ErrTooOldVersion}, // v13
  59. {"12345678", ErrUnknownMagic},
  60. }
  61. for _, tc := range cases {
  62. msg, _ := hex.DecodeString(tc.msg)
  63. outBuf := new(bytes.Buffer)
  64. outBuf.Write(msg)
  65. inBuf := new(bytes.Buffer)
  66. conn := &readWriter{outBuf, inBuf}
  67. send := &Hello{
  68. DeviceName: "this device",
  69. ClientName: "other client",
  70. ClientVersion: "v1.0.0",
  71. }
  72. _, err := ExchangeHello(conn, send)
  73. if err != tc.err {
  74. t.Errorf("unexpected error %v != %v", err, tc.err)
  75. }
  76. }
  77. }
  78. type readWriter struct {
  79. r io.Reader
  80. w io.Writer
  81. }
  82. func (rw *readWriter) Write(data []byte) (int, error) {
  83. return rw.w.Write(data)
  84. }
  85. func (rw *readWriter) Read(data []byte) (int, error) {
  86. return rw.r.Read(data)
  87. }