-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
207 lines (170 loc) · 4.47 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
)
type signalRequest struct {
Room string `json:"room"` // 16 bytes (32 chars as hex string): room identifier
Intent string `json:"intent"` // enum as string: offer, answer
Desc string `json:"desc"` // < 8KB as uint8 array string: sdp desc
Nonce string `json:"nonce"` // 16 bytes as uint8 array string: nonce for the desc
}
type channel struct {
signal []byte
createdAt int64
}
const (
httpDefaultPort = "8080"
httpMaxBodySize = 8 * 1024
httpErrMsgNotAllowed = "{\"err\": \"method not allowed\"}"
httpErrMsgNotFound = "{\"err\": \"404\"}"
httpErrMsgInvalidJSON = "{\"err\": \"invalid json\"}"
httpErrMsgInvalidRequest = "{\"err\": \"{error}\"}"
intentOffer = "offer"
intentAnswer = "answer"
maxDurationInSeconds = 10 * 60 // 10 mins
)
var (
_channels sync.Map
_signalsPath = "/signals"
_rootPath = "/"
errInvalidRoom = errors.New("invalid room")
errInvalidNonce = errors.New("invalid nonce")
errInvalidIntent = errors.New("invalid intent")
errInvalidDesc = errors.New("invalid sdp")
rePatternHex = regexp.MustCompile("^[A-Fa-f0-9]{32}$")
httpMsgCreated = []byte("{\"status\": \"created\"}")
)
func main() {
go sweep()
http.HandleFunc(_signalsPath, handleSignals)
http.Handle(_rootPath, http.FileServer(http.Dir("./public")))
port := os.Getenv("PORT")
if port == "" {
port = httpDefaultPort
}
http.ListenAndServe(":"+port, nil)
select {}
}
func handleSignals(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Methods", "POST,GET")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Cache-Control")
r.Body = http.MaxBytesReader(w, r.Body, httpMaxBodySize)
if r.Method == http.MethodGet {
handleGetSignal(w, r)
} else if r.Method == http.MethodPost {
handleCreateSignal(w, r)
} else {
http.Error(w, httpErrMsgNotAllowed, http.StatusMethodNotAllowed)
return
}
}
func handleCreateSignal(w http.ResponseWriter, r *http.Request) {
var err error
var req signalRequest
defer func() {
if err != nil {
log.Println(req, err)
} else {
log.Println(req)
}
}()
if r.Method != http.MethodPost {
http.Error(w, httpErrMsgNotAllowed, http.StatusMethodNotAllowed)
return
}
content, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, httpErrMsgInvalidJSON, http.StatusUnprocessableEntity)
}
err = json.Unmarshal(content, &req)
if err != nil {
http.Error(w, httpErrMsgInvalidJSON, http.StatusUnprocessableEntity)
return
}
err = validateSignalReq(req)
if err != nil {
http.Error(w, buildErr(err), http.StatusUnprocessableEntity)
return
}
signal, _ := json.Marshal(map[string]string{
"nonce": req.Nonce,
"desc": req.Desc,
})
_channels.Store(req.Room+req.Intent, channel{signal: signal, createdAt: time.Now().Unix()})
w.Write(httpMsgCreated)
}
func handleGetSignal(w http.ResponseWriter, r *http.Request) {
var err error
defer func() {
if err != nil {
log.Println(err)
}
}()
room := r.URL.Query().Get("room")
intent := r.URL.Query().Get("intent")
err = validateSignalQuery(room, intent)
if err != nil {
http.Error(w, buildErr(err), http.StatusUnprocessableEntity)
return
}
key := room + intent
val, ok := _channels.Load(key)
if !ok {
err = fmt.Errorf("%s for room(%s) not found", intent, room)
http.Error(w, httpErrMsgNotFound, http.StatusNotFound)
return
}
_channels.Delete(key)
w.Write(val.(channel).signal)
}
func validateSignalReq(req signalRequest) error {
if !rePatternHex.Match([]byte(req.Room)) {
return errInvalidRoom
}
if req.Intent != intentOffer && req.Intent != intentAnswer {
return errInvalidIntent
}
if req.Desc == "" {
return errInvalidDesc
}
if len(req.Nonce) > 64 {
return errInvalidNonce
}
return nil
}
func validateSignalQuery(room, intent string) error {
if !rePatternHex.Match([]byte(room)) {
return errInvalidRoom
}
if intent != intentOffer && intent != intentAnswer {
return errInvalidIntent
}
return nil
}
func buildErr(err error) string {
return strings.Replace(httpErrMsgInvalidRequest, "{error}", err.Error(), 1)
}
func sweep() {
for {
cleanBefore := time.Now().Unix() - maxDurationInSeconds
_channels.Range(func(key, value any) bool {
if value.(channel).createdAt <= cleanBefore {
_channels.Delete(key)
}
return true
})
time.Sleep(time.Minute)
}
}