hello_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright (C) 2016 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "io"
  8. "testing"
  9. )
  10. func TestVersion14Hello(t *testing.T) {
  11. // Tests that we can send and receive a version 0.14 hello message.
  12. expected := Hello{
  13. DeviceName: "test device",
  14. ClientName: "syncthing",
  15. ClientVersion: "v0.14.5",
  16. }
  17. msgBuf, err := expected.Marshal()
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. hdrBuf := make([]byte, 6)
  22. binary.BigEndian.PutUint32(hdrBuf, HelloMessageMagic)
  23. binary.BigEndian.PutUint16(hdrBuf[4:], uint16(len(msgBuf)))
  24. outBuf := new(bytes.Buffer)
  25. outBuf.Write(hdrBuf)
  26. outBuf.Write(msgBuf)
  27. inBuf := new(bytes.Buffer)
  28. conn := &readWriter{outBuf, inBuf}
  29. send := Hello{
  30. DeviceName: "this device",
  31. ClientName: "other client",
  32. ClientVersion: "v0.14.6",
  33. Timestamp: 1234567890,
  34. }
  35. res, err := ExchangeHello(conn, send)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. if res.ClientName != expected.ClientName {
  40. t.Errorf("incorrect ClientName %q != expected %q", res.ClientName, expected.ClientName)
  41. }
  42. if res.ClientVersion != expected.ClientVersion {
  43. t.Errorf("incorrect ClientVersion %q != expected %q", res.ClientVersion, expected.ClientVersion)
  44. }
  45. if res.DeviceName != expected.DeviceName {
  46. t.Errorf("incorrect DeviceName %q != expected %q", res.DeviceName, expected.DeviceName)
  47. }
  48. }
  49. func TestOldHelloMsgs(t *testing.T) {
  50. // Tests that we can correctly identify old/missing/unknown hello
  51. // messages.
  52. cases := []struct {
  53. msg string
  54. err error
  55. }{
  56. {"00010001", ErrTooOldVersion}, // v12
  57. {"9F79BC40", ErrTooOldVersion}, // v13
  58. {"12345678", ErrUnknownMagic},
  59. }
  60. for _, tc := range cases {
  61. msg, _ := hex.DecodeString(tc.msg)
  62. outBuf := new(bytes.Buffer)
  63. outBuf.Write(msg)
  64. inBuf := new(bytes.Buffer)
  65. conn := &readWriter{outBuf, inBuf}
  66. send := Hello{
  67. DeviceName: "this device",
  68. ClientName: "other client",
  69. ClientVersion: "v1.0.0",
  70. Timestamp: 1234567890,
  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. }