-
Notifications
You must be signed in to change notification settings - Fork 0
/
newProjet.go
863 lines (695 loc) · 22.6 KB
/
newProjet.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
288
289
290
291
292
293
294
295
296
297
298
299
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
328
329
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"net"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
)
type udpAddrJson struct {
Ip string `json:"ip"`
Port int64 `json:"port"`
}
type peerInfoJson struct {
Name string `json:"name"`
Addresses []udpAddrJson `json:"addresses"`
Key string `json:"key"`
}
type nameAndKeyJson struct {
Name string `json:"name"`
Key string `json:"key"`
}
type Node struct {
// typeNode int
hash [32]byte
sons []*Node
leaf bool
content []byte
}
func main() {
sizeMsg := 1128
datagram := make([]byte, sizeMsg)
flag := make([]byte, 4)
username := "com3"
usernameByte := []byte(username)
id := []byte{34, 122, 76, 97}
//idUnSigned := []byte{0, 0, 0, 0}
IPv4Port := 8777
IPv6Port := 7888
sockIpv4, myIPv4Addr := listenUDPIPv4(IPv4Port)
sockIpv6, myIPv6Addr := listenUDPIPv6(IPv6Port)
channel := make(chan []byte)
myMsgNumber := 33
if myIPv4Addr.IP == nil && myIPv6Addr.IP == nil {
fmt.Println("No IPv4 and IPv6 address available on your machine")
os.Exit(1)
}
// build merkel tree
myMessagesByte := getMyMessages(myMsgNumber)
leaves := getMerkleLeaves(myMessagesByte)
rootMerkel := buildMerkleTree(leaves)
// // that's how to append a message to Merkle tree
// messageToAppend := getMyMessage(34)
// myMessagesByte = append(myMessagesByte, messageToAppend)
// leaves = getMerkleLeaves(myMessagesByte)
// rootMerkel = buildMerkleTree(leaves)
client := getClient()
_, privateKey, keyBase64 := loadPublicAndPrivateKeys()
registerInServer(username, keyBase64, client)
udpServerAddresses := getUDPAddrArray(getUdpServerAddrs(client))
// Reply to every received request from any peer
go replyAllPeers(usernameByte, flag, sizeMsg, privateKey, rootMerkel, sockIpv4, channel)
go replyAllPeers(usernameByte, flag, sizeMsg, privateKey, rootMerkel, sockIpv6, channel)
// Say hello to server in IPv4 and IPv6
datagram = buildDatagram(id, 0, flag, usernameByte, nil, nil, sizeMsg, privateKey)
sayHelloToPeer(datagram, udpServerAddresses, sockIpv4, myIPv4Addr, sockIpv6, myIPv6Addr, channel)
// choose a peer
peerUdpAddresses := getPeerAddresses(client)
// say hello to peer in IPv4 and IPv6
datagram = buildDatagram(id, 0, flag, usernameByte, nil, nil, sizeMsg, privateKey)
sayHelloToPeer(datagram, peerUdpAddresses, sockIpv4, myIPv4Addr, sockIpv6, myIPv6Addr, channel)
// RootRequest peer
datagram = buildDatagram(id, 1, nil, nil, nil, nil, sizeMsg, nil)
datagram = rootRequestToPeer(datagram, peerUdpAddresses, sockIpv4, myIPv4Addr, sockIpv6, myIPv6Addr, channel)
// send Datum
rootPeerHash := datagram[7:39]
rootMerkelPeer := new(Node)
// var rootPeerMercle *Node
getMerkleMsgsFromPeer(rootMerkelPeer, peerUdpAddresses[0], sockIpv4, rootPeerHash, id, sizeMsg, channel)
for {
datagram = buildDatagram(id, 1, nil, nil, nil, nil, sizeMsg, nil)
datagram = rootRequestToPeer(datagram, peerUdpAddresses, sockIpv4, myIPv4Addr, sockIpv6, myIPv6Addr, channel)
newRootPeer := datagram[7:39]
if !reflect.DeepEqual(rootPeerHash[:], newRootPeer) {
getMerkleMsgsFromPeer(rootMerkelPeer, peerUdpAddresses[0], sockIpv4, newRootPeer, id, sizeMsg, channel)
rootPeerHash = newRootPeer
}
}
// NAT
}
func getMerkleMsgsFromPeer(node *Node, peerAddress net.UDPAddr, sock *net.UDPConn, hash []byte, id []byte, sizeMsg int, channel chan []byte) {
exponent := 0
datagram := buildDatagram(id, 2, nil, nil, hash, nil, sizeMsg, nil)
for (datagram[4] != 130 || !reflect.DeepEqual(datagram[0:len(id)], id)) &&
(datagram[4] != 131 || !reflect.DeepEqual(datagram[0:len(id)], id)) {
datagram = buildDatagram(id, 2, nil, nil, hash, nil, sizeMsg, nil)
deadLineTime := math.Pow(2, float64(exponent))
exponent += 1
if deadLineTime > 64 {
fmt.Println("Timeout : Peer not responding")
os.Exit(1)
}
if datagram[4] == 254 {
length := int(datagram[5])<<8 | int(datagram[6])
fmt.Println("getMerkleMsgsFromPeer error >> ", string(datagram[7:7+length]))
}
if (datagram[4] != 130 || !reflect.DeepEqual(datagram[0:len(id)], id)) &&
(datagram[4] != 130 || !reflect.DeepEqual(datagram[0:len(id)], id)) {
_, err := sock.WriteToUDP(datagram, &peerAddress)
if err != nil {
log.Fatal("sockIpv4.WriteToUDP >> ", err)
}
}
sock.SetReadDeadline(time.Now().Add(time.Duration(int(deadLineTime)) * time.Second))
datagram = <-channel
sock.SetReadDeadline(time.Time{})
}
// verify hash is correct
length := int(datagram[5])<<8 | int(datagram[6])
calculatedHash := sha256.Sum256(datagram[7+32 : length+7])
if !reflect.DeepEqual(datagram[7:7+32], calculatedHash[:]) && datagram[4] != 131 {
log.Println("Received wrong hash value from peer")
os.Exit(1)
}
if datagram[4] == 130 && datagram[39] == 0 {
if node.hash == new(Node).hash {
var hashCorr [32]byte
content := datagram[39 : length+7]
copy(hashCorr[:], hash)
node.hash = hashCorr
node.content = content
node.leaf = true
lengthMsg := int(datagram[76])<<8 | int(datagram[77])
msg := datagram[78 : 78+lengthMsg]
timestamp := int64(datagram[40])<<24 | int64(datagram[41])<<16 | int64(datagram[42])<<8 | int64(datagram[43])
publishDate := time.Unix(timestamp, 0)
fmt.Println(string(msg))
fmt.Println("\tPublished in : ", publishDate)
fmt.Println("\tReplies to ", datagram[44:44+32])
} else if !reflect.DeepEqual(node.hash[:], hash) {
var hashCorr [32]byte
copy(hashCorr[:], hash)
node.hash = hashCorr
node.content = datagram[39 : length+7]
node.leaf = true
lengthMsg := int(datagram[76])<<8 | int(datagram[77])
msg := datagram[78 : 78+lengthMsg]
timestamp := int64(datagram[40])<<24 | int64(datagram[41])<<16 | int64(datagram[42])<<8 | int64(datagram[43])
publishDate := time.Unix(timestamp, 0)
fmt.Println(string(msg))
fmt.Println("\tPublished in : ", publishDate)
fmt.Println("\tReplies to ", datagram[44:44+32])
}
return
}
if datagram[4] == 131 {
fmt.Println("No Datum")
return
}
if datagram[4] == 130 && datagram[39] != 0 && datagram[39] != 1 {
return
}
if datagram[4] == 130 && datagram[39] == 1 {
length := int(datagram[5])<<8 | int(datagram[6])
numberOfHashNodes := len(datagram[40:length+7]) / 32
if node.hash == new(Node).hash {
var hashCorr [32]byte
copy(hashCorr[:], hash)
s := make([]*Node, numberOfHashNodes)
for i := range s {
s[i] = new(Node)
}
node.hash = hashCorr
node.content = datagram[39 : length+7]
node.leaf = false
node.sons = s
i := 0
for i < numberOfHashNodes {
getMerkleMsgsFromPeer(node.sons[i], peerAddress, sock, datagram[40+i*32:40+i*32+32], id, sizeMsg, channel)
i += 1
}
} else if !reflect.DeepEqual(node.hash[:], hash) {
var hashCorr [32]byte
copy(hashCorr[:], hash)
node.content = datagram[39 : length+7]
node.hash = hashCorr
node.leaf = false
if len(node.sons) < numberOfHashNodes {
s := make([]*Node, numberOfHashNodes-len(node.sons))
for i := range s {
s[i] = new(Node)
}
node.sons = append(node.sons, s...)
}
i := 0
for i < numberOfHashNodes {
if !reflect.DeepEqual(node.sons[i].hash[:], datagram[40+i*32:40+i*32+32]) {
getMerkleMsgsFromPeer(node.sons[i], peerAddress, sock, datagram[40+i*32:40+i*32+32], id, sizeMsg, channel)
}
i += 1
}
}
}
}
func buildMerkleTree(nodesDownLevel []*Node) *Node {
var nodeUpLevel []*Node
if len(nodesDownLevel) < 1 {
fmt.Println("Cannot create merkle tree of empty nodes")
return nil
}
if len(nodesDownLevel) == 1 {
return nodesDownLevel[0]
}
for i := 0; i < len(nodesDownLevel); i += 32 {
chash := []byte{1}
lastMember := 0
for j := i; j < i+32 && j < len(nodesDownLevel); j++ {
chash = append(chash, nodesDownLevel[j].hash[:]...)
lastMember = j
}
nodeNew := &Node{
hash: sha256.Sum256(chash),
sons: nodesDownLevel[i : lastMember+1],
content: chash,
leaf: false,
}
nodeUpLevel = append(nodeUpLevel, nodeNew)
if len(nodesDownLevel) <= 32 {
return nodeNew
}
if len(nodesDownLevel[lastMember+1:]) < 32 {
nodeUpLevel = append(nodeUpLevel, nodesDownLevel[lastMember+1:]...)
break
}
}
return buildMerkleTree(nodeUpLevel)
}
func getMerkleSons(node *Node, hash [32]byte) []byte {
if reflect.DeepEqual(node.hash, hash) {
return node.content
} else {
for j := 0; j < len(node.sons); j++ {
content := getMerkleSons(node.sons[j], hash)
if content != nil {
return content
}
}
}
return nil
}
func getMerkleLeaves(datagrams [][]byte) []*Node {
var leaves []*Node
for _, v := range datagrams {
node := &Node{
hash: sha256.Sum256(v),
leaf: true,
content: v,
}
leaves = append(leaves, node)
}
return leaves
}
func getRequest(client *http.Client, url string) []byte {
req, err := http.NewRequest("GET", url, nil)
checkError(err)
response, err := client.Do(req)
checkError(err)
body, err := ioutil.ReadAll(response.Body)
checkError(err)
return body
}
func replyAllPeers(usernameByte []byte, flag []byte, sizeMsg int, privateKey *ecdsa.PrivateKey, rootMerkel *Node, sock *net.UDPConn, channel chan []byte) {
if sock == nil {
return
}
for {
receivedDatagram := make([]byte, sizeMsg)
n, peerUdpAddress, err := sock.ReadFromUDP(receivedDatagram)
if err != nil {
log.Println("ERROR replyAllPeers func >> ", err)
}
sock.SetReadDeadline(time.Time{})
if receivedDatagram[4] == 128 {
channel <- receivedDatagram
}
if receivedDatagram[4] == 129 {
channel <- receivedDatagram
}
if receivedDatagram[4] == 130 || receivedDatagram[4] == 131 {
channel <- receivedDatagram
}
if n == 0 || receivedDatagram[4] == 254 {
channel <- receivedDatagram
}
if n != 0 && receivedDatagram[4] == 0 {
id := receivedDatagram[0:3]
receivedDatagram = buildDatagram(id, 128, flag, usernameByte, nil, nil, sizeMsg, privateKey)
_, err = sock.WriteToUDP(receivedDatagram, peerUdpAddress)
checkError(err)
}
if n != 0 && receivedDatagram[4] == 1 {
id := receivedDatagram[0:3]
receivedDatagram = buildDatagram(id, 129, nil, nil, rootMerkel.hash[:], nil, sizeMsg, nil)
_, err = sock.WriteToUDP(receivedDatagram, peerUdpAddress)
checkError(err)
}
if n != 0 && receivedDatagram[4] == 2 {
var requestedHash [32]byte
id := receivedDatagram[0:3]
copy(requestedHash[:], receivedDatagram[7:7+32])
nodeContent := getMerkleSons(rootMerkel, requestedHash)
if nodeContent == nil {
receivedDatagram = buildDatagram(id, 131, nil, nil, requestedHash[:], nil, sizeMsg, nil)
_, err = sock.WriteToUDP(receivedDatagram, peerUdpAddress)
checkError(err)
} else {
receivedDatagram = buildDatagram(id, 130, nil, nil, requestedHash[:], nodeContent, sizeMsg, nil)
_, err = sock.WriteToUDP(receivedDatagram, peerUdpAddress)
checkError(err)
}
}
}
}
func sayHelloToPeer(datagram []byte, peerUDPAddresses []net.UDPAddr, sockIpv4 *net.UDPConn, myIPv4Addr net.UDPAddr, sockIpv6 *net.UDPConn, myIPv6Addr net.UDPAddr, channel chan []byte) {
var helloMsg []byte
copy(helloMsg[:], datagram[:])
// IPv4
if myIPv4Addr.IP != nil {
for _, v := range peerUDPAddresses {
if v.IP.To4() != nil {
sayHello(datagram, datagram[0:4], sockIpv4, v, channel)
}
}
}
// IPV6
if myIPv6Addr.IP != nil {
copy(datagram[:], helloMsg[:])
for _, v := range peerUDPAddresses {
if v.IP.To16() != nil {
sayHello(datagram, datagram[0:4], sockIpv6, v, channel)
}
}
}
}
func sayHello(helloMsg []byte, id []byte, sock *net.UDPConn, udpAddress net.UDPAddr, channel chan []byte) {
exponent := 0
helloReplyMsg := helloMsg
for helloReplyMsg[4] != 128 || !reflect.DeepEqual(helloReplyMsg[0:len(id)], id) {
deadLineTime := math.Pow(2, float64(exponent))
exponent += 1
if deadLineTime > 64 {
fmt.Println("Timeout : No HelloReply Recieved, Server not responding")
os.Exit(1)
}
if helloReplyMsg[4] == 254 {
length := int(helloReplyMsg[5])<<8 | int(helloReplyMsg[6])
fmt.Println("sayHello error >> ", string(helloMsg[7:7+length]))
}
if helloReplyMsg[4] != 128 || !reflect.DeepEqual(helloReplyMsg[0:len(id)], id) {
_, err := sock.WriteToUDP(helloMsg, &udpAddress)
checkError(err)
}
sock.SetReadDeadline(time.Now().Add(time.Duration(int(deadLineTime)) * time.Second))
helloReplyMsg = <-channel
sock.SetReadDeadline(time.Time{})
}
}
func rootRequestToPeer(datagram []byte, peerUDPAddresses []net.UDPAddr, sockIpv4 *net.UDPConn, myIPv4Addr net.UDPAddr, sockIpv6 *net.UDPConn, myIPv6Addr net.UDPAddr, channel chan []byte) []byte {
var rootRequestMsg []byte
copy(rootRequestMsg[:], datagram[:])
// IPv4
if myIPv4Addr.IP != nil {
for _, v := range peerUDPAddresses {
if v.IP.To4() != nil {
datagram = rootRequest(datagram, datagram[0:4], sockIpv4, v, channel)
}
}
}
// IPV6
if myIPv6Addr.IP != nil {
copy(datagram[:], rootRequestMsg[:])
for _, v := range peerUDPAddresses {
if v.IP.To16() != nil {
datagram = rootRequest(datagram, datagram[0:4], sockIpv6, v, channel)
}
}
}
return datagram
}
func rootRequest(rootRequestMsg []byte, id []byte, sock *net.UDPConn, udpAddress net.UDPAddr, channel chan []byte) []byte {
exponent := 0
rootReplyMsg := rootRequestMsg
for rootReplyMsg[4] != 129 || !reflect.DeepEqual(rootReplyMsg[0:len(id)], id) {
deadLineTime := math.Pow(2, float64(exponent))
exponent += 1
if deadLineTime > 64 {
fmt.Println("Timeout : No Response from peer about Root Request")
os.Exit(1)
}
if rootReplyMsg[4] == 254 {
length := int(rootReplyMsg[5])<<8 | int(rootReplyMsg[6])
fmt.Println("rootRequest error >> ", string(rootReplyMsg[7:7+length]))
}
if rootReplyMsg[4] != 129 || !reflect.DeepEqual(rootReplyMsg[0:len(id)], id) {
_, err := sock.WriteToUDP(rootRequestMsg, &udpAddress)
checkError(err)
}
sock.SetReadDeadline(time.Now().Add(time.Duration(deadLineTime) * time.Second))
rootReplyMsg = <-channel
sock.SetReadDeadline(time.Time{})
}
return rootReplyMsg
}
func buildDatagram(id []byte, typeMsg int, flag []byte, usernameByte []byte, hash []byte, value []byte, sizeMsg int, privateKey *ecdsa.PrivateKey) []byte {
switch typeMsg {
case 0, 128: // hello or helloReply
datagram := make([]byte, sizeMsg)
length := 5 + len(usernameByte)
copy(datagram[0:len(id)], id)
datagram[4] = byte(typeMsg)
copy(datagram[5:7], []byte{byte(length >> 8), byte(length - (length>>8)<<8)})
copy(datagram[7:11], flag)
datagram[11] = byte(len(usernameByte))
copy(datagram[12:12+len(usernameByte)], usernameByte)
signature := getMsgSignature(datagram, privateKey)
copy(datagram[7+length:], signature)
datagram = datagram[:64+7+length]
return datagram
case 1: // RootRequest message
datagram := make([]byte, sizeMsg)
copy(datagram[0:len(id)], id)
datagram[4] = byte(typeMsg)
return datagram
case 2, 129, 131: // GetDatum type message OR RootReply OR NoDatum
datagram := make([]byte, sizeMsg)
copy(datagram[0:len(id)], id)
datagram[4] = byte(typeMsg)
datagram[6] = 32
copy(datagram[7:39], hash)
return datagram
case 130: // Datum
datagram := make([]byte, sizeMsg)
copy(datagram[0:len(id)], id)
datagram[4] = byte(typeMsg)
length := 32 + len(value)
copy(datagram[5:7], []byte{byte(length >> 8), byte(length - (length>>8)<<8)})
copy(datagram[7:7+32], hash)
copy(datagram[7+32:], value)
return datagram
}
return nil
}
func getUDPAddrArray(udpAddrs []udpAddrJson) []net.UDPAddr {
udpAddresses := make([]net.UDPAddr, 0)
var udpAddress net.UDPAddr
i := 0
for i < len(udpAddrs) {
udpAddress.Port = int(udpAddrs[i].Port)
udpAddress.IP = net.ParseIP(udpAddrs[i].Ip)
udpAddresses = append(udpAddresses, udpAddress)
i += 1
}
return udpAddresses
}
func getLocalIPv4() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Println(err)
return nil
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func getLocalIPv6() net.IP {
conn, err := net.Dial("udp6", "[2001:4860:4860:0:0:0:0:8888]:53")
if err != nil {
log.Println(err)
return nil
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func getUdpServerAddrs(client *http.Client) []udpAddrJson {
body := getRequest(client, "https://jch.irif.fr:8443/udp-address")
var serverUdpAddrsJson []udpAddrJson
if err := json.Unmarshal(body, &serverUdpAddrsJson); err != nil {
log.Fatal(err)
}
return serverUdpAddrsJson
}
func registerInServer(name string, keyBase64 string, client *http.Client) {
nameAndKey := nameAndKeyJson{
Name: name,
Key: keyBase64,
}
body, _ := json.Marshal(nameAndKey)
req, err := http.NewRequest("POST", "https://jch.irif.fr:8443/register", bytes.NewBuffer(body))
checkError(err)
res, err := client.Do(req)
checkError(err)
if res.StatusCode == 204 {
fmt.Printf("Server HelloReply %c \n\n", 0x1F64B)
}
if res.StatusCode == 400 {
fmt.Printf("Server already replied you %c \n\n", 0x1F612)
}
}
func getClient() *http.Client {
transport := &*http.DefaultTransport.(*http.Transport)
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{
Transport: transport,
Timeout: 50 * time.Second,
}
return client
}
func getMsgSignature(datagram []byte, privateKey *ecdsa.PrivateKey) []byte {
if privateKey != nil {
signature := make([]byte, 64)
length := int(datagram[5])<<8 | int(datagram[6])
hashed := sha256.Sum256(datagram[0 : 7+length])
r, s, err := ecdsa.Sign(rand.Reader, privateKey, hashed[:])
checkError(err)
r.FillBytes(signature[:32])
s.FillBytes(signature[32:])
return signature
}
return nil
}
func verifiySignature(datagram []byte, publicKey *ecdsa.PublicKey) bool {
var r, s big.Int
length := int(datagram[5])<<8 | int(datagram[6])
signature := datagram[7+length:]
r.SetBytes(signature[:32])
s.SetBytes(signature[32:])
hashed := sha256.Sum256(datagram[0 : 7+length])
ok := ecdsa.Verify(publicKey, hashed[:], &r, &s)
return ok
}
func listenUDPIPv6(IPv6Port int) (*net.UDPConn, net.UDPAddr) {
myIPv6Addr := net.UDPAddr{
Port: IPv6Port,
IP: getLocalIPv6(),
}
sockIpv6, err := net.ListenUDP("udp6", &myIPv6Addr)
checkError(err)
if myIPv6Addr.IP == nil {
fmt.Print("No IPv6 address available in your machine \n\n")
sockIpv6.Close()
sockIpv6 = nil
}
return sockIpv6, myIPv6Addr
}
func listenUDPIPv4(IPv4Port int) (*net.UDPConn, net.UDPAddr) {
myIPv4Addr := net.UDPAddr{
Port: IPv4Port,
IP: getLocalIPv4(),
}
sockIpv4, err := net.ListenUDP("udp", &myIPv4Addr)
checkError(err)
if myIPv4Addr.IP == nil {
fmt.Println("No IPv4 address available in your machine")
sockIpv4.Close()
sockIpv4 = nil
}
return sockIpv4, myIPv4Addr
}
func getMyMessages(myMsgNumber int) [][]byte {
var myMessagesByte [][]byte
for i := 1; i <= myMsgNumber; i++ {
myMessageByte := getMyMessage(i)
myMessagesByte = append(myMessagesByte, myMessageByte[:])
}
return myMessagesByte
}
func getMyMessage(i int) []byte {
var msg string
var myMessageByte [1024]byte
msg = "My message number " + strconv.Itoa(i)
myMessageByte = getFormatedMsg(myMessageByte, 0, time.Now().Unix(), nil, []byte(msg))
return myMessageByte[:]
}
func getFormatedMsg(myMessageByte [1024]byte, typeMsg byte, date int64, inReplyTo []byte, body []byte) [1024]byte {
myMessageByte[0] = typeMsg
dateByte := []byte{byte(date >> 24), byte(date>>16 - (date>>24)<<8), byte(date>>8 - (date>>16)<<8), byte(date - (date>>24)<<8)}
copy(myMessageByte[1:5], dateByte)
length := len(body)
copy(myMessageByte[37:39], []byte{byte(length >> 8), byte(length - (length>>8)<<8)})
copy(myMessageByte[39:], body)
return myMessageByte
}
func getPeerAddresses(client *http.Client) []net.UDPAddr {
body := getRequest(client, "https://jch.irif.fr:8443/peers")
peersArray := strings.Split(string(body), "\n")
peersArray = peersArray[:len(peersArray)-1]
for i, p := range peersArray {
fmt.Println(i+1, "- ", p)
}
var choosedPeer int
fmt.Println("\nChoose a peer to connect with")
fmt.Scanln(&choosedPeer)
body = getRequest(client, "https://jch.irif.fr:8443/peers/"+peersArray[choosedPeer-1])
var peerInfo peerInfoJson
if err := json.Unmarshal(body, &peerInfo); err != nil {
log.Fatal(err)
}
peerUdpAddresses := getUDPAddrArray(peerInfo.Addresses)
return peerUdpAddresses
}
func generatePublicAndPrivateKeys() (*ecdsa.PublicKey, *ecdsa.PrivateKey, string) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
checkError(err)
publicKey, ok := privateKey.Public().(*ecdsa.PublicKey)
checkOk(ok)
// Je convertis la cle privee en String
x509Encoded, _ := x509.MarshalECPrivateKey(privateKey)
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
stringPrivateKey := string(pemEncoded)
// Je formate la cle publique en 64 octets et je la converstis en String
formatted := make([]byte, 64)
publicKey.X.FillBytes(formatted[:32])
publicKey.Y.FillBytes(formatted[32:])
publicKeystring := base64.RawStdEncoding.EncodeToString(formatted)
// Création d'un fichier sur disque pour conserver la clé publique
f1, err := os.Create("public_key.txt")
checkError(err)
defer f1.Close()
_, err = f1.WriteString(publicKeystring)
checkError(err)
fmt.Println("Key saved to the public key file")
// Création d'un fichier sur disque pour conserver la clé privée
f2, err := os.Create("private_key.txt")
checkError(err)
defer f2.Close()
_, err = f2.WriteString(stringPrivateKey)
checkError(err)
fmt.Println("Key saved to the private key file")
// Je retourne les cles publique et privee + le string de la clé publique en 64 bits.
return publicKey, privateKey, publicKeystring
}
func loadPublicAndPrivateKeys() (*ecdsa.PublicKey, *ecdsa.PrivateKey, string) {
// Je lie les clés publique et privee depuis leurs fichiers
content1, err := os.ReadFile("public_key.txt")
content2, err := os.ReadFile("private_key.txt")
// En cas d'erreur d'erreur, je regénère de nouvelles clés
if err != nil {
return generatePublicAndPrivateKeys()
}
checkError(err)
// J'obtiens les clés sous forme de String
publicKeyString := string(content1)
privateKeyString := string(content2)
// Je décode la clé privée
block, _ := pem.Decode([]byte(privateKeyString))
x509Encoded := block.Bytes
privateKey, _ := x509.ParseECPrivateKey(x509Encoded)
// Le décodage de la clé publique est spécial car elle est codée sur 64 bits
var x, y big.Int
x.SetBytes([]byte(publicKeyString[:32]))
y.SetBytes([]byte(publicKeyString[32:]))
publicKey := ecdsa.PublicKey{
Curve: elliptic.P256(),
X: &x,
Y: &y,
}
return &publicKey, privateKey, publicKeyString
}
func checkError(err error) {
if err != nil {
log.Fatalln("Fatal error ", err.Error())
}
}
func checkOk(ok bool) {
if !ok {
log.Fatalln("Failed to create the public key")
}
}