package connections import ( "crypto/rsa" "cwtch.im/cwtch/protocol" "cwtch.im/cwtch/server/fetch" "cwtch.im/cwtch/server/send" "github.com/s-rah/go-ricochet" "github.com/s-rah/go-ricochet/channels" "github.com/s-rah/go-ricochet/connection" "github.com/s-rah/go-ricochet/identity" "github.com/s-rah/go-ricochet/utils" "net" "testing" "time" ) func ServerAuthValid(string, rsa.PublicKey) (allowed, known bool) { return true, true } type TestServer struct { connection.AutoConnectionHandler Received bool } func (ts *TestServer) HandleGroupMessage(gm *protocol.GroupMessage) { ts.Received = true } func (ts *TestServer) HandleFetchRequest() []*protocol.GroupMessage { return []*protocol.GroupMessage{{Ciphertext: []byte("hello"), Spamguard: []byte{}}, {Ciphertext: []byte("hello"), Spamguard: []byte{}}} } func runtestserver(t *testing.T, ts *TestServer, privateKey *rsa.PrivateKey) { ln, _ := net.Listen("tcp", "127.0.0.1:5451") conn, _ := ln.Accept() defer conn.Close() rc, err := goricochet.NegotiateVersionInbound(conn) if err != nil { t.Errorf("Negotiate Version Error: %v", err) } rc.TraceLog(true) err = connection.HandleInboundConnection(rc).ProcessAuthAsServer(identity.Initialize("", privateKey), ServerAuthValid) if err != nil { t.Errorf("ServerAuth Error: %v", err) } ts.RegisterChannelHandler("im.cwtch.server.send", func() channels.Handler { server := new(send.CwtchServerSendChannel) server.Handler = ts return server }) ts.RegisterChannelHandler("im.cwtch.server.fetch", func() channels.Handler { server := new(fetch.CwtchServerFetchChannel) server.Handler = ts return server }) rc.Process(ts) } func TestPeerServerConnection(t *testing.T) { privateKey, err := utils.GeneratePrivateKey() if err != nil { t.Errorf("Private Key Error %v", err) } ts := new(TestServer) ts.Init() go runtestserver(t, ts, privateKey) onionAddr, err := utils.GetOnionAddress(privateKey) if err != nil { t.Errorf("Error getting onion address: %v", err) } psc := NewPeerServerConnection("127.0.0.1:5451|" + onionAddr) numcalls := 0 psc.GroupMessageHandler = func(s string, gm *protocol.GroupMessage) { numcalls++ } state := psc.GetState() if state != DISCONNECTED { t.Errorf("new connections should start in disconnected state") } time.Sleep(time.Second * 1) go psc.Run() time.Sleep(time.Second * 2) state = psc.GetState() if state != AUTHENTICATED { t.Errorf("connection should now be authed(%v), instead was %v", AUTHENTICATED, state) } gm := &protocol.GroupMessage{Ciphertext: []byte("hello")} psc.SendGroupMessage(gm) time.Sleep(time.Second * 2) if ts.Received == false { t.Errorf("Should have received a group message in test server") } if numcalls != 2 { t.Errorf("Should have received 2 calls from fetch request, instead received %v", numcalls) } }