hello_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. }
  34. res, err := ExchangeHello(conn, send)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. if res.ClientName != expected.ClientName {
  39. t.Errorf("incorrect ClientName %q != expected %q", res.ClientName, expected.ClientName)
  40. }
  41. if res.ClientVersion != expected.ClientVersion {
  42. t.Errorf("incorrect ClientVersion %q != expected %q", res.ClientVersion, expected.ClientVersion)
  43. }
  44. if res.DeviceName != expected.DeviceName {
  45. t.Errorf("incorrect DeviceName %q != expected %q", res.DeviceName, expected.DeviceName)
  46. }
  47. }
  48. func TestOldHelloMsgs(t *testing.T) {
  49. // Tests that we can correctly identify old/missing/unknown hello
  50. // messages.
  51. cases := []struct {
  52. msg string
  53. err error
  54. }{
  55. {"00010001", ErrTooOldVersion}, // v12
  56. {"9F79BC40", ErrTooOldVersion}, // v13
  57. {"12345678", ErrUnknownMagic},
  58. }
  59. for _, tc := range cases {
  60. msg, _ := hex.DecodeString(tc.msg)
  61. outBuf := new(bytes.Buffer)
  62. outBuf.Write(msg)
  63. inBuf := new(bytes.Buffer)
  64. conn := &readWriter{outBuf, inBuf}
  65. send := &Hello{
  66. DeviceName: "this device",
  67. ClientName: "other client",
  68. ClientVersion: "v1.0.0",
  69. }
  70. _, err := ExchangeHello(conn, send)
  71. if err != tc.err {
  72. t.Errorf("unexpected error %v != %v", err, tc.err)
  73. }
  74. }
  75. }
  76. type readWriter struct {
  77. r io.Reader
  78. w io.Writer
  79. }
  80. func (rw *readWriter) Write(data []byte) (int, error) {
  81. return rw.w.Write(data)
  82. }
  83. func (rw *readWriter) Read(data []byte) (int, error) {
  84. return rw.r.Read(data)
  85. }