punch_server.go 8.95 KB
Newer Older
Jason Fong's avatar
Jason Fong committed
1
2
3
package main

import (
4
	"bytes"
Jason Fong's avatar
Jason Fong committed
5
	"encoding/binary"
6
7
8
	"errors"
	"io"
	"math/rand"
Jason Fong's avatar
Jason Fong committed
9
	"net"
10
	"os"
Jason Fong's avatar
Jason Fong committed
11
	"sync"
12
13
14
	"time"

	log "github.com/sirupsen/logrus"
Jason Fong's avatar
Jason Fong committed
15
16
)

17
18
19
20
21
22
23
24
25
26
27
28
type PeerInfo struct {
	IP      [16]byte
	Port    uint16
	NatType uint16
	Meta    string
	ID      uint32
}

type natInfo struct {
	IP      [16]byte
	Port    uint16
	NatType uint16
Jason Fong's avatar
Jason Fong committed
29
30
31
}

const (
32
33
34
35
36
37
38
39
40
41
42
	_ = iota
	Enroll
	GetPeerInfo
	NotifyPeer
	GetPeerInfoFromMeta
	NotifyPeerFromMeta

	PeerOffline = 1
	PeerError   = 2

	ListeningPort = ":9988"
Jason Fong's avatar
Jason Fong committed
43
44
)

45
46
47
48
49
50
51
52
53
54
55
var (
	seq              uint32 = 1
	peers            map[uint32]PeerInfo
	peersFromMeta    map[string]PeerInfo
	peerConn         map[uint32]net.Conn
	peerConnFromMeta map[string]net.Conn
	mutex            sync.RWMutex
	letterRunes      = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	ErrPeerNotFound  = errors.New("Peer not found")
	ErrConnNotFound  = errors.New("Connection not found, peer maybe is now offline")
)
Jason Fong's avatar
Jason Fong committed
56

57
58
59
60
61
62
func init() {
	peers = make(map[uint32]PeerInfo)
	peersFromMeta = make(map[string]PeerInfo)
	peerConn = make(map[uint32]net.Conn)
	peerConnFromMeta = make(map[string]net.Conn)
	rand.Seed(time.Now().UnixNano())
Jason Fong's avatar
Jason Fong committed
63

64
65
66
	log.SetOutput(os.Stdout)
	log.SetLevel(log.DebugLevel)
}
Jason Fong's avatar
Jason Fong committed
67

68
69
70
71
72
73
74
func main() {
	l, err := net.Listen("tcp", ListeningPort)
	if err != nil {
		log.WithFields(log.Fields{
			"err": err,
		}).Fatal("Unable to start server")
	}
Jason Fong's avatar
Jason Fong committed
75
	defer l.Close()
76
	go dumpPeers()
Jason Fong's avatar
Jason Fong committed
77
78
79
	for {
		conn, err := l.Accept()
		if err != nil {
80
81
82
			log.WithFields(log.Fields{
				"err": err,
			}).Error("Accepting connection failed")
Jason Fong's avatar
Jason Fong committed
83
84
			continue
		}
85
		log.Info("New connection received")
Jason Fong's avatar
Jason Fong committed
86
87
88
89
		go handleConn(conn)
	}
}

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
func dumpPeers() {
	for {
		time.Sleep(10 * time.Second)
		mutex.RLock()
		for k, v := range peers {
			log.WithFields(log.Fields{
				"Key":     k,
				"ID":      v.ID,
				"Meta":    v.Meta,
				"IP":      string(v.IP[:]),
				"Port":    v.Port,
				"NatType": v.NatType,
			}).Debug("peer info")
		}
		mutex.RUnlock()
	}
}

