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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
|
package domain
import (
"crypto/tls"
"errors"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sys/unix"
"gitlab.com/gitlab-org/gitlab-pages/internal/httperrors"
"gitlab.com/gitlab-org/gitlab-pages/internal/httputil"
)
type locationDirectoryError struct {
FullPath string
RelativePath string
}
type project struct {
HTTPSOnly bool
}
type projects map[string]*project
// D is a domain that gitlab-pages can serve.
type D struct {
group string
// custom domains:
projectName string
config *domainConfig
certificate *tls.Certificate
certificateError error
certificateOnce sync.Once
// group domains:
projects projects
}
// String implements Stringer.
func (d *D) String() string {
if d.group != "" && d.projectName != "" {
return d.group + "/" + d.projectName
}
if d.group != "" {
return d.group
}
return d.projectName
}
func (l *locationDirectoryError) Error() string {
return "location error accessing directory where file expected"
}
func acceptsGZip(r *http.Request) bool {
if r.Header.Get("Range") != "" {
return false
}
offers := []string{"gzip", "identity"}
acceptedEncoding := httputil.NegotiateContentEncoding(r, offers)
return acceptedEncoding == "gzip"
}
func handleGZip(w http.ResponseWriter, r *http.Request, fullPath string) string {
if !acceptsGZip(r) {
return fullPath
}
gzipPath := fullPath + ".gz"
// Ensure the .gz file is not a symlink
if fi, err := os.Lstat(gzipPath); err != nil || !fi.Mode().IsRegular() {
return fullPath
}
w.Header().Set("Content-Encoding", "gzip")
return gzipPath
}
func setContentType(w http.ResponseWriter, fullPath string) {
ext := filepath.Ext(fullPath)
ctype := mime.TypeByExtension(ext)
if ctype != "" {
w.Header().Set("Content-Type", ctype)
}
}
// IsHTTPSOnly figures out if the request should be handled with HTTPS
// only by looking at group and project level config.
func (d *D) IsHTTPSOnly(r *http.Request) bool {
// Check custom domain config (e.g. http://example.com)
if d.config != nil {
return d.config.HTTPSOnly
}
// Check default domain config (e.g. http://mydomain.gitlab.io)
groupProject := d.projects[strings.ToLower(r.Host)]
if groupProject != nil {
return groupProject.HTTPSOnly
}
// Check URLs with multiple projects for a group
// (e.g. http://group.gitlab.io/projectA and http://group.gitlab.io/projectB)
split := strings.SplitN(r.URL.Path, "/", 3)
if len(split) < 2 {
return false
}
project := d.projects[strings.ToLower(split[1])]
if project != nil {
return project.HTTPSOnly
}
return false
}
func (d *D) serveFile(w http.ResponseWriter, r *http.Request, origPath string) error {
fullPath := handleGZip(w, r, origPath)
file, err := openNoFollow(fullPath)
if err != nil {
return err
}
defer file.Close()
fi, err := file.Stat()
if err != nil {
return err
}
// Set caching headers
w.Header().Set("Cache-Control", "max-age=600")
w.Header().Set("Expires", time.Now().Add(10*time.Minute).Format(time.RFC1123))
// ServeContent sets Content-Type for us
http.ServeContent(w, r, origPath, fi.ModTime(), file)
return nil
}
func (d *D) serveCustomFile(w http.ResponseWriter, r *http.Request, code int, origPath string) error {
fullPath := handleGZip(w, r, origPath)
// Open and serve content of file
file, err := openNoFollow(fullPath)
if err != nil {
return err
}
defer file.Close()
fi, err := file.Stat()
if err != nil {
return err
}
setContentType(w, origPath)
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
w.WriteHeader(code)
if r.Method != "HEAD" {
_, err := io.CopyN(w, file, fi.Size())
return err
}
return nil
}
// Resolve the HTTP request to a path on disk, converting requests for
// directories to requests for index.html inside the directory if appropriate.
func (d *D) resolvePath(projectName string, subPath ...string) (string, error) {
publicPath := filepath.Join(d.group, projectName, "public")
// Don't use filepath.Join as cleans the path,
// where we want to traverse full path as supplied by user
// (including ..)
testPath := publicPath + "/" + strings.Join(subPath, "/")
fullPath, err := filepath.EvalSymlinks(testPath)
if err != nil {
return "", err
}
// The requested path resolved to somewhere outside of the public/ directory
if !strings.HasPrefix(fullPath, publicPath+"/") && fullPath != publicPath {
return "", fmt.Errorf("%q should be in %q", fullPath, publicPath)
}
fi, err := os.Lstat(fullPath)
if err != nil {
return "", err
}
// The requested path is a directory, so try index.html via recursion
if fi.IsDir() {
return "", &locationDirectoryError{
FullPath: fullPath,
RelativePath: strings.TrimPrefix(fullPath, publicPath),
}
}
// The file exists, but is not a supported type to serve. Perhaps a block
// special device or something else that may be a security risk.
if !fi.Mode().IsRegular() {
return "", fmt.Errorf("%s: is not a regular file", fullPath)
}
return fullPath, nil
}
func (d *D) tryNotFound(w http.ResponseWriter, r *http.Request, projectName string) error {
page404, err := d.resolvePath(projectName, "404.html")
if err != nil {
return err
}
err = d.serveCustomFile(w, r, http.StatusNotFound, page404)
if err != nil {
return err
}
return nil
}
func (d *D) tryFile(w http.ResponseWriter, r *http.Request, projectName, pathSuffix string, subPath ...string) error {
fullPath, err := d.resolvePath(projectName, subPath...)
if locationError, _ := err.(*locationDirectoryError); locationError != nil {
if endsWithSlash(r.URL.Path) {
fullPath, err = d.resolvePath(projectName, filepath.Join(subPath...), "index.html")
} else {
redirectPath := "//" + r.Host + "/"
if pathSuffix != "" {
redirectPath += pathSuffix + "/"
}
if locationError.RelativePath != "" {
redirectPath += strings.TrimPrefix(locationError.RelativePath, "/") + "/"
}
http.Redirect(w, r, redirectPath, 302)
return nil
}
}
if err != nil {
return err
}
return d.serveFile(w, r, fullPath)
}
func (d *D) serveFromGroup(w http.ResponseWriter, r *http.Request) {
// The Path always contains "/" at the beginning
split := strings.SplitN(r.URL.Path, "/", 3)
// Try to serve file for http://group.example.com/subpath/... => /group/subpath/...
if len(split) >= 2 && d.tryFile(w, r, split[1], split[1], split[2:]...) == nil {
return
}
// Try to serve file for http://group.example.com/... => /group/group.example.com/...
if r.Host != "" && d.tryFile(w, r, strings.ToLower(r.Host), "", r.URL.Path) == nil {
return
}
// Try serving not found page for http://group.example.com/subpath/ => /group/subpath/404.html
if len(split) >= 2 && d.tryNotFound(w, r, split[1]) == nil {
return
}
// Try serving not found page for http://group.example.com/ => /group/group.example.com/404.html
if r.Host != "" && d.tryNotFound(w, r, strings.ToLower(r.Host)) == nil {
return
}
// Serve generic not found
httperrors.Serve404(w)
}
func (d *D) serveFromConfig(w http.ResponseWriter, r *http.Request) {
// Try to serve file for http://host/... => /group/project/...
if d.tryFile(w, r, d.projectName, "", r.URL.Path) == nil {
return
}
// Try serving not found page for http://host/ => /group/project/404.html
if d.tryNotFound(w, r, d.projectName) == nil {
return
}
// Serve generic not found
httperrors.Serve404(w)
}
// EnsureCertificate parses the PEM-encoded certificate for the domain
func (d *D) EnsureCertificate() (*tls.Certificate, error) {
if d.config == nil {
return nil, errors.New("tls certificates can be loaded only for pages with configuration")
}
d.certificateOnce.Do(func() {
var cert tls.Certificate
cert, d.certificateError = tls.X509KeyPair([]byte(d.config.Certificate), []byte(d.config.Key))
if d.certificateError == nil {
d.certificate = &cert
}
})
return d.certificate, d.certificateError
}
// ServeHTTP implements http.Handler.
func (d *D) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if d.config != nil {
d.serveFromConfig(w, r)
} else {
d.serveFromGroup(w, r)
}
}
func endsWithSlash(path string) bool {
return strings.HasSuffix(path, "/")
}
func openNoFollow(path string) (*os.File, error) {
return os.OpenFile(path, os.O_RDONLY|unix.O_NOFOLLOW, 0)
}
|