-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
http_server.go
209 lines (171 loc) · 4.78 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
package hls
import (
_ "embed"
"errors"
"net"
"net/http"
gopath "path"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/protocols/httpp"
"github.com/bluenviron/mediamtx/internal/restrictnetwork"
)
//go:generate go run ./hlsjsdownloader
//go:embed index.html
var hlsIndex []byte
//nolint:typecheck
//go:embed hls.min.js
var hlsMinJS []byte
func mergePathAndQuery(path string, rawQuery string) string {
res := path
if rawQuery != "" {
res += "?" + rawQuery
}
return res
}
type httpServer struct {
address string
encryption bool
serverKey string
serverCert string
allowOrigin string
trustedProxies conf.IPNetworks
readTimeout conf.StringDuration
pathManager serverPathManager
parent *Server
inner *httpp.WrappedServer
}
func (s *httpServer) initialize() error {
router := gin.New()
router.SetTrustedProxies(s.trustedProxies.ToTrustedProxies()) //nolint:errcheck
router.NoRoute(s.onRequest)
network, address := restrictnetwork.Restrict("tcp", s.address)
s.inner = &httpp.WrappedServer{
Network: network,
Address: address,
ReadTimeout: time.Duration(s.readTimeout),
Encryption: s.encryption,
ServerCert: s.serverCert,
ServerKey: s.serverKey,
Handler: router,
Parent: s,
}
err := s.inner.Initialize()
if err != nil {
return err
}
return nil
}
// Log implements logger.Writer.
func (s *httpServer) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, format, args...)
}
func (s *httpServer) close() {
s.inner.Close()
}
func (s *httpServer) onRequest(ctx *gin.Context) {
ctx.Writer.Header().Set("Access-Control-Allow-Origin", s.allowOrigin)
ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
switch ctx.Request.Method {
case http.MethodOptions:
ctx.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET")
ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Range")
ctx.Writer.WriteHeader(http.StatusNoContent)
return
case http.MethodGet:
default:
return
}
// remove leading prefix
pa := ctx.Request.URL.Path[1:]
var dir string
var fname string
switch {
case strings.HasSuffix(pa, "/hls.min.js"):
ctx.Writer.Header().Set("Cache-Control", "max-age=3600")
ctx.Writer.Header().Set("Content-Type", "application/javascript")
ctx.Writer.WriteHeader(http.StatusOK)
ctx.Writer.Write(hlsMinJS)
return
case pa == "", pa == "favicon.ico", strings.HasSuffix(pa, "/hls.min.js.map"):
return
case strings.HasSuffix(pa, ".m3u8") ||
strings.HasSuffix(pa, ".ts") ||
strings.HasSuffix(pa, ".mp4") ||
strings.HasSuffix(pa, ".mp"):
dir, fname = gopath.Dir(pa), gopath.Base(pa)
if strings.HasSuffix(fname, ".mp") {
fname += "4"
}
default:
dir, fname = pa, ""
if !strings.HasSuffix(dir, "/") {
ctx.Writer.Header().Set("Location", mergePathAndQuery(ctx.Request.URL.Path+"/", ctx.Request.URL.RawQuery))
ctx.Writer.WriteHeader(http.StatusMovedPermanently)
return
}
}
dir = strings.TrimSuffix(dir, "/")
if dir == "" {
return
}
user, pass, hasCredentials := ctx.Request.BasicAuth()
pathConf, err := s.pathManager.FindPathConf(defs.PathFindPathConfReq{
AccessRequest: defs.PathAccessRequest{
Name: dir,
Query: ctx.Request.URL.RawQuery,
Publish: false,
IP: net.ParseIP(ctx.ClientIP()),
User: user,
Pass: pass,
Proto: auth.ProtocolHLS,
},
})
if err != nil {
var terr auth.Error
if errors.As(err, &terr) {
if !hasCredentials {
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return
}
s.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Message)
// wait some seconds to mitigate brute force attacks
<-time.After(auth.PauseAfterError)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return
}
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
switch fname {
case "":
ctx.Writer.Header().Set("Cache-Control", "max-age=3600")
ctx.Writer.Header().Set("Content-Type", "text/html")
ctx.Writer.WriteHeader(http.StatusOK)
ctx.Writer.Write(hlsIndex)
default:
mux, err := s.parent.getMuxer(serverGetMuxerReq{
path: dir,
remoteAddr: httpp.RemoteAddr(ctx),
query: ctx.Request.URL.RawQuery,
sourceOnDemand: pathConf.SourceOnDemand,
})
if err != nil {
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
mi := mux.getInstance()
if mi == nil {
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
ctx.Request.URL.Path = fname
mi.handleRequest(ctx)
}
}