aboutsummaryrefslogtreecommitdiff
path: root/server/server.go
blob: e84b4e081c56db1cbd8175cdb1781fca9442d929 (plain)
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
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"sort"
	"strings"
	"sync"
)

var mu sync.Mutex
var me string
var hashToDomain map[string]string
var peerHashes []string
var kvstore map[string]string

func sha256sum(s string) string {
	// Get the sha256sum of string as a hex string
	b := sha256.Sum256([]byte(s))
	return hex.EncodeToString(b[:])
}

func addPeer(peer string) error {
	// Try to peer with another server
	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()
	peerHashes = append(peerHashes, peerHash)
	sort.Sort(sort.StringSlice(peerHashes))
	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
}

func peerHandler(w http.ResponseWriter, r *http.Request) {
	// Handle incoming peer requests
	r.ParseForm()
	peer := r.Form.Get("peer")
	if peer == "" {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	go addPeer(peer)
	for _, p := range hashToDomain {
		fmt.Fprintf(w, "%s\n", p)
	}
}

func getHandler(w http.ResponseWriter, r *http.Request) {

}

func setHandler(w http.ResponseWriter, r *http.Request) {

}

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
	peerHashes = append(peerHashes, sha256sum(me))
	hashToDomain = map[string]string{peerHashes[0]: me}

	if *peer != "" {
		go addPeer(*peer)
	}

	http.HandleFunc("/peer", peerHandler)
	http.HandleFunc("/get", getHandler)
	http.HandleFunc("/set", setHandler)
	log.Fatal(http.ListenAndServe(*bindAddr, nil))
}