-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrelay.go
287 lines (261 loc) · 7.21 KB
/
relay.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"encoding/json"
"github.com/gorilla/websocket"
"log"
"net/http"
"sync"
"time"
mh "gx/ipfs/QmZyZDi491cCNTLfAhwcaDii2Kg4pwKRkhqQzURGDvY6ua/go-multihash"
"errors"
"github.com/OpenBazaar/openbazaar-go/mobile"
"encoding/base64"
"context"
"gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
"crypto/sha256"
"encoding/hex"
"gx/ipfs/QmZoWKhxUmZ2seW4BzX6fJkNR8hh9PsGModr7q171yq2SS/go-libp2p-peer"
"github.com/OpenBazaar/openbazaar-go/ipfs"
"strings"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type RelayProtocol struct {
node *mobile.Node
db Datastore
connectedNodes map[string][]*websocket.Conn
lock sync.RWMutex
}
func StartRelayProtocol(n *mobile.Node, db Datastore) error {
rp := &RelayProtocol{
connectedNodes: make(map[string][]*websocket.Conn),
lock: sync.RWMutex{},
db: db,
node: n,
}
go rp.handlePublishes()
http.HandleFunc("/", rp.handleNewConnection)
return http.ListenAndServe(":8080", nil)
}
// Run subscription protocol
func (rp *RelayProtocol) handleNewConnection(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
// The first message should be an SubscribeMessage message
// We'll set up a timer, if we don't get one within 30
// seconds we'll disconnect from this client.
subChan := make(chan struct{})
var subscribeMessage []byte
go func() {
_, subscribeMessage, err = c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
subChan <- struct{}{}
}()
ticker := time.NewTicker(time.Second * 30)
subscribeLoop:
for {
select {
case <-subChan:
break subscribeLoop
case <-ticker.C:
ticker.Stop()
log.Println("peer timed out on connection")
return
}
}
ticker.Stop()
// Unmarshall message
incomingMessage := new(TypedMessage)
err = json.Unmarshal(subscribeMessage, incomingMessage)
if err != nil {
c.WriteMessage(1, []byte(`{"error": "invalid incoming message"}`))
log.Println("invalid incoming message:", err)
return
}
subscription := new(SubscribeMessage)
err = json.Unmarshal(incomingMessage.Data, subscription)
if err != nil {
c.WriteMessage(1, []byte(`{"error": "invalid subscribe message"}`))
log.Println("invalid subscribe message:", err)
return
}
if subscription.UserID == "" {
c.WriteMessage(1, []byte(`{"error": "userID required"}`))
log.Println("received subscribe message without userID")
return
}
// Decode the subscription key
subscriptionKey, err := mh.FromB58String(subscription.SubscriptionKey)
if err != nil {
c.WriteMessage(1, []byte(`{"error": "subscription key"}`))
log.Println("invalid subscription key:", err)
return
}
if err := rp.db.AddSubscription(subscriptionKey); err != nil {
c.WriteMessage(1, []byte(`{"error": "database error"}`))
log.Println("error saving subscriber to database:", err)
return
}
if err := rp.subscribe(subscriptionKey); err != nil {
c.WriteMessage(1, []byte(`{"error": "subscribe error"}`))
log.Println("error subscribing to pubsub:", err)
return
}
rp.lock.Lock()
conns, _ := rp.connectedNodes[subscriptionKey.B58String()]
conns = append(conns, c)
rp.connectedNodes[subscriptionKey.B58String()] = conns
rp.lock.Unlock()
defer func(wsConn *websocket.Conn) {
rp.lock.Lock()
conns, ok := rp.connectedNodes[subscriptionKey.B58String()]
// If only one connection, remove it from map
if ok && len(conns) == 1 {
delete(rp.connectedNodes, subscriptionKey.B58String())
} else if ok { // Otherwise just delete the connection from the list
for i, conn := range conns {
if conn == wsConn {
conns[i] = conns[len(conns)-1]
conns = conns[:len(conns)-1]
rp.connectedNodes[subscriptionKey.B58String()] = conns
break
}
}
}
rp.lock.Unlock()
}(c)
log.Printf("New peer subscription: %s\n", subscriptionKey.B58String())
c.WriteMessage(1, []byte(`{"subscribe": true}`))
// Load messages for subscription key
messages, err := rp.db.GetMessages(subscription.UserID, subscriptionKey)
if err != nil {
log.Println("error fetching messages from database: ", err)
}
for _, message := range messages {
formatted, err := json.MarshalIndent(message, "", " ")
if err != nil {
log.Println(err)
continue
}
c.WriteMessage(1, formatted)
}
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
if err := rp.handleMessage(message, subscription.UserID); err != nil {
log.Println(err)
}
}
}
func (rp *RelayProtocol) handleMessage(m []byte, userID string) error {
incomingMessage := new(TypedMessage)
err := json.Unmarshal(m, incomingMessage)
if err != nil {
log.Println("invalid incoming message:", err)
return err
}
message, err := unmarshalMessage(incomingMessage)
if err != nil {
return err
}
switch incomingMessage.Type {
case "EncryptedMessage":
em := message.(EncryptedMessage)
b, err := base64.StdEncoding.DecodeString(em.Message)
if err != nil {
return err
}
_, err = peer.IDB58Decode(em.Recipient)
if err != nil {
return nil
}
return rp.node.OpenBazaarNode.SendOfflineRelay(em.Recipient, b)
case "AckMessage":
return rp.db.MarkMessageAsRead(message.(AckMessage).MessageID, userID)
}
return nil
}
func unmarshalMessage(message *TypedMessage) (interface{}, error) {
formatted := strings.Replace(string(message.Data) , "\n", "", -1)
switch message.Type {
case "EncryptedMessage":
var encryptedMessage EncryptedMessage
if err := json.Unmarshal([]byte(formatted), &encryptedMessage); err == nil {
return encryptedMessage, nil
}
case "AckMessage":
var ack AckMessage
if err := json.Unmarshal([]byte(formatted), &ack); err == nil {
return ack, nil
}
}
return nil, errors.New("unknown message type")
}
func (rp *RelayProtocol) handlePublishes() {
subs, err := rp.db.GetSubscriptions()
if err != nil {
log.Fatal(err)
}
for _, sub := range subs {
if err := rp.subscribe(sub); err != nil {
log.Println(err)
}
}
}
func (rp *RelayProtocol) subscribe(sub mh.Multihash) error {
k, err := cid.Decode(sub.B58String())
if err != nil {
return err
}
topic := "/offlinemessage/"+k.String()
currentSubscriptions := rp.node.OpenBazaarNode.Pubsub.Subscriber.GetSubscriptions()
for _, s := range currentSubscriptions {
if s == topic { // already subscribed
return nil
}
}
c, err := rp.node.OpenBazaarNode.Pubsub.Subscriber.Subscribe(context.Background(), topic)
if err != nil {
return err
}
go func(subscriptionKey mh.Multihash, ch <-chan []byte) {
for {
data := <- ch
messageID := sha256.Sum256(data)
err := rp.db.PutMessage(subscriptionKey, hex.EncodeToString(messageID[:]), data)
if err != nil {
log.Println(err)
}
nodes, ok := rp.connectedNodes[subscriptionKey.B58String()]
if ok {
for _, node := range nodes {
messageID := sha256.Sum256(data)
em := EncryptedMessage{
ID: hex.EncodeToString(messageID[:]),
Message: base64.StdEncoding.EncodeToString(data),
}
out ,err := json.MarshalIndent(em, "", " ")
if err != nil {
log.Println(err)
continue
}
node.WriteMessage(1, out)
}
}
}
}(sub, c)
return nil
}