func RandStringRunes(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

func readMeta(c io.Reader) (meta string, err error) {
	var metaSize uint8
	err = binary.Read(c, binary.BigEndian, &metaSize)
	if err != nil || metaSize == 0 {
		log.WithFields(log.Fields{
			"err":      err,
			"metaSize": metaSize,
		}).Info("reading meta failed")
		return
	}
	data := make([]byte, metaSize)
	if _, err = c.Read(data); err != nil {
		log.WithFields(log.Fields{
			"err": err,
		}).Info("reading meta failed")
		return
	}
	meta = string(data)
	return
}

func writeMeta(c io.Writer, meta string) (err error) {
	err = binary.Write(c, binary.BigEndian, uint8(len(meta)))
	if err != nil {
		return
	}
	return binary.Write(c, binary.BigEndian, []byte(meta))
}

func readPeerInfo(r io.Reader) (p PeerInfo, err error) {
	var IP [16]byte
	var Port uint16
	var NatType uint16
	if err = binary.Read(r, binary.BigEndian, &IP); err != nil {
		return
	}
	if err = binary.Read(r, binary.BigEndian, &Port); err != nil {
		return
	}
	if err = binary.Read(r, binary.BigEndian, &NatType); err != nil {
		return
	}
	p = PeerInfo{
		IP:      IP,
		Port:    Port,
		NatType: NatType,
	}

	meta, err := readMeta(r)
	if err != nil {
		log.WithFields(log.Fields{
			"err": err,
		}).Warn("reading meta failed")
		meta = RandStringRunes(18)
	}
	p.Meta = meta
	log.WithFields(log.Fields{
		"meta": meta,
	}).Info("reading meta succeeded")
	return
}

func writePeerInfo(w io.Writer, p PeerInfo) (err error) {
	p1 := natInfo{
		IP:      p.IP,
		Port:    p.Port,
		NatType: p.NatType,
	}
	var buf bytes.Buffer
	if err = binary.Write(&buf, binary.BigEndian, p.ID); err != nil {
		return
	}
	if err = binary.Write(&buf, binary.BigEndian, p1); err != nil {
		return
	}
	if err = writeMeta(&buf, p.Meta); err != nil {
		return
	}
	return binary.Write(w, binary.BigEndian, (&buf).Bytes())
}

func getPeerInfo(p PeerInfo) (p1 PeerInfo, err error) {
	var ok bool
	mutex.RLock()
	defer mutex.RUnlock()
	if p.ID != 0 {
		if p1, ok = peers[p.ID]; ok {
			return
		}
	}
	if p.Meta != "" {
		if p1, ok = peersFromMeta[p.Meta]; ok {
			return
		}
	}
	err = ErrPeerNotFound
	return
}

func getConn(p PeerInfo) (c net.Conn, err error) {
	var ok bool
	mutex.RLock()
	defer mutex.RUnlock()
	if p.ID != 0 {
		if c, ok = peerConn[p.ID]; ok {
			return
		}
	}
	if p.Meta != "" {
		if c, ok = peerConnFromMeta[p.Meta]; ok {
			return
		}
	}
	err = ErrConnNotFound
	return
}

Jason Fong's avatar
Jason Fong committed
233
234
235
// 2 bytes for message type
func handleConn(c net.Conn) {
	defer c.Close()
236
237
	log.Info("new connection received!")
	var myInfo PeerInfo
Jason Fong's avatar
Jason Fong committed
238
	for {
239
240
		var myBuf bytes.Buffer
		w := io.MultiWriter(&myBuf, c)
Jason Fong's avatar
Jason Fong committed
241
242
		data := make([]byte, 2)
		_, err := c.Read(data)
243
244
245
		log.WithFields(log.Fields{
			"header": data,
		}).Info("new received header")
Jason Fong's avatar
Jason Fong committed
246
		if err != nil {
247
248
249
250
251
252
253
254
255
256
			mutex.Lock()
			delete(peers, myInfo.ID)
			delete(peerConn, myInfo.ID)
			delete(peersFromMeta, myInfo.Meta)
			delete(peerConnFromMeta, myInfo.Meta)
			mutex.Unlock()
			log.WithFields(log.Fields{
				"err":  err,
				"myID": myInfo.ID,
			}).Info("peer left")
Jason Fong's avatar
Jason Fong committed
257
258
			return
		}
259
260
		t := binary.BigEndian.Uint16(data[:])
		switch t {
Jason Fong's avatar
Jason Fong committed
261
		case Enroll:
262
263
			var err error
			myInfo, err = readPeerInfo(c)
Jason Fong's avatar
Jason Fong committed
264
			if err != nil {
265
266
267
268
				log.WithFields(log.Fields{
					"err": err,
				}).Warn("Reading meta failed")
				break
Jason Fong's avatar
Jason Fong committed
269
			}
270
			mutex.Lock()
Jason Fong's avatar
Jason Fong committed
271
			seq++
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
			myInfo.ID = seq
			peers[myInfo.ID] = myInfo
			peerConn[myInfo.ID] = c
			if myInfo.Meta != "" {
				peersFromMeta[myInfo.Meta] = myInfo
				peerConnFromMeta[myInfo.Meta] = c
			}
			mutex.Unlock()
			log.WithFields(log.Fields{
				"ID":      myInfo.ID,
				"Meta":    myInfo.Meta,
				"IP":      string(myInfo.IP[:]),
				"Port":    myInfo.Port,
				"NatType": myInfo.NatType,
			}).Debug("New peer enrolled")
			err = binary.Write(w, binary.BigEndian, myInfo.ID)
Fong's avatar
Fong committed
288
			if err != nil {
289
290
291
292
293
294
295
296
297
				log.WithFields(log.Fields{
					"err":     err,
					"ID":      myInfo.ID,
					"Meta":    myInfo.Meta,
					"IP":      string(myInfo.IP[:]),
					"Port":    myInfo.Port,
					"NatType": myInfo.NatType,
				}).Warn("Unable to return my peer info")
				break
Fong's avatar
Fong committed
298
			}
Jason Fong's avatar
Jason Fong committed
299
		case GetPeerInfo:
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
			var peerID uint32
			err = binary.Read(c, binary.BigEndian, &peerID)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to get peer id")
				binary.Write(c, binary.BigEndian, PeerOffline)
				break
			}
			peer, err := getPeerInfo(PeerInfo{ID: peerID})
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to get peer info")
				break
			}
			err = writePeerInfo(w, peer)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to write peer info")
				break
Jason Fong's avatar
Jason Fong committed
328
329
			}
		case NotifyPeer:
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
			var peerID uint32
			err = binary.Read(c, binary.BigEndian, &peerID)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to get peer id")
				break
			}
			conn, err := getConn(PeerInfo{ID: peerID})
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to get peer conn")
				binary.Write(c, binary.BigEndian, PeerOffline)
				break
			}
			err = writePeerInfo(conn, myInfo)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"peerID": peerID,
					"myID":   myInfo.ID,
				}).Warn("Unable to write my peer info to peer connection")
				break
			}
		case GetPeerInfoFromMeta:
			peerMeta, err := readMeta(c)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"myMeta": myInfo.Meta,
				}).Warn("Unable to get peer meta")
				break
			}
			peer, err := getPeerInfo(PeerInfo{Meta: peerMeta})
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"meta":   peerMeta,
					"myMeta": myInfo.Meta,
				}).Warn("Unable to get peer info")
				break
			}
			err = writePeerInfo(w, peer)
			if err != nil {
				log.WithFields(log.Fields{
					"err":      err,
					"peerMeta": peer.Meta,
					"myMeta":   myInfo.Meta,
				}).Warn("Unable to write peer info")
				break
			}
		case NotifyPeerFromMeta:
			peerMeta, err := readMeta(c)
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"myMeta": myInfo.Meta,
				}).Warn("Unable to get peer id")
				break
			}
			conn, err := getConn(PeerInfo{Meta: peerMeta})
			if err != nil {
				log.WithFields(log.Fields{
					"err":    err,
					"meta":   peerMeta,
					"myMeta": myInfo.Meta,
				}).Warn("Unable to get peer conn")
				binary.Write(c, binary.BigEndian, PeerOffline)
				break
			}
			err = writePeerInfo(conn, myInfo)
			if err != nil {
				log.WithFields(log.Fields{
					"err":      err,
					"peerMeta": peerMeta,
					"myMeta":   myInfo.Meta,
				}).Warn("Unable to write my peer to peer connection")
				break
Jason Fong's avatar
Jason Fong committed
413
414
			}
		default:
415
416
417
			log.WithFields(log.Fields{
				"type": t,
			}).Warn("Illegal message")
Jason Fong's avatar
Jason Fong committed
418
		}
419
420
421
		log.WithFields(log.Fields{
			"response": (&myBuf).Bytes(),
		}).Debug("Response sent")
Jason Fong's avatar
Jason Fong committed
422
423
424
425
	}

	return
}