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
|
package main
import (
"crypto/ed25519"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"net/http"
"sort"
"strings"
"sync"
)
type user struct {
pubkey []byte
}
var mu sync.Mutex
var me string
var myHash string
var myPos int
var hashToDomain map[string]string
var peerHashes []string
var kvstore map[string]string
// Get the sha256sum of string as a hex string
func sha256sum(s string) string {
b := sha256.Sum256([]byte(s))
return hex.EncodeToString(b[:])
}
// Try to peer with another server
func addPeer(peer string) error {
peerHash := sha256sum(peer)
// Check if already peered
mu.Lock()
_, ok := hashToDomain[peerHash]
mu.Unlock()
if ok {
return nil
}
mu.Lock()
hashToDomain[peerHash] = peer
mu.Unlock()
// Try request to peer
log.Printf("%s trying to peer with %s", me, peer)
resp, err := http.Get(peer + "/peer?peer=" + me)
if err != nil {
// Request failed, delete peer
mu.Lock()
delete(hashToDomain, peerHash)
mu.Unlock()
return err
}
log.Printf("%s successfully peered with %s", me, peer)
mu.Lock()
i := sort.SearchStrings(peerHashes, peerHash)
peerHashes = append(peerHashes, "")
copy(peerHashes[i+1:], peerHashes[i:])
peerHashes[i] = peerHash
myPos = sort.SearchStrings(peerHashes, me)
mu.Unlock()
// Read response body
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
// Try adding all peers of this peer
newPeers := strings.Split(string(body), "\n")
for _, newPeer := range newPeers[:len(newPeers)-1] {
go addPeer(newPeer)
}
return nil
}
// Handle incoming peer requests
func peerHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
peer := r.Form.Get("peer")
if peer == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
for _, p := range hashToDomain {
fmt.Fprintf(w, "%s\n", p)
}
go addPeer(peer)
}
// Handle DHT requests
func dhtHandler(w http.ResponseWriter, r *http.Request) {
key := r.URL.String()[5:]
keyHash := sha256sum(key)
fmt.Println(key, keyHash)
mu.Lock()
keyPos := sort.SearchStrings(peerHashes, keyHash)
if keyPos < myPos {
keyPos += len(peerHashes)
}
mu.Unlock()
if r.Method == "GET" {
if keyPos - myPos < 5 {
mu.Lock()
if val, ok := kvstore[key]; ok {
w.Write([]byte(val))
} else {
w.WriteHeader(http.StatusNotFound)
}
mu.Unlock()
} else {
for i := 0; i < 5 && i < len(peerHashes); i++ {
j := hashToDomain[peerHashes[(keyPos+i)%len(peerHashes)]]
go func() string {
resp, err := http.Get(j + r.URL.String())
if err != nil {
return ""
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return ""
}
return string(b)
}()
}
}
} else if r.Method == "PUT" {
b, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
if keyPos - myPos < 5 {
mu.Lock()
kvstore[key] = string(b)
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// Handle storage requests
func storageHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.String()[5:]
if r.Method == "GET" {
} else if r.Method == "PUT" {
} else if r.Method == "DELETE" {
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
bindAddr := flag.String("b", ":4200", "bind address")
domain := flag.String("d", "http://localhost:4200", "full domain name")
peer := flag.String("i", "", "initial peer")
flag.Parse()
log.Printf("Starting %s %s %s", *bindAddr, *domain, *peer)
// Record myself
me = *domain
myHash = sha256sum(me)
myPos = 0
peerHashes = append(peerHashes, sha256sum(me))
hashToDomain = map[string]string{peerHashes[0]: me}
if *peer != "" {
go addPeer(*peer)
}
http.HandleFunc("/peer", peerHandler)
http.HandleFunc("/dht", dhtHandler)
http.HandleFunc("/storage", storageHandler)
log.Fatal(http.ListenAndServe(*bindAddr, nil))
}
|