protocol_test.go 9.3 KB

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