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
|
package main
import (
"encoding/gob"
"flag"
"fmt"
"log"
"net/http"
"os"
"sync"
)
var mu sync.Mutex
var bindAddr string
var me string
var initialPeer string
var dataDir string
type LoggingHandler struct {
Handler http.Handler
}
// Log all HTTP requests
func (lh LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s%s", r.Method, me, r.URL.String())
lh.Handler.ServeHTTP(w, r)
}
func main() {
flag.StringVar(&bindAddr, "b", ":4200", "bind address")
flag.StringVar(&me, "u", "http://localhost:4200", "public URL")
flag.StringVar(&initialPeer, "i", "", "initial peer")
flag.StringVar(&dataDir, "d", ".", "data directory")
flag.Parse()
log.Printf("Starting %s %s %s %s", bindAddr, me, initialPeer, dataDir)
// Record myself
myHash = sha256sum(me)
myPos = 0
peerHashes = append(peerHashes, sha256sum(me))
hashToDomain = map[string]string{peerHashes[0]: me}
kvstore = make(map[string][]byte)
users = make(map[string]*user)
// Load user data from disk
os.Mkdir(dataDir, 0755)
entries, err := os.ReadDir(dataDir)
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
id := entry.Name()
reader, err := os.Open(dataDir + "/" + id + "/gob")
if err != nil {
log.Fatal(err)
continue
}
var user *user
dec := gob.NewDecoder(reader)
dec.Decode(user)
users[id] = user
}
// Start background functions
if initialPeer != "" {
go addPeer(initialPeer)
}
go cleanPeers()
go cleanKVStore()
go redistributeKeys()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello! This is a Kela server.")
})
http.HandleFunc("/peer", peerHandler)
http.HandleFunc("/user/", userHandler)
http.HandleFunc("/dht/", dhtHandler)
http.HandleFunc("/storage/", storageHandler)
http.HandleFunc("/message/", messageHandler)
log.Fatal(http.ListenAndServe(bindAddr, LoggingHandler{Handler: http.DefaultServeMux}))
}
|