http guest api

This commit is contained in:
KusakabeSi
2021-08-24 18:16:21 +00:00
parent c4183ca924
commit ad196d3f95
7 changed files with 100 additions and 20 deletions

View File

@ -2,8 +2,11 @@ package main
import (
"bytes"
"encoding/json"
"net"
"strconv"
"sync"
"time"
"net/http"
@ -23,9 +26,20 @@ var (
http_PeerInfoStr []byte
http_PeerState map[string]*PeerState
http_PeerID2Map map[config.Vertex]string
http_PeerInfos config.HTTP_Peers
http_PeerInfos config.HTTP_Peers // nodeID name pubkey, preshared key and more
http_peerinfos sync.Map // map[config.Vertex]string // nodeID and name, for guest visiting
http_StatePWD string
http_StateExpire time.Time
http_StateString []byte
)
type HttpState struct {
PeerInfo map[config.Vertex]string
Edges map[config.Vertex]map[config.Vertex]float64
NhTable config.NextHopTable
Dist config.DistTable
}
type PeerState struct {
NhTableState [32]byte
PeerInfoState [32]byte
@ -59,6 +73,7 @@ func get_peerinfo(w http.ResponseWriter, r *http.Request) {
if bytes.Equal(http_PeerInfo_hash[:], []byte(State)) {
if state := http_PeerState[PubKey]; state != nil {
copy(http_PeerState[PubKey].PeerInfoState[:], State)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(http_PeerInfoStr))
return
@ -87,6 +102,7 @@ func get_nhtable(w http.ResponseWriter, r *http.Request) {
if bytes.Equal(http_NhTable_Hash[:], []byte(State)) {
if state := http_PeerState[PubKey]; state != nil {
copy(http_PeerState[PubKey].NhTableState[:], State)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(http_NhTableStr))
return
@ -96,6 +112,39 @@ func get_nhtable(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Not found"))
}
func get_info(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
PwdA, has := params["Password"]
if !has {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not found"))
return
}
password := PwdA[0]
if password != http_StatePWD {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Wrong password"))
return
}
if time.Now().After(http_StateExpire) {
hs := HttpState{
PeerInfo: make(map[config.Vertex]string),
NhTable: http_graph.GetNHTable(false),
Edges: http_graph.GetEdges(),
Dist: http_graph.GetDtst(),
}
http_peerinfos.Range(func(key interface{}, value interface{}) bool {
hs.PeerInfo[key.(config.Vertex)] = value.(string)
return true
})
http_StateExpire = time.Now().Add(5 * time.Second)
http_StateString, _ = json.Marshal(hs)
}
w.WriteHeader(http.StatusOK)
w.Write(http_StateString)
return
}
func HttpServer(http_port int, apiprefix string) {
mux := http.NewServeMux()
if apiprefix[0] != '/' {