-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_server.go
257 lines (199 loc) · 4.86 KB
/
http_server.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// HTTP Server
package main
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
tls_certificate_loader "github.com/AgustinSRG/go-tls-certificate-loader"
)
// Generates unique ID for each request
func (node *WebRTC_CDN_Node) getRequestID() uint64 {
node.mutexReqCount.Lock()
defer node.mutexReqCount.Unlock()
node.reqCount++
return node.reqCount
}
// Adds IP address to the list
// Returns false if the limit has been reached
func (node *WebRTC_CDN_Node) AddIP(ip string) bool {
node.mutexIpCount.Lock()
defer node.mutexIpCount.Unlock()
c := node.ipCount[ip]
if c >= node.ipLimit {
return false
}
node.ipCount[ip] = c + 1
return true
}
// Checks if an IP is exempted from the limit
func (node *WebRTC_CDN_Node) isIPExempted(ipStr string) bool {
r := os.Getenv("CONCURRENT_LIMIT_WHITELIST")
if r == "" {
return false
}
if r == "*" {
return true
}
ip := net.ParseIP(ipStr)
parts := strings.Split(r, ",")
for i := 0; i < len(parts); i++ {
_, rang, e := net.ParseCIDR(parts[i])
if e != nil {
LogError(e)
continue
}
if rang.Contains(ip) {
return true
}
}
return false
}
// Removes an IP from the list
func (node *WebRTC_CDN_Node) RemoveIP(ip string) {
node.mutexIpCount.Lock()
defer node.mutexIpCount.Unlock()
c := node.ipCount[ip]
if c <= 1 {
delete(node.ipCount, ip)
} else {
node.ipCount[ip] = c - 1
}
}
// Runs secure HTTPs server
func (node *WebRTC_CDN_Node) runHTTPSecureServer(wg *sync.WaitGroup) {
defer func() {
wg.Done()
}()
bind_addr := os.Getenv("BIND_ADDRESS")
// Setup HTTPS server
var port int
port = 443
customSSLPort := os.Getenv("SSL_PORT")
if customSSLPort != "" {
sslp, e := strconv.Atoi(customSSLPort)
if e == nil {
port = sslp
}
}
certFile := os.Getenv("SSL_CERT")
keyFile := os.Getenv("SSL_KEY")
if certFile == "" || keyFile == "" {
return
}
var sslReloadSeconds = 60
customSslReloadSeconds := os.Getenv("SSL_CHECK_RELOAD_SECONDS")
if customSslReloadSeconds != "" {
n, e := strconv.Atoi(customSslReloadSeconds)
if e == nil {
sslReloadSeconds = n
}
}
certificateLoader, err := tls_certificate_loader.NewTlsCertificateLoader(tls_certificate_loader.TlsCertificateLoaderConfig{
CertificatePath: certFile,
KeyPath: keyFile,
CheckReloadPeriod: time.Duration(sslReloadSeconds) * time.Second,
OnReload: func() {
LogInfo("Reloaded SSL certificates")
},
OnError: func(err error) {
LogError(err)
},
})
if err != nil {
LogError(err)
return
}
defer certificateLoader.Close()
// Setup HTTPS server
tlsServer := http.Server{
Addr: bind_addr + ":" + strconv.Itoa(port),
Handler: node,
TLSConfig: &tls.Config{
GetCertificate: certificateLoader.GetCertificate,
},
}
// Listen
LogInfo("[SSL] Listening on " + bind_addr + ":" + strconv.Itoa(port))
errSSL := tlsServer.ListenAndServeTLS("", "")
if errSSL != nil {
LogError(errSSL)
}
}
// Runs HTTP server
func (node *WebRTC_CDN_Node) runHTTPServer(wg *sync.WaitGroup) {
defer func() {
wg.Done()
}()
bind_addr := os.Getenv("BIND_ADDRESS")
// Setup HTTP server
var tcp_port int
tcp_port = 80
customTCPPort := os.Getenv("HTTP_PORT")
if customTCPPort != "" {
tcpp, e := strconv.Atoi(customTCPPort)
if e == nil {
tcp_port = tcpp
}
}
// Listen
LogInfo("[HTTP] Listening on " + bind_addr + ":" + strconv.Itoa(tcp_port))
errHTTP := http.ListenAndServe(bind_addr+":"+strconv.Itoa(tcp_port), node)
if errHTTP != nil {
LogError(errHTTP)
}
}
// Handles HTTP/HTTPS requests from clients
func (node *WebRTC_CDN_Node) ServeHTTP(w http.ResponseWriter, req *http.Request) {
reqId := node.getRequestID()
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
LogError(err)
w.WriteHeader(200)
fmt.Fprintf(w, "WebRTC-CDN Signaling Server. Connect to /ws for signaling\nGo to /test for testing.")
return
}
LogRequest(reqId, ip, ""+req.Method+" "+req.RequestURI)
if req.URL.Path == "/ws" {
// Websocket signaling connection
if !node.isIPExempted(ip) {
if !node.AddIP(ip) {
w.WriteHeader(429)
fmt.Fprintf(w, "Too many requests.")
LogRequest(reqId, ip, "Connection rejected: Too many requests")
return
}
}
c, err := node.upgrader.Upgrade(w, req, nil)
if err != nil {
LogError(err)
return
}
handler := Connection_Handler{
id: reqId,
ip: ip,
node: node,
connection: c,
}
handler.init()
node.mutexConnections.Lock()
node.connections[reqId] = &handler
node.mutexConnections.Unlock()
go handler.run()
} else {
w.WriteHeader(200)
fmt.Fprintf(w, "WebRTC-CDN Signaling Server. Connect to /ws for signaling")
}
}
// Called after a connection is closed
func (node *WebRTC_CDN_Node) onConnectionClose(id uint64, ip string) {
node.mutexConnections.Lock()
defer node.mutexConnections.Unlock()
node.RemoveIP(ip) // Remove ip count
delete(node.connections, id)
}