protocol_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "encoding/binary"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "reflect"
  13. "strings"
  14. "testing"
  15. "testing/quick"
  16. "time"
  17. "github.com/calmh/xdr"
  18. )
  19. var (
  20. c0ID = NewDeviceID([]byte{1})
  21. c1ID = NewDeviceID([]byte{2})
  22. quickCfg = &quick.Config{}
  23. )
  24. func TestHeaderEncodeDecode(t *testing.T) {
  25. f := func(ver, id, typ int) bool {
  26. ver = int(uint(ver) % 16)
  27. id = int(uint(id) % 4096)
  28. typ = int(uint(typ) % 256)
  29. h0 := header{version: ver, msgID: id, msgType: typ}
  30. h1 := decodeHeader(encodeHeader(h0))
  31. return h0 == h1
  32. }
  33. if err := quick.Check(f, nil); err != nil {
  34. t.Error(err)
  35. }
  36. }
  37. func TestHeaderMarshalUnmarshal(t *testing.T) {
  38. f := func(ver, id, typ int) bool {
  39. ver = int(uint(ver) % 16)
  40. id = int(uint(id) % 4096)
  41. typ = int(uint(typ) % 256)
  42. buf := make([]byte, 4)
  43. h0 := header{version: ver, msgID: id, msgType: typ}
  44. h0.MarshalXDRInto(&xdr.Marshaller{Data: buf})
  45. var h1 header
  46. h1.UnmarshalXDRFrom(&xdr.Unmarshaller{Data: buf})
  47. return h0 == h1
  48. }
  49. if err := quick.Check(f, nil); err != nil {
  50. t.Error(err)
  51. }
  52. }
  53. func TestHeaderLayout(t *testing.T) {
  54. var e, a uint32
  55. // Version are the first four bits
  56. e = 0xf0000000
  57. a = encodeHeader(header{version: 0xf})
  58. if a != e {
  59. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  60. }
  61. // Message ID are the following 12 bits
  62. e = 0x0fff0000
  63. a = encodeHeader(header{msgID: 0xfff})
  64. if a != e {
  65. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  66. }
  67. // Type are the last 8 bits before reserved
  68. e = 0x0000ff00
  69. a = encodeHeader(header{msgType: 0xff})
  70. if a != e {
  71. t.Errorf("Header layout incorrect; %08x != %08x", a, e)
  72. }
  73. }
  74. func TestPing(t *testing.T) {
  75. ar, aw := io.Pipe()
  76. br, bw := io.Pipe()
  77. c0 := NewConnection(c0ID, ar, bw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  78. c0.Start()
  79. c1 := NewConnection(c1ID, br, aw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  80. c1.Start()
  81. c0.ClusterConfig(ClusterConfigMessage{})
  82. c1.ClusterConfig(ClusterConfigMessage{})
  83. if ok := c0.ping(); !ok {
  84. t.Error("c0 ping failed")
  85. }
  86. if ok := c1.ping(); !ok {
  87. t.Error("c1 ping failed")
  88. }
  89. }
  90. func TestVersionErr(t *testing.T) {
  91. m0 := newTestModel()
  92. m1 := newTestModel()
  93. ar, aw := io.Pipe()
  94. br, bw := io.Pipe()
  95. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  96. c0.Start()
  97. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  98. c1.Start()
  99. c0.ClusterConfig(ClusterConfigMessage{})
  100. c1.ClusterConfig(ClusterConfigMessage{})
  101. timeoutWriteHeader(c0.cw, header{
  102. version: 2, // higher than supported
  103. msgID: 0,
  104. msgType: messageTypeIndex,
  105. })
  106. if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown protocol version") {
  107. t.Error("Connection should close due to unknown version, not", err)
  108. }
  109. }
  110. func TestTypeErr(t *testing.T) {
  111. m0 := newTestModel()
  112. m1 := newTestModel()
  113. ar, aw := io.Pipe()
  114. br, bw := io.Pipe()
  115. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  116. c0.Start()
  117. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  118. c1.Start()
  119. c0.ClusterConfig(ClusterConfigMessage{})
  120. c1.ClusterConfig(ClusterConfigMessage{})
  121. timeoutWriteHeader(c0.cw, header{
  122. version: 0,
  123. msgID: 0,
  124. msgType: 42, // unknown type
  125. })
  126. if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown message type") {
  127. t.Error("Connection should close due to unknown message type, not", err)
  128. }
  129. }
  130. func TestClose(t *testing.T) {
  131. m0 := newTestModel()
  132. m1 := newTestModel()
  133. ar, aw := io.Pipe()
  134. br, bw := io.Pipe()
  135. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  136. c0.Start()
  137. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  138. c1.Start()
  139. c0.ClusterConfig(ClusterConfigMessage{})
  140. c1.ClusterConfig(ClusterConfigMessage{})
  141. c0.close(errors.New("manual close"))
  142. <-c0.closed
  143. if err := m0.closedError(); err == nil || !strings.Contains(err.Error(), "manual close") {
  144. t.Fatal("Connection should be closed")
  145. }
  146. // None of these should panic, some should return an error
  147. if c0.ping() {
  148. t.Error("Ping should not return true")
  149. }
  150. c0.Index("default", nil, 0, nil)
  151. c0.Index("default", nil, 0, nil)
  152. if _, err := c0.Request("default", "foo", 0, 0, nil, false); err == nil {
  153. t.Error("Request should return an error")
  154. }
  155. }
  156. func TestMarshalIndexMessage(t *testing.T) {
  157. if testing.Short() {
  158. quickCfg.MaxCount = 10
  159. }
  160. f := func(m1 IndexMessage) bool {
  161. if len(m1.Options) == 0 {
  162. m1.Options = nil
  163. }
  164. if len(m1.Files) == 0 {
  165. m1.Files = nil
  166. }
  167. for i, f := range m1.Files {
  168. m1.Files[i].CachedSize = 0
  169. if len(f.Blocks) == 0 {
  170. m1.Files[i].Blocks = nil
  171. } else {
  172. for j := range f.Blocks {
  173. f.Blocks[j].Offset = 0
  174. if len(f.Blocks[j].Hash) == 0 {
  175. f.Blocks[j].Hash = nil
  176. }
  177. }
  178. }
  179. }
  180. return testMarshal(t, "index", &m1, &IndexMessage{})
  181. }
  182. if err := quick.Check(f, quickCfg); err != nil {
  183. t.Error(err)
  184. }
  185. }
  186. func TestMarshalRequestMessage(t *testing.T) {
  187. if testing.Short() {
  188. quickCfg.MaxCount = 10
  189. }
  190. f := func(m1 RequestMessage) bool {
  191. if len(m1.Options) == 0 {
  192. m1.Options = nil
  193. }
  194. if len(m1.Hash) == 0 {
  195. m1.Hash = nil
  196. }
  197. return testMarshal(t, "request", &m1, &RequestMessage{})
  198. }
  199. if err := quick.Check(f, quickCfg); err != nil {
  200. t.Error(err)
  201. }
  202. }
  203. func TestMarshalResponseMessage(t *testing.T) {
  204. if testing.Short() {
  205. quickCfg.MaxCount = 10
  206. }
  207. f := func(m1 ResponseMessage) bool {
  208. if len(m1.Data) == 0 {
  209. m1.Data = nil
  210. }
  211. return testMarshal(t, "response", &m1, &ResponseMessage{})
  212. }
  213. if err := quick.Check(f, quickCfg); err != nil {
  214. t.Error(err)
  215. }
  216. }
  217. func TestMarshalClusterConfigMessage(t *testing.T) {
  218. if testing.Short() {
  219. quickCfg.MaxCount = 10
  220. }
  221. f := func(m1 ClusterConfigMessage) bool {
  222. if len(m1.Options) == 0 {
  223. m1.Options = nil
  224. }
  225. if len(m1.Folders) == 0 {
  226. m1.Folders = nil
  227. }
  228. for i := range m1.Folders {
  229. if len(m1.Folders[i].Devices) == 0 {
  230. m1.Folders[i].Devices = nil
  231. }
  232. if len(m1.Folders[i].Options) == 0 {
  233. m1.Folders[i].Options = nil
  234. }
  235. }
  236. return testMarshal(t, "clusterconfig", &m1, &ClusterConfigMessage{})
  237. }
  238. if err := quick.Check(f, quickCfg); err != nil {
  239. t.Error(err)
  240. }
  241. }
  242. func TestMarshalCloseMessage(t *testing.T) {
  243. if testing.Short() {
  244. quickCfg.MaxCount = 10
  245. }
  246. f := func(m1 CloseMessage) bool {
  247. return testMarshal(t, "close", &m1, &CloseMessage{})
  248. }
  249. if err := quick.Check(f, quickCfg); err != nil {
  250. t.Error(err)
  251. }
  252. }
  253. type message interface {
  254. MarshalXDR() ([]byte, error)
  255. UnmarshalXDR([]byte) error
  256. }
  257. func testMarshal(t *testing.T, prefix string, m1, m2 message) bool {
  258. failed := func(bc []byte) {
  259. bs, _ := json.MarshalIndent(m1, "", " ")
  260. ioutil.WriteFile(prefix+"-1.txt", bs, 0644)
  261. bs, _ = json.MarshalIndent(m2, "", " ")
  262. ioutil.WriteFile(prefix+"-2.txt", bs, 0644)
  263. if len(bc) > 0 {
  264. f, _ := os.Create(prefix + "-data.txt")
  265. fmt.Fprint(f, hex.Dump(bc))
  266. f.Close()
  267. }
  268. }
  269. buf, err := m1.MarshalXDR()
  270. if err != nil && strings.Contains(err.Error(), "exceeds size") {
  271. return true
  272. }
  273. if err != nil {
  274. failed(nil)
  275. t.Fatal(err)
  276. }
  277. err = m2.UnmarshalXDR(buf)
  278. if err != nil {
  279. failed(buf)
  280. t.Fatal(err)
  281. }
  282. ok := reflect.DeepEqual(m1, m2)
  283. if !ok {
  284. failed(buf)
  285. }
  286. return ok
  287. }
  288. func timeoutWriteHeader(w io.Writer, hdr header) {
  289. // This tries to write a message header to w, but times out after a while.
  290. // This is useful because in testing, with a PipeWriter, it will block
  291. // forever if the other side isn't reading any more. On the other hand we
  292. // can't just "go" it into the background, because if the other side is
  293. // still there we should wait for the write to complete. Yay.
  294. var buf [8]byte // header and message length
  295. binary.BigEndian.PutUint32(buf[:], encodeHeader(hdr))
  296. binary.BigEndian.PutUint32(buf[4:], 0) // zero message length, explicitly
  297. done := make(chan struct{})
  298. go func() {
  299. w.Write(buf[:])
  300. close(done)
  301. }()
  302. select {
  303. case <-done:
  304. case <-time.After(250 * time.Millisecond):
  305. }
  306. }
  307. func TestFileInfoSize(t *testing.T) {
  308. fi := FileInfo{
  309. Blocks: []BlockInfo{
  310. {Size: 42},
  311. {Offset: 42, Size: 23},
  312. {Offset: 42 + 23, Size: 34},
  313. },
  314. }
  315. size := fi.Size()
  316. want := int64(42 + 23 + 34)
  317. if size != want {
  318. t.Errorf("Incorrect size reported, got %d, want %d", size, want)
  319. }
  320. size = fi.Size() // Cached, this time
  321. if size != want {
  322. t.Errorf("Incorrect cached size reported, got %d, want %d", size, want)
  323. }
  324. fi.CachedSize = 8
  325. want = 8
  326. size = fi.Size() // Ensure it came from the cache
  327. if size != want {
  328. t.Errorf("Incorrect cached size reported, got %d, want %d", size, want)
  329. }
  330. fi.CachedSize = 0
  331. fi.Flags = FlagDirectory
  332. want = 128
  333. size = fi.Size() // Directories are 128 bytes large
  334. if size != want {
  335. t.Errorf("Incorrect cached size reported, got %d, want %d", size, want)
  336. }
  337. fi.CachedSize = 0
  338. fi.Flags = FlagDeleted
  339. want = 128
  340. size = fi.Size() // Also deleted files
  341. if size != want {
  342. t.Errorf("Incorrect cached size reported, got %d, want %d", size, want)
  343. }
  344. }