Welcome to mirror list, hosted at ThFree Co, Russian Federation.

helpers.go « helper « internal « workhorse - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4b458372629626a5644f93df37812f474cfd1557 (plain)
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
package helper

import (
	"bytes"
	"errors"
	"io"
	"mime"
	"net"
	"net/http"
	"net/url"
	"os"
	"strings"

	"github.com/sebest/xff"

	"gitlab.com/gitlab-org/gitlab/workhorse/internal/log"
)

func CaptureAndFail(w http.ResponseWriter, r *http.Request, err error, msg string, code int) {
	http.Error(w, msg, code)
	printError(r, err, nil)
}

func Fail500(w http.ResponseWriter, r *http.Request, err error) {
	CaptureAndFail(w, r, err, "Internal server error", http.StatusInternalServerError)
}

func Fail500WithFields(w http.ResponseWriter, r *http.Request, err error, fields log.Fields) {
	http.Error(w, "Internal server error", http.StatusInternalServerError)
	printError(r, err, fields)
}

func RequestEntityTooLarge(w http.ResponseWriter, r *http.Request, err error) {
	CaptureAndFail(w, r, err, "Request Entity Too Large", http.StatusRequestEntityTooLarge)
}

func printError(r *http.Request, err error, fields log.Fields) {
	log.WithRequest(r).WithFields(fields).WithError(err).Error()
}

func SetNoCacheHeaders(header http.Header) {
	header.Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
	header.Set("Pragma", "no-cache")
	header.Set("Expires", "Fri, 01 Jan 1990 00:00:00 GMT")
}

func OpenFile(path string) (file *os.File, fi os.FileInfo, err error) {
	file, err = os.Open(path)
	if err != nil {
		return
	}

	defer func() {
		if err != nil {
			file.Close()
		}
	}()

	fi, err = file.Stat()
	if err != nil {
		return
	}

	// The os.Open can also open directories
	if fi.IsDir() {
		err = &os.PathError{
			Op:   "open",
			Path: path,
			Err:  errors.New("path is directory"),
		}
		return
	}

	return
}

func URLMustParse(s string) *url.URL {
	u, err := url.Parse(s)
	if err != nil {
		log.WithError(err).WithFields(log.Fields{"url": s}).Fatal("urlMustParse")
	}
	return u
}

func HTTPError(w http.ResponseWriter, r *http.Request, error string, code int) {
	if r.ProtoAtLeast(1, 1) {
		// Force client to disconnect if we render request error
		w.Header().Set("Connection", "close")
	}

	http.Error(w, error, code)
}

func HeaderClone(h http.Header) http.Header {
	h2 := make(http.Header, len(h))
	for k, vv := range h {
		vv2 := make([]string, len(vv))
		copy(vv2, vv)
		h2[k] = vv2
	}
	return h2
}

func FixRemoteAddr(r *http.Request) {
	// Unix domain sockets have a remote addr of @. This will make the
	// xff package lookup the X-Forwarded-For address if available.
	if r.RemoteAddr == "@" {
		r.RemoteAddr = "127.0.0.1:0"
	}
	r.RemoteAddr = xff.GetRemoteAddr(r)
}

func SetForwardedFor(newHeaders *http.Header, originalRequest *http.Request) {
	if clientIP, _, err := net.SplitHostPort(originalRequest.RemoteAddr); err == nil {
		var header string

		// If we aren't the first proxy retain prior
		// X-Forwarded-For information as a comma+space
		// separated list and fold multiple headers into one.
		if prior, ok := originalRequest.Header["X-Forwarded-For"]; ok {
			header = strings.Join(prior, ", ") + ", " + clientIP
		} else {
			header = clientIP
		}
		newHeaders.Set("X-Forwarded-For", header)
	}
}

func IsContentType(expected, actual string) bool {
	parsed, _, err := mime.ParseMediaType(actual)
	return err == nil && parsed == expected
}

func IsApplicationJson(r *http.Request) bool {
	contentType := r.Header.Get("Content-Type")
	return IsContentType("application/json", contentType)
}

func ReadRequestBody(w http.ResponseWriter, r *http.Request, maxBodySize int64) ([]byte, error) {
	limitedBody := http.MaxBytesReader(w, r.Body, maxBodySize)
	defer limitedBody.Close()

	return io.ReadAll(limitedBody)
}

func CloneRequestWithNewBody(r *http.Request, body []byte) *http.Request {
	newReq := *r
	newReq.Body = io.NopCloser(bytes.NewReader(body))
	newReq.Header = HeaderClone(r.Header)
	newReq.ContentLength = int64(len(body))
	return &newReq
}