protocol_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "reflect"
  15. "strings"
  16. "testing"
  17. "testing/quick"
  18. "time"
  19. "github.com/calmh/xdr"
  20. )
  21. var (
  22. c0ID = NewDeviceID([]byte{1})
  23. c1ID = NewDeviceID([]byte{2})
  24. quickCfg = &quick.Config{}
  25. )
  26. func TestMain(m *testing.M) {
  27. flag.Parse()
  28. if flag.Lookup("test.short").Value.String() != "false" {
  29. quickCfg.MaxCount = 10
  30. }
  31. os.Exit(m.Run())
  32. }
  33. func TestHeaderFunctions(t *testing.T) {
  34. f := func(ver, id, typ int) bool {
  35. ver = int(uint(ver) % 16)
  36. id = int(uint(id) % 4096)
  37. typ = int(uint(typ) % 256)
  38. h0 := header{version: ver, msgID: id, msgType: typ}
  39. h1 := decodeHeader(encodeHeader(h0))
  40. return h0 == h1
  41. }
  42. if err := quick.Check(f, nil); err != nil {
  43. t.Error(err)
  44. }
  45. }
  46. func TestHeaderLayout(t *testing.T) {
  47. var e, a uint32
  48. // Version are the first four bits
  49. e = 0xf0000000
  50. a = encodeHeader(header{version: 0xf})
  51. if a != e {
  52. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  53. }
  54. // Message ID are the following 12 bits
  55. e = 0x0fff0000
  56. a = encodeHeader(header{msgID: 0xfff})
  57. if a != e {
  58. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  59. }
  60. // Type are the last 8 bits before reserved
  61. e = 0x0000ff00
  62. a = encodeHeader(header{msgType: 0xff})
  63. if a != e {
  64. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  65. }
  66. }
  67. func TestPing(t *testing.T) {
  68. ar, aw := io.Pipe()
  69. br, bw := io.Pipe()
  70. c0 := NewConnection(c0ID, ar, bw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  71. c0.Start()
  72. c1 := NewConnection(c1ID, br, aw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  73. c1.Start()
  74. c0.ClusterConfig(ClusterConfigMessage{})
  75. c1.ClusterConfig(ClusterConfigMessage{})
  76. if ok := c0.ping(); !ok {
  77. t.Error("c0 ping failed")
  78. }
  79. if ok := c1.ping(); !ok {
  80. t.Error("c1 ping failed")
  81. }
  82. }
  83. func TestVersionErr(t *testing.T) {
  84. m0 := newTestModel()
  85. m1 := newTestModel()
  86. ar, aw := io.Pipe()
  87. br, bw := io.Pipe()
  88. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  89. c0.Start()
  90. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  91. c1.Start()
  92. c0.ClusterConfig(ClusterConfigMessage{})
  93. c1.ClusterConfig(ClusterConfigMessage{})
  94. w := xdr.NewWriter(c0.cw)
  95. timeoutWriteHeader(w, header{
  96. version: 2, // higher than supported
  97. msgID: 0,
  98. msgType: messageTypeIndex,
  99. })
  100. if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown protocol version") {
  101. t.Error("Connection should close due to unknown version, not", err)
  102. }
  103. }
  104. func TestTypeErr(t *testing.T) {
  105. m0 := newTestModel()
  106. m1 := newTestModel()
  107. ar, aw := io.Pipe()
  108. br, bw := io.Pipe()
  109. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  110. c0.Start()
  111. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  112. c1.Start()
  113. c0.ClusterConfig(ClusterConfigMessage{})
  114. c1.ClusterConfig(ClusterConfigMessage{})
  115. w := xdr.NewWriter(c0.cw)
  116. timeoutWriteHeader(w, header{
  117. version: 0,
  118. msgID: 0,
  119. msgType: 42, // unknown type
  120. })
  121. if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown message type") {
  122. t.Error("Connection should close due to unknown message type, not", err)
  123. }
  124. }
  125. func TestClose(t *testing.T) {
  126. m0 := newTestModel()
  127. m1 := newTestModel()
  128. ar, aw := io.Pipe()
  129. br, bw := io.Pipe()
  130. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  131. c0.Start()
  132. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  133. c1.Start()
  134. c0.ClusterConfig(ClusterConfigMessage{})
  135. c1.ClusterConfig(ClusterConfigMessage{})
  136. c0.close(errors.New("manual close"))
  137. <-c0.closed
  138. if err := m0.closedError(); err == nil || !strings.Contains(err.Error(), "manual close") {
  139. t.Fatal("Connection should be closed")
  140. }
  141. // None of these should panic, some should return an error
  142. if c0.ping() {
  143. t.Error("Ping should not return true")
  144. }
  145. c0.Index("default", nil, 0, nil)
  146. c0.Index("default", nil, 0, nil)
  147. if _, err := c0.Request("default", "foo", 0, 0, nil, 0, nil); err == nil {
  148. t.Error("Request should return an error")
  149. }
  150. }
  151. func TestElementSizeExceededNested(t *testing.T) {
  152. m := ClusterConfigMessage{
  153. ClientName: "longstringlongstringlongstringinglongstringlongstringlonlongstringlongstringlon",
  154. }
  155. _, err := m.EncodeXDR(ioutil.Discard)
  156. if err == nil {
  157. t.Errorf("ID length %d > max 64, but no error", len(m.Folders[0].ID))
  158. }
  159. }
  160. func TestMarshalIndexMessage(t *testing.T) {
  161. f := func(m1 IndexMessage) bool {
  162. for i, f := range m1.Files {
  163. m1.Files[i].CachedSize = 0
  164. for j := range f.Blocks {
  165. f.Blocks[j].Offset = 0
  166. if len(f.Blocks[j].Hash) == 0 {
  167. f.Blocks[j].Hash = nil
  168. }
  169. }
  170. }
  171. return testMarshal(t, "index", &m1, &IndexMessage{})
  172. }
  173. if err := quick.Check(f, quickCfg); err != nil {
  174. t.Error(err)
  175. }
  176. }
  177. func TestMarshalRequestMessage(t *testing.T) {
  178. f := func(m1 RequestMessage) bool {
  179. return testMarshal(t, "request", &m1, &RequestMessage{})
  180. }
  181. if err := quick.Check(f, quickCfg); err != nil {
  182. t.Error(err)
  183. }
  184. }
  185. func TestMarshalResponseMessage(t *testing.T) {
  186. f := func(m1 ResponseMessage) bool {
  187. if len(m1.Data) == 0 {
  188. m1.Data = nil
  189. }
  190. return testMarshal(t, "response", &m1, &ResponseMessage{})
  191. }
  192. if err := quick.Check(f, quickCfg); err != nil {
  193. t.Error(err)
  194. }
  195. }
  196. func TestMarshalClusterConfigMessage(t *testing.T) {
  197. f := func(m1 ClusterConfigMessage) bool {
  198. return testMarshal(t, "clusterconfig", &m1, &ClusterConfigMessage{})
  199. }
  200. if err := quick.Check(f, quickCfg); err != nil {
  201. t.Error(err)
  202. }
  203. }
  204. func TestMarshalCloseMessage(t *testing.T) {
  205. f := func(m1 CloseMessage) bool {
  206. return testMarshal(t, "close", &m1, &CloseMessage{})
  207. }
  208. if err := quick.Check(f, quickCfg); err != nil {
  209. t.Error(err)
  210. }
  211. }
  212. type message interface {
  213. EncodeXDR(io.Writer) (int, error)
  214. DecodeXDR(io.Reader) error
  215. }
  216. func testMarshal(t *testing.T, prefix string, m1, m2 message) bool {
  217. var buf bytes.Buffer
  218. failed := func(bc []byte) {
  219. bs, _ := json.MarshalIndent(m1, "", " ")
  220. ioutil.WriteFile(prefix+"-1.txt", bs, 0644)
  221. bs, _ = json.MarshalIndent(m2, "", " ")
  222. ioutil.WriteFile(prefix+"-2.txt", bs, 0644)
  223. if len(bc) > 0 {
  224. f, _ := os.Create(prefix + "-data.txt")
  225. fmt.Fprint(f, hex.Dump(bc))
  226. f.Close()
  227. }
  228. }
  229. _, err := m1.EncodeXDR(&buf)
  230. if err != nil && strings.Contains(err.Error(), "exceeds size") {
  231. return true
  232. }
  233. if err != nil {
  234. failed(nil)
  235. t.Fatal(err)
  236. }
  237. bc := make([]byte, len(buf.Bytes()))
  238. copy(bc, buf.Bytes())
  239. err = m2.DecodeXDR(&buf)
  240. if err != nil {
  241. failed(bc)
  242. t.Fatal(err)
  243. }
  244. ok := reflect.DeepEqual(m1, m2)
  245. if !ok {
  246. failed(bc)
  247. }
  248. return ok
  249. }
  250. func timeoutWriteHeader(w *xdr.Writer, hdr header) {
  251. // This tries to write a message header to w, but times out after a while.
  252. // This is useful because in testing, with a PipeWriter, it will block
  253. // forever if the other side isn't reading any more. On the other hand we
  254. // can't just "go" it into the background, because if the other side is
  255. // still there we should wait for the write to complete. Yay.
  256. var buf [8]byte // header and message length
  257. binary.BigEndian.PutUint32(buf[:], encodeHeader(hdr))
  258. binary.BigEndian.PutUint32(buf[4:], 0) // zero message length, explicitly
  259. done := make(chan struct{})
  260. go func() {
  261. w.WriteRaw(buf[:])
  262. l.Infoln("write completed")
  263. close(done)
  264. }()
  265. select {
  266. case <-done:
  267. case <-time.After(250 * time.Millisecond):
  268. }
  269. }