summaryrefslogtreecommitdiff
path: root/plugins/http/handler.go
blob: ecdcb2c0430b388e1841f1af9fa2a90827f034b3 (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
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
package http

import (
	"net"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/hashicorp/go-multierror"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/interfaces/events"
	"github.com/spiral/roadrunner/v2/interfaces/pool"
	"github.com/spiral/roadrunner/v2/plugins/http/config"
	"github.com/spiral/roadrunner/v2/plugins/logger"
)

// MB is 1024 bytes
const MB uint64 = 1024 * 1024

// ErrorEvent represents singular http error event.
type ErrorEvent struct {
	// Request contains client request, must not be stored.
	Request *http.Request

	// Error - associated error, if any.
	Error error

	// event timings
	start   time.Time
	elapsed time.Duration
}

// Elapsed returns duration of the invocation.
func (e *ErrorEvent) Elapsed() time.Duration {
	return e.elapsed
}

// ResponseEvent represents singular http response event.
type ResponseEvent struct {
	// Request contains client request, must not be stored.
	Request *Request

	// Response contains service response.
	Response *Response

	// event timings
	start   time.Time
	elapsed time.Duration
}

// Elapsed returns duration of the invocation.
func (e *ResponseEvent) Elapsed() time.Duration {
	return e.elapsed
}

// Handler serves http connections to underlying PHP application using PSR-7 protocol. Context will include request headers,
// parsed files and query, payload will include parsed form dataTree (if any).
type Handler struct {
	maxRequestSize uint64
	uploads        config.Uploads
	trusted        config.Cidrs
	log            logger.Logger
	pool           pool.Pool
	mul            sync.Mutex
	lsn            events.Listener
}

// NewHandler return handle interface implementation
func NewHandler(maxReqSize uint64, uploads config.Uploads, trusted config.Cidrs, pool pool.Pool) (*Handler, error) {
	if pool == nil {
		return nil, errors.E(errors.Str("pool should be initialized"))
	}
	return &Handler{
		maxRequestSize: maxReqSize * MB,
		uploads:        uploads,
		pool:           pool,
		trusted:        trusted,
	}, nil
}

// AddListener attaches handler event controller.
func (h *Handler) AddListener(l events.Listener) {
	h.mul.Lock()
	defer h.mul.Unlock()

	h.lsn = l
}

// mdwr serve using PSR-7 requests passed to underlying application. Attempts to serve static files first if enabled.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	const op = errors.Op("http_plugin_serve_http")
	start := time.Now()

	// validating request size
	if h.maxRequestSize != 0 {
		err := h.maxSize(w, r, start, op)
		if err != nil {
			return
		}
	}

	req, err := NewRequest(r, h.uploads)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	// proxy IP resolution
	h.resolveIP(req)

	req.Open(h.log)
	defer req.Close(h.log)

	p, err := req.Payload()
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	rsp, err := h.pool.Exec(p)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	resp, err := NewResponse(rsp)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	h.handleResponse(req, resp, start)
	err = resp.Write(w)
	if err != nil {
		h.handleError(w, r, err, start)
	}
}

func (h *Handler) maxSize(w http.ResponseWriter, r *http.Request, start time.Time, op errors.Op) error {
	if length := r.Header.Get("content-length"); length != "" {
		if size, err := strconv.ParseInt(length, 10, 64); err != nil {
			h.handleError(w, r, err, start)
			return err
		} else if size > int64(h.maxRequestSize) {
			h.handleError(w, r, errors.E(op, errors.Str("request body max size is exceeded")), start)
			return err
		}
	}
	return nil
}

// handleError sends error.
func (h *Handler) handleError(w http.ResponseWriter, r *http.Request, err error, start time.Time) {
	h.mul.Lock()
	defer h.mul.Unlock()
	// if pipe is broken, there is no sense to write the header
	// in this case we just report about error
	if err == errEPIPE {
		h.throw(ErrorEvent{Request: r, Error: err, start: start, elapsed: time.Since(start)})
		return
	}
	err = multierror.Append(err)
	// ResponseWriter is ok, write the error code
	w.WriteHeader(500)
	_, err2 := w.Write([]byte(err.Error()))
	// error during the writing to the ResponseWriter
	if err2 != nil {
		err = multierror.Append(err2, err)
		// concat original error with ResponseWriter error
		h.throw(ErrorEvent{Request: r, Error: errors.E(err), start: start, elapsed: time.Since(start)})
		return
	}
	h.throw(ErrorEvent{Request: r, Error: err, start: start, elapsed: time.Since(start)})
}

// handleResponse triggers response event.
func (h *Handler) handleResponse(req *Request, resp *Response, start time.Time) {
	h.throw(ResponseEvent{Request: req, Response: resp, start: start, elapsed: time.Since(start)})
}

// throw invokes event handler if any.
func (h *Handler) throw(event interface{}) {
	if h.lsn != nil {
		h.lsn(event)
	}
}

// get real ip passing multiple proxy
func (h *Handler) resolveIP(r *Request) {
	if h.trusted.IsTrusted(r.RemoteAddr) == false {
		return
	}

	if r.Header.Get("X-Forwarded-For") != "" {
		ips := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
		ipCount := len(ips)

		for i := ipCount - 1; i >= 0; i-- {
			addr := strings.TrimSpace(ips[i])
			if net.ParseIP(addr) != nil {
				r.RemoteAddr = addr
				return
			}
		}

		return
	}

	// The logic here is the following:
	// In general case, we only expect X-Real-Ip header. If it exist, we get the IP address from header and set request Remote address
	// But, if there is no X-Real-Ip header, we also trying to check CloudFlare headers
	// True-Client-IP is a general CF header in which copied information from X-Real-Ip in CF.
	// CF-Connecting-IP is an Enterprise feature and we check it last in order.
	// This operations are near O(1) because Headers struct are the map type -> type MIMEHeader map[string][]string
	if r.Header.Get("X-Real-Ip") != "" {
		r.RemoteAddr = fetchIP(r.Header.Get("X-Real-Ip"))
		return
	}

	if r.Header.Get("True-Client-IP") != "" {
		r.RemoteAddr = fetchIP(r.Header.Get("True-Client-IP"))
		return
	}

	if r.Header.Get("CF-Connecting-IP") != "" {
		r.RemoteAddr = fetchIP(r.Header.Get("CF-Connecting-IP"))
	}
}