File: sendfile.go

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (176 lines) | stat: -rw-r--r-- 4,558 bytes parent folder | download
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
/*
Package sendfile middleware transparently sends static files in HTTP responses
via the X-Sendfile mechanism. All that is needed in the Rails code is the
'send_file' method.
*/
package sendfile

import (
	"fmt"
	"io"
	"net/http"
	"regexp"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"

	"gitlab.com/gitlab-org/labkit/log"
	"gitlab.com/gitlab-org/labkit/mask"

	"gitlab.com/gitlab-org/gitlab/workhorse/internal/headers"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper/fail"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper/nginx"
)

var (
	sendFileRequests = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gitlab_workhorse_sendfile_requests",
			Help: "How many X-Sendfile requests have been processed by gitlab-workhorse, partitioned by sendfile type.",
		},
		[]string{"type"},
	)

	sendFileBytes = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gitlab_workhorse_sendfile_bytes",
			Help: "How many X-Sendfile bytes have been sent by gitlab-workhorse, partitioned by sendfile type.",
		},
		[]string{"type"},
	)

	artifactsSendFile = regexp.MustCompile("builds/[0-9]+/artifacts")
)

type sendFileResponseWriter struct {
	rw       http.ResponseWriter
	status   int
	hijacked bool
	req      *http.Request
}

// SendFile wraps an HTTP handler and serves static files efficiently using sendfile.
func SendFile(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		s := &sendFileResponseWriter{
			rw:  rw,
			req: req,
		}
		// Advertise to upstream (Rails) that we support X-Sendfile
		req.Header.Set(headers.XSendFileTypeHeader, headers.XSendFileHeader)
		defer s.flush()
		h.ServeHTTP(s, req)
	})
}

func (s *sendFileResponseWriter) Header() http.Header {
	return s.rw.Header()
}

func (s *sendFileResponseWriter) Write(data []byte) (int, error) {
	if s.status == 0 {
		s.WriteHeader(http.StatusOK)
	}
	if s.hijacked {
		return len(data), nil
	}
	return s.rw.Write(data)
}

func (s *sendFileResponseWriter) WriteHeader(status int) {
	if s.status != 0 {
		return
	}

	s.status = status
	if s.status != http.StatusOK {
		s.rw.WriteHeader(s.status)
		return
	}

	file := s.Header().Get(headers.XSendFileHeader)
	if file != "" && !s.hijacked {
		// Mark this connection as hijacked
		s.hijacked = true

		// Serve the file
		nginx.DisableResponseBuffering(s.rw)
		sendFileFromDisk(s.rw, s.req, file)
		return
	}

	s.rw.WriteHeader(s.status)
}

// Unwrap lets http.ResponseController get the underlying http.ResponseWriter.
func (s *sendFileResponseWriter) Unwrap() http.ResponseWriter {
	return s.rw
}

func sendFileFromDisk(w http.ResponseWriter, r *http.Request, file string) {
	log.WithContextFields(r.Context(), log.Fields{
		"file":   file,
		"method": r.Method,
		"uri":    mask.URL(r.RequestURI),
	}).Print("Send file")

	contentTypeHeaderPresent := false

	if headers.IsDetectContentTypeHeaderPresent(w) {
		// Removing the GitlabWorkhorseDetectContentTypeHeader header to
		// avoid handling the response by the senddata handler
		w.Header().Del(headers.GitlabWorkhorseDetectContentTypeHeader)
		contentTypeHeaderPresent = true
	}

	content, fi, err := helper.OpenFile(file)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer func() {
		if err = content.Close(); err != nil {
			fmt.Printf("Error closing file: %v", err)
		}
	}()

	countSendFileMetrics(fi.Size(), r)

	if contentTypeHeaderPresent {
		data, err := io.ReadAll(io.LimitReader(content, headers.MaxDetectSize))
		if err != nil {
			fail.Request(w, r, fmt.Errorf("content type detection: %v", err))
			return
		}

		_, err = content.Seek(0, io.SeekStart)
		if err != nil {
			fail.Request(w, r, fmt.Errorf("error rewinding file: %v", err))
			return
		}

		contentType, contentDisposition := headers.SafeContentHeaders(data, w.Header().Get(headers.ContentDispositionHeader))
		w.Header().Set(headers.ContentTypeHeader, contentType)
		w.Header().Set(headers.ContentDispositionHeader, contentDisposition)
	}

	http.ServeContent(w, r, "", fi.ModTime(), content)
}

func countSendFileMetrics(size int64, r *http.Request) {
	var requestType string
	switch {
	case artifactsSendFile.MatchString(r.RequestURI):
		requestType = "artifacts"
	default:
		requestType = "other"
	}

	sendFileRequests.WithLabelValues(requestType).Inc()
	sendFileBytes.WithLabelValues(requestType).Add(float64(size))
}

func (s *sendFileResponseWriter) flush() {
	s.WriteHeader(http.StatusOK)
}